import random
import matplotlib.pyplot as plt
#原理 落在圆内的概率=圆与正方形面积之比=0.25Π
# total指代在圆里面晒的豆子数
def pi(total):count = 0for 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 += 1pi = 4 * count / totalprint(total,"π是", 4 * count / total)return pi
with open(
","w") as f:i=500xx=[]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()
import randomimport matplotlib.pyplot as plt
import pandas as pddef pi(total):x1=[]y1=[]x2=[]y2=[]count = 0for 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 += 1else:x2.append(x)y2.append(y)pi = 4 * count / totalprint(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])#s调整点的大小
plt.scatter(x2, y2,s=1, c=color[2])
plt.title(PI)
plt.xlabel(total)
plt.show()
本文发布于:2024-01-28 09:36:05,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/17064057716488.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |