Is it possible to create a repeatable stream of random numbers?

Per How to create a repeatable sequence of random numbers? you can set the state of a random module so that you can expect subsequent calls to randint to return the same amount.

One of the limitations that I see with this approach is that the state is set at the module level (essentially a global variable), so it seems impossible to create several streams / iterators of random numbers that will be repeated (but the calls of the streams can be alternating randomly ) using the current mechanism. Are there any workarounds / alternative libraries for this?

+4
source share
2 answers

It does not need to maintain state at the module level - see the docs for random module :

The functions provided by this module are actually related methods of a hidden instance of the random.Random class. You can instantiate your own instances of Random to get generators that do not share state. This is especially useful for multi-threaded programs, creating a Random instance for each thread and using the jumpahead() method to ensure that the generated sequences visible by each thread do not overlap.

+8
source

random.Random() is what you are looking for.

http://hg.python.org/cpython/file/2.7/Lib/random.py#l72

All the functions of the random.* Module level are simply proxies for a common instance of Random() , which lives in random._inst .

http://hg.python.org/cpython/file/2.7/Lib/random.py#l879

In your situation, all you need to do is an instance of N random.Random() ; they will have independent internal RNG states and can be seeded / consumed without affecting each other.

In fact, I consider it best practice to create our own instances of Random() for non-trivial applications, in particular, so it can be easily made repeatable if there is a state-dependent error, etc. Especially in test cases, this can be invaluable.

+5
source

Source: https://habr.com/ru/post/1497052/


All Articles