In Python, what is the best way to generate some random number using a certain seed but without reseeding the global state? In Java, you could write simply:
Random r = new Random(seed);
r.nextDouble();
and the standard Math.random()
would not be affected. In Python, the best solution that I can see is:
old_state = random.getstate()
random.seed(seed)
random.random()
random.setstate(old_state)
Is this idiomatic Python? It seems much less clean than the Java solution that doesn't require "restoring" an old seed. I'd love to know if there's a better way to do this.
A random seed is a starting point in generating random numbers. A random seed specifies the start point when a computer generates a random number sequence.
Python Random seed() Method The random number generator needs a number to start with (a seed value), to be able to generate a random number. By default the random number generator uses the current system time. Use the seed() method to customize the start number of the random number generator.
Seed function is used to save the state of a random function, so that it can generate same random numbers on multiple executions of the code on the same machine or on different machines (for a specific seed value). The seed value is the previous value number generated by the generator.
So the short answer to the question is: if you want to set a seed to create a reproducible process then do what you have done and set the seed once; however, you should not set the seed before every random draw because that will start the pseudo-random process again from the beginning.
You can instantiate your own Random
object.
myrandom = random.Random(myseed)
The random
module manages its own instance of Random
, which will be unaffected by changes made to myrandom
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With