[Rcpp-devel] repeatable random numbers

Silkworth,David J. SILKWODJ at airproducts.com
Thu Sep 1 21:45:07 CEST 2011

RNGScope() mearly saves the state of the RNG for the R environment,
returning it upon class destruction at end of your (compiled) Rcpp

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) );	
int j=3;	
for(int i=0; i<NumRands; i++) {	
RandVals(i,j) = RandCol(i);	
return RandVals;	
 fun <- cxxfunction(signature(),	
 src, plugin = "Rcpp")	

>Message: 6
>Date: Thu, 1 Sep 2011 12:06:53 -0500
>From: Zhongyi Yuan <zhongyi-yuan at uiowa.edu>
>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
>that can be retrieved even after re-compilation. Can this done with

>Thanks for your help.


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20110901/4a55d1c0/attachment-0001.htm>

More information about the Rcpp-devel mailing list