When does using RNGScope make a difference?

落爺英雄遲暮 提交于 2019-11-29 04:40:33

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
}

Note the automatic construction of the RNGScope object.

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

This all becomes a little clearer once you read the original documentation in the Writing R Extensions manual, Section 6.3, "Random Numbers".

All that RNGScope scope does is the automagic calls to "get" and "put" in order to keep the state of the RNG sane.

The problem with your test code, as explained by Kevin, is that it already happens for you. So you can only test by going through .Call() by hand, in which case you will for sure leave the RNG in a mess if you use it and do not get/put properly.

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