蒙特卡洛方法估算 π
原理:在单位正方形(边长为 1)内随机生成点(如上图)。计算落在单位圆(半径为 1)内的点的比例,根据公式 π ≈ 4 * (圆内点数 / 总点数) 估算 π 值。
并使用 matplotlib 绘制随机点分布图,蓝色点表示落在圆内的点,红色点表示落在圆外的点。绘制单位圆,直观展示点的分布情况。
首先,用函数estimate_pi来计算 π,参数:num_samples:随机生成的点的数量。返回值:pi_estimate:估算的 π 值;points_inside_x:圆内点的 x 坐标列表;points_inside_y:圆内点的 y 坐标列表;points_outside_x:圆外点的 x 坐标列表;points_outside_y:圆外点的 y 坐标列表。根据公式 π ≈ 4 * (圆内点数 / 总点数) 计算 π 的估算值。代码如下:
def estimate_pi(num_samples):
"""使用蒙特卡洛方法估算圆周率 π"""
inside_circle = 0 # 记录落在圆内的点数
points_inside_x = [] # 圆内点的 x 坐标
points_inside_y = [] # 圆内点的 y 坐标
points_outside_x = [] # 圆外点的 x 坐标
points_outside_y = [] # 圆外点的 y 坐标
for _ in range(num_samples):
# 在单位正方形内随机生成点
x = random.uniform(0, 1)
y = random.uniform(0, 1)
# 计算点到原点的距离
distance = x**2 + y**2
# 判断点是否在单位圆内
if distance <= 1:
inside_