0

I am converting my sampling algorithm from R to Rcpp. Output of Rcpp and R are not matching there is some bug in the Rcpp code ( and the difference is not different because of randomization). I am trying to match internal variables of Rcpp with those from R code. However, this is problematic because of randomization due to sampler from distribution.

 Rcpp::rbinom(1, 1, 10) 
 rbinom(1, 1, 10)  

How can I make the code give same output in R and Rcpp, I mean setting a common seed from R and Rcpp?

vinash85
  • 431
  • 4
  • 15

1 Answers1

4

You are having a number of issues here:

  1. rbinom(1,1,10) is nonsense, it gets you 'Warning message: In rbinom(1, 1, 10) : NAs produced' (and I joined two lines here for display).

  2. So let's assume you wrote rbinom(10, 1, 0.5) which would generate 10 draws from a binomial with p=0.5 of drawing one or zero.

  3. Rcpp documentation is very clear about using the same RNGs, with the same seeding, via RNGScope objects which you get for free via Rcpp Attributes (see below).

So witness this (with an indentation to fit the first line here)

R> cppFunction("NumericVector cpprbinom(int n, double size, double prob) { \
      return(rbinom(n, size, prob)); }")
R> set.seed(42); cpprbinom(10, 1, 0.5)
 [1] 1 1 0 1 1 1 1 0 1 1
R> set.seed(42); rbinom(10,1,0.5)
 [1] 1 1 0 1 1 1 1 0 1 1
R> 

I define, compile, link and load a custom C++ function cpprbinom() here. I then set the seed, and retrieve 10 values. Resetting the seed and retrieving ten values under the same parameterisation gets the same values.

This will hold for all random distributions, unless we introduced a bug which can happen.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725