有没有一种相反的方法可以找到两个人生日相同但不使用数学公式的概率为 0.5 的人数?

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?

我在做生日悖论,想知道有多少人可以用python.

满足两个人生日相同的0.5概率

我尝试不使用数学公式通过在 python

中使用 random 和 randint 来计算给定人数的概率
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')

我希望得到一些提示或代码来帮助我解决这个问题。

好吧,你的代码有问题,你只检查连续的生日是否相等。最好使用 sets

检查一下

沿线

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))

如果 n 人的生日是同一天,上述函数将 return 为真,否则为假。

调用它 1000000 次,n = 20, 21, ...., 25 并计算有多少对错

运行代码

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

print((nt, nf))

n = 23 和 n = 22 生产

(506245, 493755)
(475290, 524710)