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()andrandom.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
randomif you relied on this, so I would suggest making arandom.Random()instance to use to avoid this.(from the docs)
Example implementation:
Which can be used like so: