尝试从集合中选择伪随机元素时,我看到了不确定的行为,即使已为RNG注入了种子(如下所示的示例代码)。为什么会发生这种情况,我是否应该期望其他Python数据类型显示类似的行为?
注意:我仅在Python 2.7上进行了测试,但是在两台不同的Windows计算机上都可以重现。
相似的问题:Python随机种子无法与遗传编程示例代码一起使用时的问题可能相似。根据我的测试,我的假设是,集合之间的运行间内存分配差异导致针对同一RNG状态拾取不同的元素。
迄今为止,我还没有在Python文档中找到关于set或random的这种警告/问题。
示例代码(randTest生成不同的运行结果):
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 …
Run Code Online (Sandbox Code Playgroud)