原理 落在圆内的概率=圆与正方形面积之比=0.25Π
先上图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/f039c2daa77714d1af57cf4de52adcfa.png)
绘制折线图
import random
import matplotlib.pyplot as plt
def pi(total):
count = 0
for i in range(total):
x = random.random()
y = random.random()
x = pow(x, 2)
y = pow(y, 2)
dis = pow(x + y, 0.5)
if dis <= 1:
count += 1
pi = 4 * count / total
print(total,"π是", 4 * count / total)
return pi
with open("pi.txt10","w") as f:
i=500
xx=[]
yy=[]
for x in range(i):
if x!=0:
y1=pi(x)
xx.append(x)
yy.append(y1)
f.write("当total为0{},π为{}\n".format(x,y1))
plt.plot(xx,yy,linestyle=':', linewidth=1, markersize=10)
plt.show()
当total=500
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0975848d584d1cae4e9b1bafae6c654b.png)
当total=1000
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1ed4114130a07fc9d9eed8e77e40be9d.png)
当total=10000
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/90c4a09420468cc0d6ea31273395b6b4.png)
绘制散点图
import random
import matplotlib.pyplot as plt
import pandas as pd
def pi(total):
x1=[]
y1=[]
x2=[]
y2=[]
count = 0
for i in range(total):
x = random.random()
y = random.random()
dis = pow(pow(x, 2) + pow(y, 2), 0.5)
if dis <= 1:
x1.append(x)
y1.append(y)
count += 1
else:
x2.append(x)
y2.append(y)
pi = 4 * count / total
print(total,"π是", 4 * count / total)
return pi,x1,y1,x2,y2
color = ['c', 'b', 'g', 'r', 'm', 'y', 'k', 'w']
total=5000
PI,x1,y1,x2,y2=pi(total)
fig=plt.figure(figsize=(6,6))
rect1 = [0.10, 0.1, 0.8, 0.8]
ax1 = plt.axes(rect1)
plt.scatter(x1, y1,s=1, c=color[0])
plt.scatter(x2, y2,s=1, c=color[2])
plt.title(PI)
plt.xlabel(total)
plt.show()
total=3000
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/b21be0c9de16b078c65a4fe524e49dc9.png)
total=100000
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a0ea5728dbff4e2d78e5bc9401ca764b.png)
total=1000000
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8a96bb1e9ef1042c7d14b2397ffcda85.png)