Categories
python python-2.x python-3.x random

python random.setstate(), seed() – is there guarantee of same results across implementations?

Is there guarantee that pyhon2/python3 script with random generator initialized with random.setstate() or random.seed() will produce same sequence of pseudo-randomness across different versions and platforms ? (for example python 3.1 on Mac , the same as python 3.2 on Linux 64-bit)

Question is about both: python2 and python3, with assumption that python3 scripts will run on python3 interpreters and vice versa.

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

Previously, you could guarantee backwards compatibility using the WichmannHill generator, but unfortunately it seems that has been removed in Python 3.x.

If you absolutely need to guarantee compatibility, write your own Random subclass (or use a stable external implementation, e.g. simplerandom) as recommended by the random documentation:

Class Random can also be subclassed if you want to use a different basic generator of your own devising: in that case, override the random(), seed(), getstate(), setstate() and jumpahead() methods. Optionally, a new generator can supply a getrandbits() method — this allows randrange() to produce selections over an arbitrarily large range.