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