Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python 3: random.seed(): where to call it?

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?

like image 879
max Avatar asked Feb 02 '11 23:02

max


People also ask

What is random seed () in python?

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.

How do you call a random module in python?

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.

How do you call a random variable in python?

To generate random number in Python, randint() function is used. This function is defined in random module.

How do you pick a random seed?

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.


2 Answers

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()
like image 139
Jim Brissom Avatar answered Oct 06 '22 16:10

Jim Brissom


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 of Random to get generators that don’t share state.

like image 31
Craig McQueen Avatar answered Oct 06 '22 15:10

Craig McQueen