Python random.setstate (), seed () - is there a guarantee of the same results in implementations?

Is there any guarantee that a pyhon2 / python3 script with a random generator initialized with random.setstate() or random.seed() will produce the same pseudorandom sequence on different versions and platforms? (e.g. python 3.1 on Mac , the same as python 3.2 on Linux 64-bit )

The question is for both: python2 and python3, with the assumption that python3 scripts will run on python3 interpreters and vice versa.

+7
source share
2 answers

Python 2.3 and above uses the Mersenne Twister generator, which is independent of the system random function (implemented as the C extension module for Python). For any version using Mersenne Twister, the results should be the same for versions and platforms.

Previously, you could guarantee backward compatibility with the WichmannHill generator, but unfortunately it looks like it was removed in Python 3.x.

If you absolutely need to guarantee compatibility, write your own subclass of Random (or use a stable external implementation like simplerandom ) as recommended in the Random documentation:

The Random class can also be subclassed if you want to use a different base generator of your own project: in this case, redefine the methods random (), seed (), getstate (), setstate () and jumpahead (). Optionally, the new generator can provide the getrandbits () method - this allows randrange () to sample in an arbitrarily large range.

+6
source

You can use the simplerandom module, which has a sequential implementation independent of the Python platform. It supports Python 2.4, 2.5, 2.6, 2.7, 3.1 and 3.2. It has 9 different algorithms.

Here is an example:

 >>> import simplerandom.iterators as sri >>> rng = sri.MWC1(12345) >>> next(rng) 498186671L >>> next(rng) 888940288L >>> next(rng) 345072384L 

And as long as you are seed with the same value, you will get the same results:

 >>> rng = sri.MWC1(12345) >>> next(rng) 498186671L >>> rng = sri.MWC1(98765) >>> next(rng) 3546724783L 
+4
source

All Articles