从总体x计算累积概率

2024-05-14 14:31:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我怎样才能创建一个函数(我们称之为生日(x)),用一个循环计算至少两个人拥有相同生日(忽略闰年)的概率p(x)?概率公式为:

p(x) = 1−365/365⋅364/365⋅363/365…(366−x)/365

我猜我应该重申一个给定数字的公式,x,但不确定如何。提前谢谢

Edit:x是至少两人生日相同的人数


Tags: 函数数字概率edit公式人生人数
2条回答

您试图计算的是Cumulative Probability of a Binomial Distribution。因此,对于x的人口,你想知道至少有两个人的生日在同一天的概率。您可以使用以下选项:

import math

# x is the size of your population
def birthday(x):
    # Probability of having birthay in a specific day of the year
    p = 1/365 
    q = 1-p

    acc = 0
    
    # Summing from 2 until size of population (you need at least 2)
    for i in range(2,x+1):
        acc += (math.factorial(n)*(p**i)*(q**(n-i)))/(math.factorial(i)*math.factorial(n-i))
        
    return acc
#For y peoples; Or for y plays of roulette and x outcomes
def odds(x,y):
    return x/x**y

print (odds(365,2))


#For at least 2 peoples within a group of n peoples
import math 

def grp_odds(x,n):
    return 1-math.factorial(x)/(x**n*math.factorial(x-n))

print (grp_odds(365,2))
print (grp_odds(365,5))

输出:

0.0027397260273972603
0.002739726027397249
0.02713557369979358

你可以通过考虑2月29日怎么样来让它更华丽;)

相关问题 更多 >

    热门问题