[Rcpp-devel] Setting R seed from Cpp (continued)

Matteo Fasiolo matteo.fasiolo at gmail.com
Mon Jun 10 19:52:24 CEST 2013


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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20130610/0c9f1c6d/attachment.html>


More information about the Rcpp-devel mailing list