Birthday Paradox program in Python

In this tutorial, we will be seeing about The Birthday Paradox, it’s explanation, and its implementation in Python. So, what is the Birthday paradox in the first place? Among n people, it deals with the probability p of at least 2 people having the same birthday.

From the Pigeonhole Principle, we can say that there must be at least 367 people (considering 366 days of a leap year) to ensure a 100% probability that at least two people have the same birthday. We need only 23 people to get the probability of 50% and 70 people to raise that to 99.9%. Compared to 367, These numbers are very low. This problem is called a Paradox because we generally assume probabilities to be linear and the involvement of exponents.

Birthday Paradox Program

Let us suppose there are ‘n’ people in a room and we need to find the probability ‘p’ of at least two people having the same birthday. Let’s proceed the other way. Let us find the probability (1-p) and call it q. The variable ‘q’ represents the probability of all the n people having different birthdays.

Out of 366 days, the first person can have any birthday and can be chosen between all of 366 days. However, the second person can have only 365 choices as 1 day is already chosen. Similarly, the third person has 363 choices and continues for all n people.

The probability ‘q’ equals
q = ( 366C1 * 365C1 * 364C1 * … 366-(n-1)C1 ) / (366)n

q = 1 * ( 1 – 1/366 ) * ( 1 – 2/366 ) * ( 1 – 3/366 ) * … ( 1 – (n-1)/366 )

The required probability ‘p’ is

p = 1 – q

def probOfSameBirthday(n):
    q = 1
    for i in range(1, n):
        probability = i / 366
        q *= (1 - probability)
    p = 1 - q
    print (p)

Program Output:


Using an input of more than 153 gives an output of 1.0 because the interpreter cannot take any more decimal values!
The graph generally looks like this

chances of sharing birthday with number of peoples

Thank You for Reading and Keep Learning 🙂

Also Read: Credit Card Fraud Detection using Machine Learning in Python

Leave a Reply