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

其他回答

在生成一组随机数之前设置种子(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
>>> 

以下是我的理解。 每当我们设置一个种子值时,就会生成一个“标签”或“引用”。下一个随机。函数调用被附加到这个“标签”,所以下次你调用相同的种子值和随机。函数,会得到相同的结果。

np.random.seed( 3 )
print(np.random.randn()) # output: 1.7886284734303186

np.random.seed( 3 )
print(np.random.rand()) # different function. output: 0.5507979025745755

np.random.seed( 5 )
print(np.random.rand()) # different seed value. output: 0.22199317108973948

Imho,当你再次使用random.seed(samedigit)时,它被用来生成相同的随机课程结果。

In [47]: random.randint(7,10)

Out[47]: 9


In [48]: random.randint(7,10)

Out[48]: 9


In [49]: random.randint(7,10)

Out[49]: 7


In [50]: random.randint(7,10)

Out[50]: 10


In [51]: random.seed(5)


In [52]: random.randint(7,10)

Out[52]: 9


In [53]: random.seed(5)


In [54]: random.randint(7,10)

Out[54]: 9

随机的。python中的seed(a, version)用于初始化伪随机数生成器(PRNG)。

PRNG是一种生成近似于随机数性质的数列的算法。这些随机数可以使用种子值重新生成。因此,如果您提供种子值,PRNG将使用种子从任意的起始状态开始。

参数a是种子值。如果a值为None,则默认使用当前系统时间。

and version是一个整数,指定如何将参数a转换为整数。缺省值为2。

import random
random.seed(9001)
random.randint(1, 10) #this gives output of 1
# 1

如果你想要复制相同的随机数,那么再次提供相同的种子

random.seed(9001)
random.randint(1, 10) # this will give the same output of 1
# 1

如果你不提供种子,那么它会生成不同的数字,而不是之前的1

random.randint(1, 10) # this gives 7 without providing seed
# 7

如果你提供不同的种子,它会给你一个不同的随机数

random.seed(9002)
random.randint(1, 10) # this gives you 5 not 1
# 5

因此,总的来说,如果您希望复制相同的随机数,请提供种子。确切地说,是同一颗种子。

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