[Rcpp-devel] repeatable random numbers

Dirk Eddelbuettel edd at debian.org
Thu Sep 1 19:13:34 CEST 2011


On 1 September 2011 at 12:06, Zhongyi Yuan wrote:
| 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?

Yes you can set a seed the same way, see 'Writing R Extensions'.  We hook
into the same C API for R's RNG as ... R itself does.

Trivial example:


R> require(inline)
Loading required package: inline
R> rngs <- cxxfunction(signature(), plugin="Rcpp", body="return Rcpp::rnorm(5,0,1);")
R> set.seed(42)
R> rngs()
[1]  1.370958 -0.564698  0.363128  0.632863  0.404268
R> rngs()
[1] -0.1061245  1.5115220 -0.0946590  2.0184237 -0.0627141
R> set.seed(42)
R> rnorm(5)
[1]  1.370958 -0.564698  0.363128  0.632863  0.404268
R> rnorm(5)
[1] -0.1061245  1.5115220 -0.0946590  2.0184237 -0.0627141
R> 

So both draws get you the _exact same numbers_ as we reset the RNG state to
the same starting point.

Dirk
 
| Thanks for your help.
| 
| Best,
| Zhongyi
|  
| 
| ----------------------------------------------------------------------
| _______________________________________________
| 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

-- 
Two new Rcpp master classes for R and C++ integration scheduled for 
New York (Sep 24) and San Francisco (Oct 8), more details are at
http://dirk.eddelbuettel.com/blog/2011/08/04#rcpp_classes_2011-09_and_2011-10
http://www.revolutionanalytics.com/products/training/public/rcpp-master-class.php


More information about the Rcpp-devel mailing list