conmak
conmak

Reputation: 1470

Python random.seed produces similar random.randint numbers in python given different range sizes

When using random in python, there are certain seeds that produce similar random numbers.

For example in python 3.8.5:

>>> import random
>>> random.seed(100)
>>> print(random.randint(1,100))
19
>>> random.seed(335)
>>> print(random.randint(1,100))
19
>>> random.seed(100)
>>> print(random.randint(1,500))
75
>>> random.seed(335)
>>> print(random.randint(1,500))
75
>>> random.seed(100)
>>> print(random.randint(1,1000))
150
>>> random.seed(335)
>>> print(random.randint(1,1000))
149

It would appear that this pattern holds for many combinations of seeds where making random.randint produce similar results for different seeds.

For another example:

>>> import random
>>> random.seed(101)
>>> print(random.randint(1,100))
75
>>> random.seed(155)
>>> print(random.randint(1,100))
75
>>> random.seed(101)
>>> print(random.randint(1,500))
298
>>> random.seed(155)
>>> print(random.randint(1,500))
298
>>> random.seed(101)
>>> print(random.randint(1,1000))
596
>>> random.seed(155)
>>> print(random.randint(1,1000))
595

Is there any reasonably simple way to solve this such that these numbers produce substantially different results given different range sizes?

Upvotes: 0

Views: 248

Answers (1)

Aplet123
Aplet123

Reputation: 35512

It's simply due to the fact that their random.random() results are very similar:

random.seed(100)
random.random() # 0.1456692551041303

random.seed(335)
random.random() # 0.14455004782209402

The easiest way is to just not generate only one random number the seeds, since they start to differ again after generating a random number. But, if you really wanted to generate different numbers depending on the range size, you could do something where you seed the rng with the seed multiplied by the range size.

Upvotes: 1

Related Questions