Creating the same random variable in Rcpp and R

I am converting my fetch algorithm from R to Rcpp. The output of Rcpp and R does not match, there is some error in the Rcpp code (and the difference is no different due to randomization). I am trying to map Rcpp internal variables to data from R code. However, this is problematic due to randomization due to the selector from the distribution.

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

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

0
source share
1 answer

Here you have a few problems:

  • rbinom(1,1,10) is nonsense, it receives the message “Warning: in rbinom (1, 1, 10): NA produced” (and I joined the two lines here to display).

  • So, suppose you wrote rbinom(10, 1, 0.5) , which will generate 10 draws from a binomial with p=0.5 to draw one or zero.

  • The Rcpp documentation very clearly describes the use of the same RNG with the same seeding through the RNGScope objects that you get for free through the Rcpp attributes (see below).

So make sure of this (indented for 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 the C ++ custom function cpprbinom() here. Then I set the seed and extract 10 values. Flushing a seed and getting ten values ​​under the same parameterization get the same value.

This will be true for all random distributions unless we imagine an error that might occur.

+4
source

All Articles