1,619字
7–10 分钟
Problem Description
Generalized Birthday Problem: Consider people in a room. Assume each person’s birthday is equally likely to be any of the 365 days of the year (ignoring February 29), and all birthdays are independent. When and satisfy certain conditions, the probability that at least two people have birthdays within days of each other is:
Implementation
This is a simple code using Log-Probability Computation to calculate . The logarithmic transformation helps prevent numerical overflow and reduces computation errors when dealing with large factorials.
import math
ln = math.log
def calculateP(n, r):
up = 0
dl = (n - 1) * ln(365)
dr = 0
for i in range(1, 365 - n * r):
up += ln(i)
for j in range(1, 365 + 1 - r * n - n):
dr += ln(j)
right = math.exp(up - dl - dr)
return 1 - right
print(calculateP(10, 0))
print(calculateP(20, 0))
print(calculateP(23, 0))
print(calculateP(30, 0))
print(calculateP(40, 0))
print(calculateP(50, 0))
print()
print(calculateP(10, 1))
print(calculateP(20, 1))
print(calculateP(23, 1))
print(calculateP(30, 1))
print(calculateP(40, 1))
print(calculateP(50, 1))
print()
print(calculateP(10, 2))
print(calculateP(20, 2))
print(calculateP(23, 2))
print(calculateP(30, 2))
print(calculateP(40, 2))
print(calculateP(50, 2))
Code language: Python (python)
Results
| n | r=0 | r=1 | r=2 |
|---|---|---|---|
| 10 | 0.1169481777 | 0.3147165301 | 0.4720877238 |
| 20 | 0.4114383836 | 0.8044833552 | 0.9393140224 |
| 23 | 0.5072972343 | 0.8879096437 | 0.9770852403 |
| 30 | 0.7063162427 | 0.9781953620 | 0.9987474258 |
| 40 | 0.8912318098 | 0.9991154417 | 0.9999963536 |
| 50 | 0.9703735796 | 0.9999879831 | 0.9999999989 |
Source
This code is used to solve a problem in the homework of Probability and Statistics for Information Science course. You can find the complete assignment in my GitHub repository (The visibility will be changed to public after the course ends).
© 版权声明
文章版权归作者所有,未经允许请勿转载。



