I need to make sure all the randomness in my program is fully replicable. Where should I place a call to random.seed()?
I thought it should be in my main.py
module, but it imports other modules that happen to use random functions.
I can carefully navigate through my imports to see which one is the first to execute, but the moment I change my code structure I will have to remember to redo this analysis again.
Is there any simple and safe solution?
Python Random seed() Method The seed() method is used to initialize the random number generator. 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.
To get access to the random module, we add from random import * to the top of our program (or type it into the python shell). Open the file randOps.py in vim, and run the program in a separate terminal. Note if you run the program again, you get different (random) results.
To generate random number in Python, randint() function is used. This function is defined in random module.
Many researchers worry about how to choose a random number seed. Some people use an easy-to-remember sequence such as their phone number or the first few digits of pi. Others use long prime numbers such as 937162211.
It is actually safe to execute code in the "import section" of your main module, so if you are unsure about importing other modules that might or might not use the random module, maybe bypassing your seed, you can of course use something like
import random
random.seed(seed_value)
import something
import else
if __name__ == "__main__":
main()
If you want random to be replicable, it's probably best to make an instance of random.Random
in your application, call seed()
on that instance, and use that instance for your random numbers.
random.random()
actually uses a singleton of the random.Random
class, for convenience for people who don't care enough to make their own class instance. But that singleton is potentially shared with other modules that might want to call random.random()
to generate random numbers for whatever reason. That's why in your case you're better off instantiating your own random.Random
instance.
Quoting from the docs:
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 ofRandom
to get generators that don’t share state.
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