Home > database >  python random number why isn't it same on all computers
python random number why isn't it same on all computers

Time:11-06

One friend that I don't have any communication with anymore once told me the following:

Using that library(python's random) you can select a seed If you give it at seed it means the randomly generated number will always be the same No matter what computer you run it on

So I tried to test this, because this is what I need so it's the same on all computers and everytime someone calls this(this is important, as I am working on a blockchain NFT and trust is important here)

So I found this: https://machinelearningmastery.com/how-to-generate-random-numbers-in-python/

on that link, there's example:

from random import seed
from random import random
# seed random number generator
seed(1)
# generate some random numbers
print(random(), random(), random())
# reset the seed
seed(1)
# generate some random numbers
print(random(), random(), random())

running above in playground of python, I get

(0.417022004703, 0.720324493442, 0.000114374817345) (0.417022004703, 0.720324493442, 0.000114374817345)

But as you can see, on that website, the creator of that post got the following:

0.13436424411240122 0.8474337369372327 0.763774618976614 0.13436424411240122 0.8474337369372327 0.763774618976614

Why aren't they same on all computers then ? I am using the same seed. and how can I ensure that they will be the same ?

CodePudding user response:

The ANSWER is that, even though you have tagged Python-3.x, you are actually using Python 2, and the random number algorithm changed between 2 and 3.

I can tell that because your print statement printed the values as a tuple, with parentheses. That wouldn't happen with Python 3's print function.

It's odd to rely on a particular implementation of a random number algorithm for financial purposes. If you really need reproducibility, then you should embed your own algorithm. There are several RNGs that are not difficult to code. But if the algorithm needs to be predictable, why not just use incrementing numbers? If you don't need randomness, then don't use randomness.

CodePudding user response:

I get the post author's values both in Python 2.3.0 (over 18 years old) and in Python 3.10 (the newest, just a month old).

I get your values if I use numpy.random instead of Python's random.

So I suspect you're not telling the truth about your code or that that "playground of python" you're using is weird.

  • Related