方法一
from collections import Counter
import matplotlib.pyplot as plt
import random
times=10000
#模拟随机抛10000次硬币
count=[]
for i in range(1,times):
y=random.randint(0,1)
count.append(y)
#统计正面出现的次数
a=Counter(count)
f1=a[1]
print(f1)
#10000次中正面出现的概率
print(f1/times)
#画图展示1-10000次试验中,每次正面向上出现的频率
p=[]
indices=[]
for i in range(1,times):
heads=0
for j in range(i):
if count[j]==1:
heads+=1
p.append(heads/i)
indices.append(i)
plt.plot(indices,p)
plt.show()
方法二
import matplotlib.pyplot as plt
import random
def r():
s=random.randint(0,1)
return s
times=5001
indices=[]
f=[]
for i in range(1,times):
heads=0
for j in range(i):
if r()==1:
heads+=1
f.append(heads/i)
indices.append(i)
print(heads/times)
plt.plot(indices,f)
plt.show()