前言
大二上概统课的大作业里,我挑了验证伯努利大数定律的那一个。
代码实现
#该程序用于验证伯努利大数定律
import random
import matplotlib.pyplot as plt
#假设在每次独立实验中,事件发生的概率为0.5
p = input("Please type in the probability of the event'A': ")
p = float(p)
#创建空列表用来存放独立重复实验
experiment = []
#创建好散点图
plt.scatter([],[])
plt.title('Frequency-Exp_times')
plt.xlabel('Exp_times')
plt.ylabel('Frequency')
#假设实验的重复次数为n,模拟n次独立重复实验
for n in range (1,10001):
print(n)
experiment = []
for i in range (1,n+1):
num = random.uniform(0,1)
if num <= p:
value = 1
if num > p:
value = 0
experiment.append(value)
nA = sum(experiment)
plt.scatter(n,nA/n,color='black',s=2)
#画出散点图
plt.show()
验证效果
p=0.25
p=0.5
p=0.75