[Rcpp-devel] RInside constructor calls srand

Dirk Eddelbuettel edd at debian.org
Sun Nov 6 16:22:44 CET 2011


On 6 November 2011 at 01:18, Joseph Xu wrote:
| Hi Dirk:
| 
| Thanks for the quick reply.
| 
| On Sat, Nov 5, 2011 at 11:06 PM, Dirk Eddelbuettel <edd at debian.org> wrote:
| 
| > Also, RInside embeds R. And just as in normal R, if you want reproducibility
| > from the embedded R provided by RInside, you need set.seed(). Just use it.
| 
| I tried something like this:
| 
| #include <stdlib.h>
| #include <iostream>
| #include <Rcpp.h>
| #include <RInside.h>
| 
| using namespace std;
| 
| int main() {
| 	srand(1);

That random number generator comes from the OS and has nothing to do with R !

| 	RInside r(0, NULL);
| 	r.parseEvalQ("set.seed(0)");

That sets R's seed.

| 	cout << rand() << endl;

That calls a different RNG.

| 	return 0;
| }
| 
| But every time I run the program, I get a different random number. Am
| I missing something?

I now see where you are coming from. Adding 'RInside' to an existing program
alters the (non-R-generated) random number stream of that program.  Is that
correct?

In that case the sequence 

	RInside r(0, NULL);
	srand(1);
	r.parseEvalQ("set.seed(0)");
	cout << rand() << endl;
	return 0;

may work as you now fix the RNG you care about (from the C library) after
setting up RInside.

In any event, most of us here are concerned about using _R's RNG_ and what we
do with Rcpp and RInside ensures that "yes you can" use those without side
effect.  See the discussesion about RNGScope in the docs and the mailing list
archives. 
 
| > "Outside of a dog, a book is a man's best friend. Inside of a dog, it is too
| > dark to read." -- Groucho Marx
| >
| Love the signature.

:)

Dirk 
 
| Joseph

-- 
"Outside of a dog, a book is a man's best friend. Inside of a dog, it is too
dark to read." -- Groucho Marx


More information about the Rcpp-devel mailing list