RNGScope() mearly saves the state of the RNG for the R environment,
returning it upon class destruction at end of your (compiled) Rcpp
function.
You can pass a seed to your Rcpp function as an argument and, after
preserving state with RNGScope(), you can set the seed within the Rcpp
function for this repeatable capability. I did this in an example that
I listed here a couple of months ago using the environment facility to
call R's set.seed command.
src <- '
Rcpp::RNGScope Scope;
Environment base("package:base");
Function SetSeed = base["set.seed"];
int NumRands = 5;
int NumTrials = 3;
Rcpp::NumericVector RandCol(NumRands);
Rcpp::NumericMatrix RandVals(NumRands, NumTrials*2);
SetSeed(Named("seed",20) );
RandCol=rnorm(NumRands,2,1);
int j=3;
for(int i=0; i<NumRands; i++) {
RandVals(i,j) = RandCol(i);
}
return RandVals;
'
fun <- cxxfunction(signature(),
src, plugin = "Rcpp")
test_fun<-fun()
>Message: 6
>Date: Thu, 1 Sep 2011 12:06:53 -0500
>From: Zhongyi Yuan <[email protected]>
>Subject: [Rcpp-devel] repeatable random numbers
>Hello everyone,
>I am conducting some numerical studies that I want to be repeatable. In
>other words, I want others who run my code to get exactly the same
result as
>I get.
>This can be easily done in pure R.
>But since I want the random number generation in Cpp, I think I need a
seed
>that can be retrieved even after re-compilation. Can this done with
>RNGScope?
>Thanks for your help.
>Best,
>Zhongyi
_______________________________________________
Rcpp-devel mailing list
[email protected]
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel