何时使用 RNGScope 会有所作为? [英] When does using RNGScope make a difference?

查看:46
本文介绍了何时使用 RNGScope 会有所作为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Rcpp 文档中,我经常发现建议在 Rcpp 中使用随机抽取之前放置 Rcpp::RNGScope scope;.我想知道这到底是做什么的,因为我只看到它被描述为确保 RNG 状态被设置/重置".

In Rcpp documentation, I often find the recommendation to place Rcpp::RNGScope scope; before using random draws within Rcpp. I wondered what exactly this does, because I've only ever seen it described as "ensures RNG state gets set/reset".

然后,我进行了一些测试,但我似乎无法想出一个示例来说明这样做有何不同.我使用了 这里.我的测试是:

Then, I tested a bit, but I can't seem to come up with an example where doing this makes any difference. I used an example from here. My tests were:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
NumericVector noscope() {
  Rcpp::Function rt("rt");
   return rt(5, 3);
}

// [[Rcpp::export]]
NumericVector withscope() {
   RNGScope scope;
   Rcpp::Function rt("rt");
   return rt(5, 3);
}

然后

set.seed(45)
noscope() # [1]  0.6438 -0.6082 -1.9710 -0.1402 -0.6482

set.seed(45)
withscope() # [1]  0.6438 -0.6082 -1.9710 -0.1402 -0.6482

set.seed(45)
rt(5, 3) # [1]  0.6438 -0.6082 -1.9710 -0.1402 -0.6482

所以,我的问题是双重的.首先,RNGScope 什么时候有所作为,它与不使用它究竟有何不同?其次,有没有人有一个代码示例,显示有和没有它的不同结果?

So, my question is twofold. First, when does RNGScope make a difference, and what exactly does it do different from not using it? Second, does anyone have a code example which shows different results with and without it?

如果 RNGScope 在较新的版本中被弃用,那么我很抱歉问这个问题.

If RNGScope was deprecated in a newer release, then I'm sorry for asking.

推荐答案

当使用 Rcpp 属性时,自动生成的代码接口将自动插入 RNGScope 对象的适当构造——所以它是在这种情况下,已经在幕后为您完成了.例如,如果您编写 sourceCpp(..., verbose = TRUE),您将看到如下输出:

When using Rcpp attributes, the automagically generated interface to your code will automatically insert the appropriate construction of the RNGScope object -- so it's already being done for you behind the scenes in this case. For example, if you write sourceCpp(..., verbose = TRUE), you'll see output like this:

Generated extern "C" functions 
--------------------------------------------------------


#include <Rcpp.h>

RcppExport SEXP sourceCpp_38808_timesTwo(SEXP xSEXP) {
BEGIN_RCPP
    Rcpp::RObject __result;
    Rcpp::RNGScope __rngScope;
    Rcpp::traits::input_parameter< NumericVector >::type x(xSEXP);
    __result = Rcpp::wrap(timesTwo(x));
    return __result;
END_RCPP
}

注意 RNGScope 对象的自动构造.

Note the automatic construction of the RNGScope object.

如果您在 Rcpp 属性范围之外进行操作,则只需手动构造该对象.

You only need to construct that object manually if you are operating outside of the realm of Rcpp attributes.

这篇关于何时使用 RNGScope 会有所作为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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