如何最好地在函数中初始化 python 的随机模块

How best to initialize python's random module within a function

我正在寻找一些关于当随机模块嵌入函数中时尽可能随机生成数字的信息,如下所示:

import random as rd

def coinFlip()
    flip = rd.random()

    if flip > .5: 
        return "Heads"
    else:
        return "Tails"

main()
    for i in range(1000000):
        print(coinFlip())

编辑:理想情况下,上面的脚本总是会产生不同的结果,因此限制了我使用 random.seed()

的能力

函数中嵌入的随机模块是否在每次调用函数时都使用新种子进行初始化? (而不是使用之前生成的随机数作为种子。)

如果是...

考虑到此处 for 循环中的系统时间非常接近甚至可能相同(取决于系统时间的精度),系统时间的默认初始化是否足够精确以提取真正的随机数。 )

有没有办法在函数外部初始化随机模块并让函数拉出下一个随机数(以避免多次初始化。)

还有其他更多 pythonic 的方法来完成这个吗?

非常感谢!

如果要初始化伪随机数生成器,请使用random.seed()

你可以看看here

If you don’t initialize the pseudo-random number generator using a random.seed (), internally random generator call the seed function and use current system current time value as the seed value. That’s why whenever we execute random.random() we always get a different value

如果你想总是有一个差异号,那么你不应该为初始化随机模块而烦恼,因为在内部,随机模块默认使用当前系统时间(它总是差异)。 只需使用:

from random import random 

def coinFlip()

    if random() > .5: 
        return "Heads"
    else:
        return "Tails"

更清楚一点,随机模块不会在每次使用时初始化,只会在导入时初始化,所以每次调用 random.random() 时都会得到下一个数字,保证是不同

初学者:

This module implements pseudo-random number generators for various distributions.

[..]

The functions supplied by this module are actually bound methods of a hidden instance of the random.Random class. You can instantiate your own instances of Random to get generators that don’t share state.

https://docs.python.org/3/library/random.html

random 模块是一个伪随机数生成器。所有 PRNG 都是完全确定的,并且具有 state。这意味着,如果 PRNG 处于相同状态,则下一个 "random" 数字将始终相同。如上段所述,您的 rd.random() 调用实际上是对隐式实例化 Random 对象的调用。

所以:

Does the random module embedded within a function initialize with a new seed each time the function is called?

没有

Is there a way to initialize a random module outside of the function and have the function pull the next random number (so to avoid multiple initializations.)

您不需要避免多重初始化,因为它不会发生。如果您想精确控制状态,您 可以 实例化您自己的 Random 对象。

class random.Random([seed])
Class that implements the default pseudo-random number generator used by the random module.

random.seed(a=None, version=2)
Initialize the random number generator. If a is omitted or None, the current system time is used. [..]

因此,隐式实例化的 Random 对象使用系统时间作为初始种子(尽管 read further),并从那里保持状态。因此,每次启动 Python 实例时,它的播种方式都会有所不同,但只会播种一次。