python 模拟抛硬币概率

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import numpy as np
import matplotlib.pyplot as plt
from random import randint
from uuid import uuid4
def rnum():
    return randint(0,1)
x=[]
y=[]
z=[]
n=0
ys=0
zs=0
for i in range(1000000):
    n=n+1
    if rnum()==0:
        zs=zs+1
    else:
        ys=ys+1
    x.append(i)
    y.append(ys/n)
    z.append(zs/n)
# print(x,y)
l1=plt.plot(x,y,z)
l2=plt.plot(x,[0.5]*1000000,color="black", linewidth=1)
plt.legend(handles=[l1, l2], labels=['P(A)', '0.5'])
plt.show()
# plt.savefig(str(uuid4())+'.jpg')
# plt.clf()