简体   繁体   中英

Probability seems wrong using Python randint

I'm using Python 2.7 to generate two random numbers, both 1-100 (including 1 and 100 ), and if they are the same, an event occurs. I would think that the probability of this would be 1/10000 because

1/100 * 1/100 = 1/10000

but the number times that it takes for the two numbers to match up is usually between 10-200. Why does this happen and is there any way to fix it?


Here's my full code:

import random
p5SickGen1 = random.randint(1,100)
p5SickGen2 = random.randint(1,100)
counter = 0
while p5SickGen1 != p5SickGen2:
    counter += 1
    p5SickGen1 = random.randint(1,100)
    p5SickGen2 = random.randint(1,100)

print(counter)

As @jgritty said earlier, your assumption is wrong .

The probability would not be 1/10000 because you are selecting from two different sets of numbers at the same time, which doesn't mean that you are picking a number from a set of numbers twice.

You can easily find the solution like this;

The number of the possibilities of getting same numbers are;

(1,1), (2,2), (3,3), (4,4), (5,5), ..., (100, 100) = 100 

Your sample space is 100*100 = 10000 . Thus the probability of getting same numbers in one pick;

100 / 10000 = 0.01

Hope this helps.

Btw, for those who are interested in learning the basics of probability, you can start from here .

Your assumption is wrong. There's nothing wrong here.

The odds of the numbers coming up the same twice in a row is simply 1 in 100.

Now, if you pick a specific number, say 42. The odds of getting 42 both times is 1 in 10000.

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