Is there a reverse way to find number of people with given 0.5 probability that two people will have same birthday but no using mathematical formula?

孤人 提交于 2020-02-25 06:16:06

问题


I'm doing birthday paradox, and want to know how many people can meet 0.5 probability that two people have same birthday by using python.

I have tried no using mathematical formula to find probability with given the number of people by using random and randint in python

import random
def random_birthdays():
    bdays = []
    bdays = [random.randint(1, 365) for i in range(23)]
    bdays.sort()
    for x in range(len(bdays)):
        while x < len(bdays)-1:
            print x
            if bdays[x] == bdays[x+1]:
                #print(bdays[x])
                return True
            x+=1
        return False
count  = sum(random_birthdays() for _ in range(1000))
print('In a sample of 1000 classes each with 23 pupils, there were', count, 'classes with individuals with the same birthday')

I expect some hints or codes that can help me through this.


回答1:


Well, problem with your code you check only consecutive birthday equality. Better check it using sets

Along the line

import random

def sim(n):
    """simulate birthdays for n people"""
    a = set([random.randint(1, 365) for _ in range(n)])
    if len(a) == n:
        return False
    return True

print(sim(23))
print(sim(23))
print(sim(23))
print(sim(23))
print(sim(23))

Function above will return true if there are same day birthday for n people, false otherwise.

Call it 1000000 times for n = 20, 21, ...., 25 and count how many Trues vs Falses are there

Running code

nt = 0
nf = 0
n = 23
for k in range(0, 1000000):
    if sim(n):
        nt += 1
    else:
        nf += 1

print((nt, nf))

for n = 23 and n = 22 produced

(506245, 493755)
(475290, 524710)


来源:https://stackoverflow.com/questions/57814174/is-there-a-reverse-way-to-find-number-of-people-with-given-0-5-probability-that

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!