[Rcpp-devel] Setting R seed from Cpp (continued)
Simon Zehnder
szehnder at uni-bonn.de
Mon Jun 10 20:22:03 CEST 2013
Hi Matteo,
this is an interesting post. My assumption is, that as in the first approach you call an R function which is implemented as a pointer (or reference to an R function) this function always has access to the RNG scope. Whereas in the second approach you call nested, which is a CPP-function that implicitly calls the R function (via the R namespace in Rcpp I think). In this case the RNG scope is not accessible and must be made accessible via a further 'RNGScope;' in the function 'nested'. What happens if you do this?
Best
Simon
On Jun 10, 2013, at 7:52 PM, Matteo Fasiolo <matteo.fasiolo at gmail.com> wrote:
> Hi all,
>
> I continued experimenting with setting the R seed from an
> Rcpp function. While this code works:
>
> cppFunction('
>
> List myFun(int n, Function foo)
> {
> RNGScope scope;
>
> Environment g = Environment::global_env();
> Environment::Binding RandomSeed = g[".Random.seed"];
> IntegerVector someVariable = RandomSeed;
>
> NumericVector output1(n);
> NumericVector output2(n);
>
> output1 = foo(n);
>
> RandomSeed = someVariable;
> output2 = foo(n);
>
> return List::create(output1, output2);
> }
>
> ')
>
> myRnorm <- function(n)
> {
> rnorm(n)
> }
>
> set.seed(524514)
> myFun(10, myRnorm)
>
> [[1]]
> [1] -0.46949481 -0.40449904 1.10377225 -0.94267114 0.71828154 0.44722386 -0.04653023 0.49021681 -0.68894641
> [10] 0.15505136
>
> [[2]]
> [1] -0.46949481 -0.40449904 1.10377225 -0.94267114 0.71828154 0.44722386 -0.04653023 0.49021681 -0.68894641
> [10] 0.15505136
>
> If I put another layer of C++:
>
>
> cppFunction('
> NumericVector nested(int n)
> {
> return rnorm(n);
> }
> ')
>
> myRnorm <- function(n)
> {
> nested(n)
> }
>
> set.seed(524514)
> myFun(10, myRnorm)
>
> [[1]]
> [1] -0.46949481 -0.40449904 1.10377225 -0.94267114 0.71828154 0.44722386 -0.04653023 0.49021681 -0.68894641
> [10] 0.15505136
>
> [[2]]
> [1] -1.58817318 0.32828207 0.01351185 -0.28672471 0.51732449 -0.10360312 0.97944543 -0.16814832 -0.83571146
> [10] -0.43258866
>
> This doesn't work any more. Luckily I listened to Dirk's warning about messing with R RNG,
> because this strange "sandwich" (C++ calls R calls C++) is pretty much what I was going to
> do in my application.
>
> Matteo
>
>
>
> _______________________________________________
> Rcpp-devel mailing list
> Rcpp-devel at lists.r-forge.r-project.org
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20130610/5f68a654/attachment.html>
More information about the Rcpp-devel
mailing list