我对random.seed()在Python中的作用有点困惑。例如,为什么下面的试验会(始终如一地)做它们所做的事情?

>>> import random
>>> random.seed(9001)
>>> random.randint(1, 10)
1
>>> random.randint(1, 10)
3
>>> random.randint(1, 10)
6
>>> random.randint(1, 10)
6
>>> random.randint(1, 10)
7

我找不到关于这方面的好的文件。


当前回答

Seed() can be used for later use ---

Example:
>>> import numpy as np
>>> np.random.seed(12)
>>> np.random.rand(4)
array([0.15416284, 0.7400497 , 0.26331502, 0.53373939])
>>>
>>>
>>> np.random.seed(10)
>>> np.random.rand(4)
array([0.77132064, 0.02075195, 0.63364823, 0.74880388])
>>>
>>>
>>> np.random.seed(12) # When you use same seed as before you will get same random output as before
>>> np.random.rand(4)
array([0.15416284, 0.7400497 , 0.26331502, 0.53373939])
>>>
>>>
>>> np.random.seed(10)
>>> np.random.rand(4)
array([0.77132064, 0.02075195, 0.63364823, 0.74880388])
>>>

其他回答

下面是一个小测试,演示了给seed()方法注入相同的参数将导致相同的伪随机结果:

# testing random.seed()

import random

def equalityCheck(l):
    state=None
    x=l[0]
    for i in l:
        if i!=x:
            state=False
            break
        else:
            state=True
    return state


l=[]

for i in range(1000):
    random.seed(10)
    l.append(random.random())

print "All elements in l are equal?",equalityCheck(l)

所有其他答案似乎都不能解释random.seed()的使用。 下面是一个简单的例子(来源):

import random
random.seed( 3 )
print "Random number with seed 3 : ", random.random() #will generate a random number 
#if you want to use the same random number once again in your program
random.seed( 3 )
random.random()   # same random number as before
# Simple Python program to understand random.seed() importance

import random

random.seed(10)

for i in range(5):    
    print(random.randint(1, 100))

多次执行上面的程序…

第一次尝试:输出5个范围为1 ~ 100的随机整数

第二次尝试:打印相同的5个随机数字出现在上面的执行。

第三次尝试:相同

…等等

解释:每次运行上述程序时,我们都将seed设置为10,然后随机生成器将其作为参考变量。然后用一些预定义的公式,生成一个随机数。

因此,在下次执行时将seed设置为10,再次将引用号设置为10,然后再次启动相同的行为…

只要我们重置种子值,它就会给出相同的植物。

注意:改变种子值并运行程序,你会看到一个与前一个不同的随机序列。

在这种情况下,随机实际上是伪随机。给定一颗种子,它将产生具有均匀分布的数字。但是使用相同的种子,它每次都会生成相同的数字序列。如果你想改变它,你就必须改变你的种子。很多人喜欢根据当前时间或其他东西来生成种子。

在生成一组随机数之前设置种子(x),并使用相同的种子生成相同的随机数集。在重现问题的情况下很有用。

>>> from random import *
>>> seed(20)
>>> randint(1,100)
93
>>> randint(1,100)
88
>>> randint(1,100)
99
>>> seed(20)
>>> randint(1,100)
93
>>> randint(1,100)
88
>>> randint(1,100)
99
>>>