为什么在Python版本之间播种随机生成器不稳定? [英] Why is seeding the random generator not stable between versions of Python?

查看:142
本文介绍了为什么在Python版本之间播种随机生成器不稳定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在安装了不同python3版本的不同系统上从python random.random()再现随机序列.

I am trying to reproduce a random sequence from python's random.random() on a different system with a different python3 version installed.

这应该很容易,因为文档说:

大多数随机模块的算法和种子函数是 可能会因Python版本而异,但有两个方面 保证不更改:

Most of the random module’s algorithms and seeding functions are subject to change across Python versions, but two aspects are guaranteed not to change:

  • 如果添加了新的播种方法,则向后兼容的播种器 将提供.
  • 生成器的random()方法将继续 当兼容的播种机被赋予相同的序列时,产生相同的序列 种子.
  • If a new seeding method is added, then a backward compatible seeder will be offered.
  • The generator’s random() method will continue to produce the same sequence when the compatible seeder is given the same seed.

因此,我希望以下代码始终打印相同的10个数字,而不管特定的python3版本如何:

So I expect the following code to print always the same 10 numbers, no matter the specific python3 version:

import sys
print(sys.version)

from random import seed, random

seed(str(1))
for i in range(10):
    print(random())

但是,请在两台不同的计算机上对其进行测试:

However, testing it on two different machines:

3.2.3 (default, May  3 2012, 15:51:42) 
[GCC 4.6.3]
0.4782479962566343
0.044242767098090496
0.11703586901195051
0.8566892547933538
0.2926790185279551
0.0067328440779825804
0.0013279506360178717
0.22167546902173108
0.9864945747444945
0.5157002525757287

3.1.2 (release31-maint, Dec  9 2011, 20:59:40)  
[GCC 4.4.5]
0.0698436845523
0.27772471476
0.833036057868
0.35569897036
0.36366158783
0.722487971761
0.963133581734
0.263723867191
0.451002768569
0.0998765577881

给出不同的结果.

这是为什么?还有什么方法可以使它起作用(即两次获得相同的随机序列?)

Why is this? And is there any way to make this to work (i.e. get the same random sequence twice?)

推荐答案

我正在浏览 Python 3.2的新功能(由于这个问题),我发现:

I was looking through What's New in Python 3.2 (because of this question), and I found:

random.seed()函数和方法 now 具有sha512哈希函数的盐串种子.要访问先前版本的种子以重现Python 3.1序列,请将version参数设置为1,random.seed(s,version = 1).

The random.seed() function and method now salt string seeds with an sha512 hash function. To access the previous version of seed in order to reproduce Python 3.1 sequences, set the version argument to 1, random.seed(s, version=1).

这似乎是一项重大突破(从3.1到3.2),并具有向后兼容选项.

It appears to be a breaking change (from 3.1 to 3.2) with a backwards compatibility option.

(正如可怕的指出的那样,因为没有违反兼容的播种机 ,因此没有违反文档合同.)

(As borrible pointed out, because a compatible seeder is offered the documentation contract has not been violated.)

这篇关于为什么在Python版本之间播种随机生成器不稳定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆