Python随机使用状态和种子?

Python随机使用状态和种子?,python,random,random-seed,Python,Random,Random Seed,植入Python的内置(伪)随机数生成器将允许我们在每次使用该种子时获得相同的响应--。我听说保存生成器的内部状态可以减少重复先前输入值的可能性。这有必要吗?也就是说,为了在每次使用“foo”种子时获得相同的结果,是否不需要下面代码中的getState()和setState() 否,设置种子或状态已足够: import random # set seed and get state random.seed(0) orig_state = random.getstate() print ran

植入Python的内置(伪)随机数生成器将允许我们在每次使用该种子时获得相同的响应--。我听说保存生成器的内部状态可以减少重复先前输入值的可能性。这有必要吗?也就是说,为了在每次使用
“foo”
种子时获得相同的结果,是否不需要下面代码中的
getState()
setState()


否,设置种子或状态已足够:

import random

# set seed and get state
random.seed(0)
orig_state = random.getstate()

print random.random()
# 0.8444218515250481

# change the RNG seed
random.seed(1)
print random.random()
# 0.13436424411240122

# setting the seed back to 0 resets the RNG back to the original state
random.seed(0)
new_state = random.getstate()
assert new_state == orig_state

# since the state of the RNG is the same as before, it will produce the same
# sequence of pseudorandom output
print random.random()
# 0.8444218515250481

# we could also achieve the same outcome by resetting the state explicitly
random.setstate(orig_state)
print random.random()
# 0.8444218515250481

通过编程设置种子通常比显式设置RNG状态更方便。

设置任何种子或状态足以使随机化重复。不同之处在于,种子可以在代码中任意设置,就像在您的示例中一样,使用
“foo”
,而
getstate()
setstate()
可以两次获得相同的随机序列,而序列仍然是不确定的

伪随机数生成器的行为总是确定性的,无论您设置的是种子还是状态。如果您考虑到伪随机性,是的。但对于用户来说,使用不可观察且不可预测的变量作为种子(例如,以毫秒为单位的时间)意味着结果是意外的。这就是我所说的不确定性。
import random

# set seed and get state
random.seed(0)
orig_state = random.getstate()

print random.random()
# 0.8444218515250481

# change the RNG seed
random.seed(1)
print random.random()
# 0.13436424411240122

# setting the seed back to 0 resets the RNG back to the original state
random.seed(0)
new_state = random.getstate()
assert new_state == orig_state

# since the state of the RNG is the same as before, it will produce the same
# sequence of pseudorandom output
print random.random()
# 0.8444218515250481

# we could also achieve the same outcome by resetting the state explicitly
random.setstate(orig_state)
print random.random()
# 0.8444218515250481