Skip to content
Prev 51686 / 63421 Next

rmultinom.c error probability not sum to 1

Hi all, 

I should have given a better explanation of my problem. Here it is.

I extracted from my code the bit that gives the error. Place this in a file called test.c

#include <math.h>
#include <R.h>
#include <Rmath.h>
#include <float.h>
#include <R_ext/Print.h>

int main(){

  double prob[3] = {0.0, 0.0, 0.0};
  double prob_tot = 0.;

  prob[0] = 0.3*dnorm(2, 0, 1, 0);
  prob[1] = 0.5*dnorm(5, 0, 1, 0);
  prob[2] = 0.2*dnorm(-3, 0, 1, 0);

  //obtain prob_tot
  prob_tot = 0.;
  for(int j = 0; j < 3; j++)
    prob_tot += prob[j];

  //normalize probabilities
  for(int j = 0; j < 3; j++)
    prob[j] = prob[j]/prob_tot;

  //or this give the same error
  //prob[2] = 1.0 - prob[1] - prob[0];

  //checking indeed prob_tot not exactly 1
  for(int j = 0; j < 3; j++)
    prob_tot += prob[j];

  Rprintf("Prob_tot: %f\n", prob_tot);

  int rN[3];
  rmultinom(1, prob, 1, rN);
  return 0;
}
 
run R CMD SHLIB test.c to generate the test.so. Now from within R
Prob_tot: 1.017084
Error: rbinom: probability sum should be 1, but is 0.948075

Maybe I miss some trivial C knowledge why this is not exactly one!

Thanks in advance!

Regards, 
Maarten