【发布时间】:2016-07-18 23:16:00
【问题描述】:
在尝试从集合中选择伪随机元素时,我看到了不确定的行为,即使 RNG 已播种(示例代码如下所示)。为什么会发生这种情况,我是否应该期望其他 Python 数据类型显示出类似的行为?
注意:我只在 Python 2.7 上对此进行了测试,但它可以在两台不同的 Windows 计算机上重现。
类似问题:Python random seed not working with Genetic Programming example code 的问题可能类似。根据我的测试,我的假设是,集合内的 run-to-run 内存分配差异导致相同的 RNG 状态被拾取不同的元素。
到目前为止,我还没有在 Python 文档中发现任何关于 set 或 random 的警告/问题。
示例代码(randTest 产生不同的输出 run-to-run):
import random
''' Class contains a large set of pseudo-random numbers. '''
class bigSet:
def __init__(self):
self.a = set()
for n in range(2000):
self.a.add(random.random())
return
''' Main test function. '''
def randTest():
''' Seed the PRNG. '''
random.seed(0)
''' Create sets of bigSet elements, presumably many memory allocations. '''
b = set()
for n in range (2000):
b.add(bigSet())
''' Pick a random value from a random bigSet. Would have expected this to be deterministic. '''
c = random.sample(b,1)[0]
print('randVal: ' + str(random.random())) #This value is always the same
print('setSample: ' + str(random.sample(c.a,1)[0])) #This value can change run-to-run
return
【问题讨论】:
-
Python 3.5 具有相同的行为。
标签: python python-2.7 random set non-deterministic