2015-06-10 64 views
1

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

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

回答

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状态做编程。

0

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

+0

伪随机数生成器将始终表现确定性,无论您设置种子还是状态 –

+0

如果考虑到伪随机性,是的。但是,对于使用不可观测和不可预测的变量作为种子的用户(例如,以毫秒为单位的时间)意味着结果是意外的。这就是我的非确定性意思。 – hajtos