python之使用蒙特卡洛方法估计圆周率π

import random
import matplotlib.pyplot as plt

def monte_carlo_pi(num_samples):
    inside_circle = 0
    inside_x, inside_y = [], []
    outside_x, outside_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_circle += 1
            inside_x.append(x)
            inside_y.append(y)
        else:
            outside_x.append(x)
            outside_y.append(y)

    pi_estimate = 4 * (inside_circle / num_samples)

    return pi_estimate, inside_x, inside_y, outside_x, outside_y

# 设置随机生成点的数量
num_samples = 1000

# 运行蒙特卡洛方法
estimated_pi, inside_x, inside_y, outside_x, outside_y = monte_carlo_pi(num_samples)

# 绘制散点图和单位圆
fig, ax = plt.subplots()
ax.scatter(inside_x, inside_y, color='blue', label='Inside Circle')
ax.scatter(outside_x, outside_y, color='red', label='Outside Circle')
ax.set_aspect('equal', 'box')
circle = plt.Circle((0, 0), 1, edgecolor='black', facecolor='none', linewidth=2, label='Unit Circle')
ax.add_patch(circle)
ax.legend()

# 显示估计的π值
plt.title(f"Monte Carlo Estimation of π: {estimated_pi:.5f}")
plt.show()

估计图:
python之使用蒙特卡洛方法估计圆周率π_第1张图片

你可能感兴趣的:(python,开发语言,算法)