python随机设置状态(),seed()是否保证实现之间的结果相同?

2024-07-03 06:56:30 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有保证pyhon2/python3脚本在使用random.setstate()random.seed()初始化的随机生成器时,会在不同的版本和平台上产生相同的伪随机序列吗?(例如python 3.1 on Mac , the same as python 3.2 on Linux 64-bit

问题是关于两者的:python2和python3,假设python3脚本将在python3解释器上运行,反之亦然。在


Tags: the版本脚本onlinuxmacasbit
2条回答

python2.3及更高版本使用mersennetwister生成器,它独立于系统random函数(作为Python的C扩展模块实现)。对于使用Mersenne Twister的任何版本,在不同版本和平台上的结果应该是相同的。在

以前,您可以使用WichmannHill生成器来保证向后兼容性,但不幸的是,在python3.x中似乎已经删除了它

如果您绝对需要保证兼容性,请按照random文档的建议编写您自己的Random子类(或使用稳定的外部实现,例如simplerandom):

Class Random can also be subclassed if you want to use a different basic generator of your own devising: in that case, override the random(), seed(), getstate(), setstate() and jumpahead() methods. Optionally, a new generator can supply a getrandbits() method — this allows randrange() to produce selections over an arbitrarily large range.

您可以使用simplerandom模块,它具有独立于Python平台的一致实现。它支持Python2.4、2.5、2.6、2.7、3.1和3.2。它有9种不同的算法。在

下面是一个例子:

>>> import simplerandom.iterators as sri
>>> rng = sri.MWC1(12345)
>>> next(rng)
498186671L
>>> next(rng)
888940288L
>>> next(rng)
345072384L

只要使用相同的值进行种子设定,就会得到相同的结果:

^{pr2}$

相关问题 更多 >