在Rcpp和R中生成相同的随机变量 [英] Generating same random variable in Rcpp and R

查看:390
本文介绍了在Rcpp和R中生成相同的随机变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将我的采样算法从R转换为Rcpp。 Rcpp和R的输出不匹配,Rcpp代码中有一些错误(由于随机化而差异并不相同)。我正在尝试将Rcpp的内部变量与R代码的内部变量进行匹配。然而,这是因为由于分发的采样器而导致的随机化问题。

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

如何使代码给出相同的输出R和Rcpp,我的意思是从R和Rcpp设置一个常见的种子?

解决方案

你在这里有一些问题: / p>


  1. rbinom(1,1,10)是废话,它得到你的警告信息:在rbinom(1,1,10)中:NAs生成了(我在这里加入了两行显示)。


  2. 你写了 rbinom(10,1,0.5),它将从二项式生成10个绘图,其中 p = 0.5 一个或者零个。


  3. 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:

  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.

这篇关于在Rcpp和R中生成相同的随机变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆