在Rcpp和R中生成相同的随机变量 [英] Generating same random variable in Rcpp and R
问题描述
Rcpp :: rbinom(1,1,10)
rbinom(1,1,10)
如何使代码给出相同的输出R和Rcpp,我的意思是从R和Rcpp设置一个常见的种子?
你在这里有一些问题: / p>
-
rbinom(1,1,10)
是废话,它得到你的警告信息:在rbinom(1,1,10)中:NAs生成了(我在这里加入了两行显示)。 -
你写了
rbinom(10,1,0.5)
,它将从二项式生成10个绘图,其中p = 0.5
一个或者零个。 -
Rcpp文档非常清楚,使用相同的RNG,通过
RNGScope
通过Rcpp属性获得免费的对象(见下文)。
所以见证这个在这里填充第一行的缩进)
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>
我定义,编译,链接和加载自定义C ++函数 cpprbinom()
这里。然后我设置种子,并检索10个值。重新设置种子并在相同的参数设置下检索十个值可获得相同的值。
这将适用于所有随机分布,除非我们引入可能发生的错误
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?
You are having a number of issues here:
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).So let's assume you wrote
rbinom(10, 1, 0.5)
which would generate 10 draws from a binomial withp=0.5
of drawing one or zero.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.
这篇关于在Rcpp和R中生成相同的随机变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!