python randomstate,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.

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()

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)

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.

Thanks,

解决方案

Why not try it out?

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

Output:

[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))

Output:

[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)

Output:

# seed() time setstate() time

0.5621587821914207 0.49502014443357545

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值