Random is barely random at all?

前端 未结 11 613
失恋的感觉
失恋的感觉 2020-11-27 10:27

I did this to test the randomness of randint:

>>> from random import randint
>>>
>>> uniques = []
>>> for i in range(4500         


        
11条回答
  •  伪装坚强ぢ
    2020-11-27 10:52

    You have defined a random space of 4501 values (500-5000), and you are iterating 4500 times. You are basically guaranteed to get a collision in the test you wrote.

    To think about it another way:

    • When the result array is empty P(dupe) = 0
    • 1 value in Array P(dupe) = 1/4500
    • 2 values in Array P(dupe) = 2/4500
    • etc.

    So by the time you get to 45/4500, that insert has a 1% chance of being a duplicate, and that probability keeps increasing with each subsequent insert.

    To create a test that truly tests the abilities of the random function, increase the universe of possible random values (eg: 500-500000) You may, or may not get a dupe. But you'll get far more iterations on average.

提交回复
热议问题