Birthday Paradox problem in Python
The birthday paradox is a classic problem in probability theory that asks how many people are needed in a room before there is a greater than 50% chance that at least two of them share the same birthday. At first glance, it may seem like the number of people needed would be quite large, but surprisingly, the answer is much smaller than you might think.
To understand why this is the case, we can start by considering the probability that two people in a room of n people do not share the same birthday. The first person can have any birthday, so the probability that the second person has a different birthday is (364/365), since there are 364 days left in the year that are not the first person’s birthday. The probability that the third person has a different birthday than the first two is (363/365), and so on. The probability that all n people have different birthdays is then:
(364/365) * (363/365) * ... * ((365-n+1)/365)
We can simplify this expression by taking the complement, which is the probability that at least two people share the same birthday:
1 - (364/365) * (363/365) * ... * ((365-n+1)/365)
Now, let’s use Python to calculate this expression for different values of n and see at what point the probability exceeds 50%.
def birthday_paradox(num_people):
prod = 1
for i in range(num_people):
prod *= (365 - i) / 365
return 1 - prod
for i in range(2, 101):
prob = birthday_paradox(i)
if prob >= 0.5:
print(f"With {i} people in the room, there is a greater than 50% chance that at least two people share the same birthday.")
break
In this code, the birthday_paradox function takes a number of people as input and calculates the probability that at least two of them share the same birthday using the expression we derived earlier. The for loop at the end tests the function for different numbers of people from 2 to 100 and prints the first number of people for which the probability exceeds 50%.
Running this code, we find that with just 23 people in a room, there is a greater than 50% chance that at least two of them share the same birthday. This result may seem counterintuitive at first, but it makes sense when we consider the sheer number of pairs of people in a room of 23: there are (23 choose 2) = 253 possible pairs, and each one has a chance of around 8% of having the same birthday. This means that there are many opportunities for two people to have the same birthday, even with a relatively small number of people.
The birthday paradox is a fascinating example of how probability theory can sometimes produce unexpected results. By using Python to calculate the probabilities, we can gain a deeper understanding of the problem and appreciate the beauty of mathematical reasoning.