本文主要是介绍利用蒙特卡罗法算PI,并绘制曲线图和散点图,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
原理 落在圆内的概率=圆与正方形面积之比=0.25Π
先上图
绘制折线图
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("pi.txt10","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()
当total=500
当total=1000
当total=10000
绘制散点图
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()
total=3000
total=100000
total=1000000
这篇关于利用蒙特卡罗法算PI,并绘制曲线图和散点图的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!