random.random() generates different numbers on different machines

Viewed 253

on a raspberry pi 3:

>>> import random
>>> random.seed(0.9849899567458751)
>>> random.random()
0.47871160253065614

on my laptop (running Ubuntu):

>>> import random
>>> random.seed(0.9849899567458751)
>>> random.random()
0.5059711320067936

I need those two numbers to be equal. My guess would be that this has something to do with floating point precision that might be different on the two machines but I don't know how to solve this.

How do I generate reproducable random numbers in python, regardless of the machine the code is running on?

1 Answers

You should use an integer for the seed instead of a floating-point number.

Python 3.5.3 on Raspberry Pi:

Python 3.5.3 (default, Sep 27 2018, 17:25:39)
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import random
>>> random.seed(9248459222926972)
>>> [random.randint(1, 1000) for x in range(5)]
[586, 818, 989, 122, 519]

Python 3.7.3 on Windows x64:

Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import random
>>> random.seed(9248459222926972)
>>> [random.randint(1, 1000) for x in range(5)]
[586, 818, 989, 122, 519]

In case you're working with library code that might be calling random.*() "in the background", you may also want to consider instantiating your own seeded RNG only your code uses:

import random
rng = random.Random()
rng.seed(9248459222926972)
# ...
Related