Generating same random variable in Rcpp and R

◇◆丶佛笑我妖孽 提交于 2019-12-13 04:37:29

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/20646666/generating-same-random-variable-in-rcpp-and-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!