在Python的PRNG中植入tup

2024-09-29 21:35:04 发布

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

我注意到,如果我用一个元组来种子Python的PRNG,每次我都会得到不同的结果。也就是说,Python 3.4程序:

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

每次运行时打印一个不同的数字。这是因为所获取的种子是元组seed1id,每次都不同吗?在

使用元组作为PRNG种子的最佳方法是什么,这样我就能得到可重复的结果?只是random.seed(str(seed1))?在


Tags: 方法import程序idfoobar数字random
2条回答

有趣。在

如果您这样做:

def repeatable_random(seed):
    random.seed(seed)
    while True:
        yield random.random()

for i, v in zip(range(20), repeatable_random(('Foo', 'Bar'))):
    print((i,v))

每次运行随机序列时,会得到不同的值。在

如果您这样做:

^{pr2}$

在Python解释器的不同运行中,它是相同的series 1=>;n。在

从上一个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).

所以使用Python2.x时,运行hash('Foo', 'Bar')通常每次在同一台计算机上都会返回相同的结果,这会给您提供相同的初始种子。在python3.3+上,对元组运行hash,每次都会给您一个唯一的值。在

如果您想得到与python3.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

也就是说,你会有一个一致的种子,但是由于随机模块在它们的实现上有所不同,你仍然会得到一个不同的随机数。在

相关问题 更多 >

    热门问题