Suppose I call srand(1234)
, then call rand()
repeatedly. Am I guaranteed to get the same sequence of random numbers regardless of my environment?
For instance,
- Ruby 1.8.7 vs 1.9.3 vs 2.0
- MRI vs JRuby
- Windows vs Mac vs Linux
Suppose I call srand(1234)
, then call rand()
repeatedly. Am I guaranteed to get the same sequence of random numbers regardless of my environment?
For instance,
The answer in my experience is "yes"
I do this exact same thing when testing a new gem. The gem is not ready for real-world use, but relies heavily on random numbers, and most of the tests involve running Ruby's srand() beforehand so I get predictable numbers for assertions. All in all I probably test a few hundred small integers generated by rand() every time I run the test suite.
So far I have tested:
On Windows: MRI 1.9.3
On Mac: MRI 1.8.7, MRI 1.9.3 and MRI 2.0.0
On Travis (see build https://travis-ci.org/neilslater/games_dice), I test all these:
The last two of which I don't even know what they are :-)
The test suite has never failed due to an unexpected number from Ruby's rand
method.
The underlying mechanism in Ruby is called the Mersenne Twister http://en.wikipedia.org/wiki/Mersenne_twister and this will generate same values from the same seeds, even across different languages, where it has been implemented. As far as I know, this algorithm is the one used by Ruby's rand()
(and srand()
) in all the standard implementations.
Well, this is what I get inside my irb - does it match what you get in yours? If so, then I think you can safely say "yes".
BTW, this is the whole point of seeding, so I expect the answer will definitely be "yes", and if not I'll be surprised.
ruby 1.9.3p327 (2012-11-10) [x86_64-darwin12.2.0]
irb(main):001:0> srand(1234)
=> 312936473923896776645464224839555650313
irb(main):002:0> rand
=> 0.1915194503788923
irb(main):003:0> rand
=> 0.6221087710398319
irb(main):004:0> rand
=> 0.4377277390071145
irb(main):006:0> rand
=> 0.7853585837137692
irb(main):007:0> rand
=> 0.7799758081188035