views:

137

answers:

4

I have C++ code that relies heavily on sampling (using rand()), but I want it to be reproducible. So in the beginning, I initialize srand() with a random seed and print that seed out. I want others to be able to run the same code again but initializing srand() with that same seed and get exactly the same answer as I did.

But under what circumstances is that guaranteed? I suppose that works only if the binaries are compiled with the same compiler on the same system? What are other factors that might make the answer differ from the one I got initially?

+2  A: 

You're correct that the sequences might be different if compiled on different machines with different rand implementations. The best way to get around this is to write your own PRNG. The Linux man page for srand gives the following simple example (quoted from the POSIX standard):

POSIX.1-2001 gives the following example of an implementation of rand() and srand(), possibly useful when one needs the same sequence on two different machines.

 static unsigned long next = 1;

 /* RAND_MAX assumed to be 32767 */
 int myrand(void) {
     next = next * 1103515245 + 12345;
     return((unsigned)(next/65536) % 32768);
 }

 void mysrand(unsigned seed) {
     next = seed;
 }
Tyler McHenry
Writing your own RNG is the last possible alternative you should consider. There is probably no other functionality it is so easy to get wrong and so difficult to test for correctness.
anon
A: 

To avoid this kind of problem, write your own implementation of rand()! I'm no expert on random-number generation algorithms, so I'll say no more than that...

Oli Charlesworth
Yeah, just solve again what thousands did before. That's the True C Programmer's approach. :P
Frank
+8  A: 

The solution is to use the same code in all cases - the Boost random number library is infinitely better than any C++ standard library implementation, and you can use the same code on all platforms. Take a look at this question for example of its use and links to the library docs.

anon
I see. So if I tell others to include the, say, Boost 1.42 random number generator that I used and initialize with the same seed that I used then they will get the exactly same result? Even on other platforms and using another compiler?
@dehmann Yes, that's correct.
anon
I'd add that it is correct only if you take the numbers in the same way everytime. Like another mentionned in the comments: if your using the same number generator for multiple threads, for exemple, the result might not be reproducible.
n1ck
A: 

Check out implementation of rand(), and use one of the random number generators from there - which ensures repeatability no matter what platform you run on.

Will A