小编Ama*_*629的帖子

种子Python RNG显示带有集合的非确定性行为

尝试从集合中选择伪随机元素时,我看到了不确定的行为,即使已为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)

python random set non-deterministic python-2.7

5
推荐指数
1
解决办法
397
查看次数

标签 统计

non-deterministic ×1

python ×1

python-2.7 ×1

random ×1

set ×1