Python随机使用状态和种子?

时间:2015-06-10 00:14:29

标签: python random random-seed

播种Python的内置(伪)随机数生成器将允许我们在每次使用该种子时获得相同的响应 - documentation here。而且我听说保存发生器的内部状态降低了重复先前输入值的可能性。这有必要吗?也就是说,下面代码中的getState()setState()是不必要的,以便每次与"foo"一起播种时获得相同的结果?

import random
...
state = random.getstate()
random.seed("foo")
bitmap = random.sample(xrange(100), 10)
random.setstate(state)
return bitmap

2 个答案:

答案 0 :(得分:1)

不,设置种子或状态就足够了:

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状态更方便。

答案 1 :(得分:0)

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