python random.getstate()和random.setstate() [英] python random.getstate() and random.setstate()

查看:561
本文介绍了python random.getstate()和random.setstate()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是随机学习模块的,一开始就有簿记功能,我知道设置一个特定的种子就是要确保获得相同的随机数.

Learning the module random here, in the very beginning there are book-keeping functions, I understand that to set a specific seed is to make sure obtaining same random number.

但是getstate()setsate()呢? 链接 在文档中,没有介绍此状态的含义,如果我不知道它的含义,该如何设置呢?

but, what about the getstate() and setsate()? link In the documentation, it has no introduction for what this state means, and if I don't know what it means, how could I set it right?

random.getstate()

random.getstate()

返回一个捕获当前对象内部状态的对象 发电机.可以将此对象传递给setstate()来还原 状态.

Return an object capturing the current internal state of the generator. This object can be passed to setstate() to restore the state.

random.setstate(state)

random.setstate(state)

state应该是从先前对getstate()的调用中获得的, 和setstate()将生成器的内部状态恢复为 是在调用getstate()的时候.

state should have been obtained from a previous call to getstate(), and setstate() restores the internal state of the generator to what it was at the time getstate() was called.

谢谢

推荐答案

为什么不尝试一下?

import random

random.seed(42)

print(random.sample(range(20),k=10))

st = random.getstate()  # remeber this state 

print(random.sample(range(20),k=20)) # print 20

random.setstate(st)     # restore state

print(random.sample(range(20),k=10)) #print same first 10

输出:

[12, 0, 4, 3, 11, 10, 19, 1, 5, 18]
[4, 9, 0, 3, 10, 8, 16, 7, 18, 17, 14, 6, 2, 1, 5, 11, 15, 13, 19, 12]
[4, 9, 0, 3, 10, 8, 16, 7, 18, 17]

好吧,如果您获得了状态并恢复了状态,则可以重复一次并重复生成相同的值.

Obvoiusly, you can go back and reproduce the same values over and over if you get a state and restore it.

您不能在两者之间使用不同的随机数,否则您将更改状态.

You can not use different randoms in between though or you alter the state.

random.setstate(st) # go back again

print(random.sample(range(99),k=2)) # do something different
print(random.sample(range(20),k=18))

输出:

[21, 50]      # something different after setting state
[0, 3, 11, 9, 18, 8, 17, 19, 16, 7, 15, 1, 10, 2, 12, 5, 13, 14] # changed values


import random
import timeit

t1 = timeit.timeit(stmt = """random.seed(42)
random.randint(1,10)""",number=10000,setup="import random")

t2 = timeit.timeit(stmt = """
random.randint(1,10)
random.setstate(s)""",number=10000,setup="""import random
s = random.getstate()""")

print(t1,t2) 

输出:

# seed() time           setstate() time
0.5621587821914207      0.49502014443357545

这篇关于python random.getstate()和random.setstate()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆