Python 如何为梅森扭曲者播种

Gui*_*cci 5 python random

如果没有提供明确的种子值,Python 如何为内置随机库中使用的梅森扭曲伪随机数生成器提供种子?它以某种方式基于时钟吗?如果是,那么在导入随机模块或首次调用随机模块时是否找到了种子?

Python的文档似乎没有给出答案。

tom*_*tom 2

种子基于时钟或(如果可用)操作系统源。该模块在导入时(而不是首次使用时random)创建(并因此种子)共享实例。Random

参考

random.seed 的 Python 文档

random.seed(a=None, version=2)
Run Code Online (Sandbox Code Playgroud)

初始化随机数生成器。

如果省略 a 或 None,则使用当前系统时间。如果操作系统提供随机源,则使用它们而不是系统时间(有关可用性的详细信息,请参阅 os.urandom() 函数)。

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()
Run Code Online (Sandbox Code Playgroud)

最后一行位于顶层,因此在加载模块时执行。