python随机数前n项和_在python中回滚随机数生成器?

Is it possible to 'rollback' the random number generator by a specified number of steps to a earlier state to get repeated random numbers?

I want to be able to do something like this:

print(random.random())

0.5112747213686085

print(random.random())

0.4049341374504143

print(random.random())

0.7837985890347726

random.rollback(2) #go back 2 steps

print(random.random())

0.4049341374504143

print(random.random())

0.7837985890347726

My only current idea to accomplish this is to store all generated random numbers into a list to go back to. However, I would personally prefer a method that does not involve doing so because I plan on generating a pretty large amount of random numbers while this function won't be used that often.

解决方案

You want to take a look at random.getstate() and random.setstate(). Combine this with keeping track of the number of items generated and it's pretty simple to do what you want.

Note that you would have to be careful about other code using random if you relied on this, so I would suggest making a random.Random() instance to use to avoid this.

The functions supplied by this module are actually bound methods of a

hidden instance of the random.Random class. You can instantiate your

own instances of Random to get generators that don’t share state.

(from the docs)

Example implementation:

from itertools import islice

import collections

from random import Random

def consume(iterator, n):

"Advance the iterator n-steps ahead. If n is none, consume entirely."

# Use functions that consume iterators at C speed.

if n is None:

# feed the entire iterator into a zero-length deque

collections.deque(iterator, maxlen=0)

else:

# advance to the empty slice starting at position n

next(islice(iterator, n, n), None)

class RewindRandom:

def __init__(self):

self._random = Random()

self._state = self._random.getstate()

self._count = 0

def __iter__(self):

while True:

yield self._random.random()

def __call__(self):

self._count += 1

return next(iter(self))

def rollback(self, amount):

self._random.setstate(self._state)

consume(self, self._count-amount)

self._count -= amount

Which can be used like so:

random = RewindRandom()

>>> random()

0.31276818768213244

>>> random()

0.7031210824422215

>>> random()

0.7196351574136909

>>> random.rollback(2)

>>> random()

0.7031210824422215

>>> random()

0.7196351574136909

>>> random()

0.6582894948982371

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值