简体   繁体   English

在Rcpp和R中生成相同的随机变量

[英]Generating same random variable in Rcpp and R

I am converting my sampling algorithm from R to Rcpp. 我将采样算法从R转换为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). Rcpp和R的输出不匹配,因此Rcpp代码中存在一些错误(由于随机化,其差异也没有不同)。 I am trying to match internal variables of Rcpp with those from R code. 我正在尝试将Rcpp的内部变量与R代码中的变量进行匹配。 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? 如何使代码在R和Rcpp中提供相同的输出,我的意思是从R和Rcpp设置公共种子?

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). rbinom(1,1,10)是胡说八道,它会向您显示“警告消息:在rbinom(1,1,10)中:产生了NA”(我在此处加入了两行以进行显示)。

  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. 因此,假设您编写了rbinom(10, 1, 0.5) ,它将从二项式生成10个平局,其中p=0.5绘制一或零。

  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). Rcpp文档非常清楚地说明了通过RNGScope对象使用相同的RNG和相同的种子,您可以通过Rcpp属性免费获得它(请参见下文)。

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. 我在这里定义,编译,链接和加载自定义C ++函数cpprbinom() I then set the seed, and retrieve 10 values. 然后设置种子,并检索10个值。 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. 这将适用于所有随机分布,除非我们引入了可能发生的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM