Skip to main content
 首页 » 编程设计

python之用元组播种 Python 的 PRNG

2024年10月25日12cyq1162

我注意到,如果我用一个元组为 Python 的 PRNG 播种,每次我都会得到不同的结果。即Python 3.4程序:

import random 
seed1 = ('Foo', 'Bar') 
random.seed(seed1) 
print(random.random()) 

每次运行时打印不同的数字。这是因为取的种子是元组seed1的id每次都不一样吗?

使用元组作为 PRNG 种子以获得可重复结果的最佳方法是什么?它只是 random.seed(str(seed1)) 吗?

请您参考如下方法:

来自之前的question :

For Python 3.3+, as @gnibbler pointed out, hash() is randomized between runs. It will work for a single run, but almost definitely won't work across runs of your program (pulling from the text file you mentioned).

因此使用 python 2.x,每次运行 hash('Foo', 'Bar') 通常会在同一台计算机上返回相同的结果,这会为您提供相同的初始种子。在 python 3.3+ 上,对你的元组运行 hash 每次都会给你一个唯一的值。

如果你想获得与 python 3.3+ 一致的结果,请查看 hashlib。例如:

import hashlib 
import random 
 
seed1 = ('Foo', 'Bar') 
text  = u''.join(seed1).encode('utf-8') 
sha   = hashlib.sha1(text) 
random.seed(sha.hexdigest()) 
print(sha.hexdigest()) 
print(random.random()) 
 
> python3 random2.py  
eb8fc41f9d9ae5855c4d801355075e4ccfb22808 
0.738130097774164 
> python3 random2.py  
eb8fc41f9d9ae5855c4d801355075e4ccfb22808 
0.738130097774164 
 
> python2 random2.py  
eb8fc41f9d9ae5855c4d801355075e4ccfb22808 
0.628422839243 
> python2 random2.py  
eb8fc41f9d9ae5855c4d801355075e4ccfb22808 
0.628422839243 

即您将获得一致的种子,但由于随机模块的实现不同,您仍然会得到不同的随机数。