Search code examples
rrcpp

Poisson draw in Rcpp and R different results


I face the following contradiction when I use the same code in R and in Rcpp

In R I run the following code

t = 0
for(i in 1:50){
 t = t + rpois(1, 0.5)
}
t
[1] 28

and I take back a value t which is nonnegative. Now I type the exact same commands in Rcpp

#include <Rcpp.h>
#include<Rmath.h>
using namespace Rcpp;

// [[Rcpp::export]]
int Pois(int l){ 
  int t=0;
  for(int i=0; i<50;++i){
    t+=R::rpois(l);
  }
  return t;
}

and when I call the function in R

Pois(0.5)
[1] 0

which is wrong since in R it was different of zero

What is going wrong?


Solution

  • You should use double l rather than int l, e.g.,

    int Pois(double l){ 
      int t=0;
      for(int i=0; i<50;++i){
        t+=R::rpois(l);
      }
      return t;
    }
    

    otherwise (int) 0.5 gives you 0.