是否有相反的方法可以找到两个人生日相同但不使用数学公式的概率为 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?

查看:130
本文介绍了是否有相反的方法可以找到两个人生日相同但不使用数学公式的概率为 0.5 的人数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做生日悖论,想知道有多少人可以用python来满足两个人生日相同的0.5概率.

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.

我没有尝试使用数学公式通过在 python 中使用 random 和 randint 来找到给定人数的概率

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.

推荐答案

好吧,你的代码有问题,你只检查连续生日相等.最好使用集合检查它

Well, problem with your code you check only consecutive birthday equality. Better check it using 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 个人有同一天生日,上面的函数将返回 true,否则返回 false.

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

对 n = 20, 21, ...., 25 调用 1000000 次并计算有多少 Trues 和 Falses

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

运行代码

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 产生

for n = 23 and n = 22 produced

(506245, 493755)
(475290, 524710)

这篇关于是否有相反的方法可以找到两个人生日相同但不使用数学公式的概率为 0.5 的人数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆