Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

Per How to generate a repeatable random number sequence? it's possible to set the state of the random module such that you can expect the subsequent calls to randint to return the same number.

One limitation 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 would be repeatable (but the streams' calls can be interleaved arbitrarily) with the current mechanism. Are there any workarounds/alternatives libraries to that would enable this?

like image 867
Maxim Khesin Avatar asked Dec 12 '22 12:12

Maxim Khesin


1 Answers

It doesn't have to maintain state at the module level -- see the docs for the random module:

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. This is especially useful for multi-threaded programs, creating a different instance of Random for each thread, and using the jumpahead() method to make it likely that the generated sequences seen by each thread don’t overlap.

like image 67
bgporter Avatar answered Jan 11 '23 23:01

bgporter