我对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])
>>>

其他回答

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

# 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
>>> 

一个随机数是通过对前一个值进行操作而生成的。

如果没有之前的值,则当前时间将自动作为之前的值。我们可以使用random.seed(x)提供之前的值,其中x可以是任何数字或字符串等。

因此random.random()实际上不是完美随机数,它可以通过random.seed(x)来预测。

import random 
random.seed(45)            #seed=45  
random.random()            #1st rand value=0.2718754143840908
0.2718754143840908  
random.random()            #2nd rand value=0.48802820785090784
0.48802820785090784  
random.seed(45)            # again reasign seed=45  
random.random()
0.2718754143840908         #matching with 1st rand value  
random.random()
0.48802820785090784        #matching with 2nd rand value

因此,生成随机数实际上不是随机的,因为它是通过算法运行的。算法总是基于相同的输入给出相同的输出。这意味着,它取决于种子的价值。因此,为了使它更随机,时间被自动分配给seed()。

所有其他答案似乎都不能解释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