Python蒙特卡洛 方法计算圆周率

蒙特卡罗法也称统计模拟法、统计试验法。是把概率现象作为研究对象的数值模拟方法。是按抽样调查法求取统计值来推定未知特性量的计算方法。

代码实现
import numpy as np
import matplotlib.pyplot as plt

N = 10000
plt.rc('font', size=16)
x, y = np.random.uniform(-1, 1, size=(2, N))
circle_in = x ** 2 + y ** 2 <= 1
circle_out = np.invert(circle_in)
pi = circle_in.sum() / N * 4
error = abs(np.pi - pi)/np.pi
plt.plot(x[circle_in],y[circle_in],'b.')
plt.plot(x[circle_out],y[circle_out],'r.')
plt.plot(0, 0, label='$\hat\pi$={:.4f}\nerror={:.4f}%'.format(pi, error), alpha=0)
plt.legend()
plt.axis('square')
plt.show()
结果图

在这里插入图片描述

N数值越大,圆周率越准确,误差越小。

猜你喜欢

转载自blog.csdn.net/qq_44864262/article/details/108468094