Python Code for Computing Generalized Birthday Problem

专业相关2026年3月20日发布 芮和
150.2K 1150
1,619字
7–10 分钟

Problem Description

Generalized Birthday Problem: Consider nn 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 nn and rr satisfy certain conditions, the probability that at least two people have birthdays within rr days of each other is:

P=1(3651nr)!365n1(365(r+1)n)!P=1-\frac{(365-1-n r)!}{365^{n-1}(365-(r+1) n)!}

Implementation

This is a simple code using Log-Probability Computation to calculate PP. 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

nr=0r=1r=2
100.11694817770.31471653010.4720877238
200.41143838360.80448335520.9393140224
230.50729723430.88790964370.9770852403
300.70631624270.97819536200.9987474258
400.89123180980.99911544170.9999963536
500.97037357960.99998798310.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).

© 版权声明

相关文章