Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Python's random number generator with a local seed?

Tags:

Python's random seems are global, so modules changing it will effect each other.

While there are of course many 3rd party modules, is there a way using Python's standard library to have a random number local to a context.

(without using random.get/setstate which may be problematic when mixing code from different modules).

Something like...

r = random.context(seed=42) number = r.randint(10, 20) 

Where each module can use its own random context.

like image 443
ideasman42 Avatar asked May 20 '16 21:05

ideasman42


People also ask

How do you generate a random number from a seed in Python?

Python Random seed() MethodThe 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 seeds work in random generators?

When you use statistical software to generate random numbers, you usually have an option to specify a random number seed. A seed is a positive integer that initializes a random-number generator (technically, a pseudorandom-number generator). A seed enables you to create reproducible streams of random numbers.


1 Answers

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.

Make your own random.Random instance and use that.

rng = random.Random(42) number = rng.randint(10, 20) 
like image 131
user2357112 supports Monica Avatar answered Oct 08 '22 20:10

user2357112 supports Monica