gpt4 book ai didi

Python随机使用状态和种子?

转载 作者:太空宇宙 更新时间:2023-11-03 17:39:46 28 4
gpt4 key购买 nike

播种 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

最佳答案

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

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

关于Python随机使用状态和种子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30745014/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com