简体   繁体   English

如果先前生成的值被显式设置为新种子,为什么Python random.random()会给出不同的值?

[英]Why does the Python random.random() give a different value if the previously generated value is explicitly set as the new seed?

I have read that the random module in Python uses the previously generated value as the seed except for the first time where it uses the system time. 我已经读到Python中的random模块使用先前生成的值作为种子,但第一次使用系统时间除外。 ( https://stackoverflow.com/a/22639752/11455105 , https://pynative.com/python-random-seed/ ) If this is true, why don't I get the same value when I explicitly set the previously generated value as the new seed like this: https://stackoverflow.com/a/22639752/11455105https://pynative.com/python-random-seed/ )如果这是真的,为什么我没有拿到相同的值时,我明确设置之前产生价值,就像这样的新种子:

random.seed(random.randint(1, 100))

The same doesn't work for the random.random() method either. 对于random.random()方法而言,这也不起作用。

>>> import random
>>> random.seed(20)
>>> random.randint(1,100)
93
>>> random.randint(1,100)
88
>>> random.seed(20)
>>> random.randint(1,100)
93
>>> random.randint(1,100)
88
>>> random.seed(20)
>>> random.seed(random.randint(1,100))
>>> random.randint(1,100)
64

Why didn't the last randint() call not give 88? 为什么最后一个randint()调用不给出88?

Thanks in Advance! 提前致谢!

Because what you read was false, or you misunderstood what it said. 因为您读到的是错误的,或者您误解了它的意思。 CPython uses the Mersenne Twister generator under the covers, which has a state consuming 19937 bits. CPython在后台使用Mersenne Twister生成器,该生成器占用状态19933位。 What you pass to .seed() is not the new state, but merely a pile of bits which is expanded to a full 19937-bit state via an undocumented (implementation-dependent) algorithm. 您传递给.seed()不是新状态,而是一堆位,它通过未记录的(依赖于实现)算法扩展为完整的19937位状态。

Note: if you want to save and restore states, that's what the .getstate() and .setstate() methods are for. 注意:如果要保存和恢复状态,那就是.getstate().setstate()方法的作用。

Python random module does not use the previously generated value as the seed. Python random模块不使用先前生成的值作为种子。 However, Python uses the Mersenne Twister generator to create pseudo-randomness. 但是,Python使用Mersenne Twister生成器来创建伪随机性。 This algorithm is deterministic : that implies that it next state (the next generated number) depends on the previous one. 该算法是确定性的 :这意味着它的下一个状态(下一个生成的数字)取决于上一个。 This is different from the seed which is a value used to configure the initial state of the generator. 这与种子不同,后者是用于配置生成器初始状态的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM