Does seed generate same random sequence across different Rubys?

眉间皱痕 提交于 2019-12-24 10:59:20

问题


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

回答1:


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:

  • "1.8.7"
  • "1.9.3"
  • "2.0.0"
  • jruby-18mode # JRuby in 1.8 mode
  • jruby-19mode # JRuby in 1.9 mode
  • rbx-18mode
  • rbx-19mode

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.




回答2:


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


来源:https://stackoverflow.com/questions/15974284/does-seed-generate-same-random-sequence-across-different-rubys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!