简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM