种子会在不同的Ruby中生成相同的随机序列吗? [英] Does seed generate same random sequence across different Rubys?
问题描述
假设我呼叫 srand(1234)
,然后反复呼叫 rand()
.无论我的环境如何,我都可以保证获得相同的随机数序列吗?
Suppose I call srand(1234)
, then call rand()
repeatedly. Am I guaranteed to get the same sequence of random numbers regardless of my environment?
例如
- Ruby 1.8.7 vs 1.9.3 vs 2.0
- MRI与JRuby
- Windows vs Mac vs Linux
推荐答案
根据我的经验,答案是是"
The answer in my experience is "yes"
在测试新宝石时,我也做同样的事情.gem尚不适合在现实世界中使用,但在很大程度上依赖于随机数,并且大多数测试都涉及事先运行Ruby的srand(),因此我得到了可预测的数字断言.总而言之,每次运行测试套件时,我可能都会测试由rand()生成的几百个小整数.
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:
在Windows上:MRI 1.9.3
On Windows: MRI 1.9.3
在Mac上:MRI 1.8.7,MRI 1.9.3和MRI 2.0.0
On Mac: MRI 1.8.7, MRI 1.9.3 and MRI 2.0.0
在Travis上(请参阅内部版本 https://travis-ci.org/neilslater/games_dice ),我将对所有这些内容进行测试:
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处于1.8模式
- jruby-19mode#1.9模式下的JRuby
- rbx-18mode
- rbx-19mode
最后两个我什至都不知道它们是什么:-)
The last two of which I don't even know what they are :-)
由于Ruby的 rand
方法中的数字意外,测试套件从未失败.
The test suite has never failed due to an unexpected number from Ruby's rand
method.
Ruby中的底层机制称为Mersenne Twister http://en.wikipedia.org/wiki/Mersenne_twister ,这将从相同的种子生成相同的值,即使是在实施该语言的不同语言中也是如此.据我所知,该算法是Ruby的 rand()
(和 srand()
)在所有标准实现中使用的算法.
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.
这篇关于种子会在不同的Ruby中生成相同的随机序列吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!