Search code examples
c++randomsrand

How to eliminate all sources of randomness so that program always gives identical answers?


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?


Solution

  • 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.