Python如何播种其Mersenne twister伪随机数生成器?它是基于时钟的某种方式?如果是这样,是在导入随机模块时还是在第一次调用它时找到种子?
Python的文档似乎没有答案。
答案 0 :(得分:3)
在现代版本的python(c.f。http://svn.python.org/projects/python/branches/release32-maint/Lib/random.py)中,Random.seed尝试使用从/ dev / urandom读取的32个字节。如果这不起作用,则使用当前时间:(a
是一个可选值,可用于显式播种PRNG。)
if a is None:
try:
a = int.from_bytes(_urandom(32), 'big')
except NotImplementedError:
import time
a = int(time.time() * 256) # use fractional seconds
答案 1 :(得分:2)
从answer开始,我找到了random.py的来源。在Random类中,在构造对象时设置种子。该模块实例化一个Random对象,并将其用于所有模块方法。因此,如果使用random.random()
或其他模块方法生成随机数,则在导入时设置种子。如果随机数是由另一个Random实例产生的,则种子是在构造该实例时设置的。
来自消息来源:
# Create one instance, seeded from current time, and export its methods
# as module-level functions. The functions share state across all uses
#(both in the user's code and in the Python libraries), but that's fine
# for most programs and is easier for the casual user than making them
# instantiate their own Random() instance.
答案 2 :(得分:2)
种子基于时钟或(如果可用)操作系统源。 random
模块在导入时创建(并因此播种)共享Random
实例,而不是在第一次使用时。
<强>参考强>
random.seed(a=None, version=2)
初始化随机数生成器。
如果省略a或None,则使用当前系统时间。如果操作系统提供随机源,则使用它们 而不是系统时间(有关详细信息,请参阅os.urandom()函数 可用性)。
Source of random.py(严重抨击):
from os import urandom as _urandom
class Random(_random.Random):
def __init__(self, x=None):
self.seed(x)
def seed(self, a=None, version=2):
if a is None:
try:
a = int.from_bytes(_urandom(32), 'big')
except NotImplementedError:
import time
a = int(time.time() * 256) # use fractional seconds
# Create one instance, seeded from current time, and export its methods
# as module-level functions. The functions share state across all uses
#(both in the user's code and in the Python libraries), but that's fine
# for most programs and is easier for the casual user than making them
# instantiate their own Random() instance.
_inst = Random()
最后一行位于顶层,因此在加载模块时执行。