用python验证生日悖论
时间: 2023-05-25 19:06:12 浏览: 177
python实现生日悖论分析
生日悖论是指在随机选择一个人时,该人的生日和已经选择的人中至少一个人的生日相同的概率达到了高于50%的水平。
为了验证这个悖论,我们可以使用Python随机生成一系列生日,然后判断是否有两个生日相同的情况出现。
下面是一个使用Python验证生日悖论的示例代码:
```python
import random
def generate_birthday(num_people):
"""
生成num_people个随机生日,格式为月份-日期,例如1-1表示1月1日
"""
birthdays = []
for i in range(num_people):
month = random.randint(1, 12)
if month in [1, 3, 5, 7, 8, 10, 12]:
day = random.randint(1, 31)
elif month in [4, 6, 9, 11]:
day = random.randint(1, 30)
else:
day = random.randint(1, 28)
birthdays.append(f"{month}-{day}")
return birthdays
def has_same_birthday(birthdays):
"""
判断生日列表中是否有重复的生日
"""
return len(birthdays) != len(set(birthdays))
def simulate(num_trials, num_people):
"""
模拟num_trials次随机选取num_people个人的过程,判断是否有重复生日出现
"""
num_success = 0
for i in range(num_trials):
birthdays = generate_birthday(num_people)
if has_same_birthday(birthdays):
num_success += 1
return num_success / num_trials
if __name__ == "__main__":
num_trials = 10000
for num_people in range(10, 101, 10):
p = simulate(num_trials, num_people)
print(f"For {num_people} people, probability of having same birthday is {p:.2%}")
```
这段代码模拟了从10个人到100个人这样一段范围内,有多少人中至少有两个人生日相同的概率。在大多数情况下,随着人数的增加,概率也逐渐升高,逼近50%。
运行结果如下:
```
For 10 people, probability of having same birthday is 11.42%
For 20 people, probability of having same birthday is 41.01%
For 30 people, probability of having same birthday is 70.34%
For 40 people, probability of having same birthday is 89.13%
For 50 people, probability of having same birthday is 97.02%
For 60 people, probability of having same birthday is 99.14%
For 70 people, probability of having same birthday is 99.76%
For 80 people, probability of having same birthday is 99.97%
For 90 people, probability of having same birthday is 99.99%
For 100 people, probability of having same birthday is 100.00%
```
可以看到,随着人数的增加,概率确实逐渐升高,并且在人数达到100的时候已经接近100%。这进一步验证了生日悖论的正确性。
阅读全文