Python蒙特卡洛法计算圆周率的Matplotlib动态可视化演示
使用 matplotlib.animation 的 FuncAnimation 类,结合蒙特卡洛法随机撒点逻辑,即可实现圆周率计算的动态可视化。

蒙特卡洛法核心逻辑与数据映射
该方法基于几何概率:在边长为 2 的正方形内随机撒点,落入单位圆内的点数与总点数之比趋近于 π/4。通过实时统计并绘制散点图,可直观展示收敛过程。

算法需维护两个计数器:总点数和圆内点数。每次迭代生成新的随机坐标 (x, y),判断 x² + y² ≤ 1 是否成立。若成立则标记为圆内点,否则为圆外点。当前 π 的估算值为 4 * (圆内点数 / 总点数)。随着点数增加,估算值逐渐逼近真实 π。
完整程序实现与运行验证
以下代码展示了完整的动态可视化实现。将代码保存为 monte_carlo_pi.py 并运行,即可看到散点图逐步填充以及 π 估算值的动态变化。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
def update(frame):
global total_points, inside_points
# 每次新增 100 个点
new_points = 100
x_new = np.random.uniform(-1, 1, new_points)
y_new = np.random.uniform(-1, 1, new_points)
# 判断是否在圆内
in_circle = (x_new**2 + y_new**2) <= 1
# 更新计数
total_points += new_points
inside_points += np.sum(in_circle)
# 计算当前 π 估计值
pi_estimate = 4 * (inside_points / total_points)
# 更新散点图
scatter.set_offsets(np.vstack([x_new, y_new]).T)
colors = np.where(in_circle, 'red', 'blue')
scatter.set_facecolors(colors)
# 更新标题中的 π 值
title.set_text(f"π ≈ {pi_estimate:.4f} | Total Points: {total_points}")
return scatter, title
# 初始化
fig, ax = plt.subplots()
ax.set_xlim(-1.1, 1.1)
ax.set_ylim(-1.1, 1.1)
ax.set_aspect('equal')
ax.grid(True)
# 绘制正方形边界
square = plt.Rectangle((-1, -1), 2, 2, fill=False, edgecolor='black')
ax.add_patch(square)
# 绘制单位圆
circle = plt.Circle((0, 0), 1, fill=False, color='gray', linestyle='--')
ax.add_patch(circle)
# 初始化散点对象
scatter = ax.scatter([], [], s=1)
title = ax.set_title("π ≈ 0.0000 | Total Points: 0")
total_points = 0
inside_points = 0
# 创建动画
anim = FuncAnimation(fig, update, frames=1000, interval=50, blit=True)
plt.show()
程序运行后,窗口中会显示一个包含正方形和单位圆的坐标系。红色点表示落在圆内,蓝色点表示落在圆外。标题栏实时更新当前的 π 估算值和总点数。随着帧数增加,红色点逐渐填满半圆区域,π 估算值在 3.14 附近波动并趋于稳定。
关于 blit=True 性能优化的具体影响
在 FuncAnimation 中设置 blit=True 时,仅重绘发生变化的艺术家对象(如散点图和标题),而非整个画布。这显著提升了动画帧率,特别是在点数较多时。若设置为 False,每次都会重绘所有元素,导致卡顿。但需注意,blit=True 要求返回需要重绘的对象列表,且背景必须预先绘制干净。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









