估算丌值并绘制圆
import numpy as np
import matplotlib.pyplot as plt
# 设置随机种子以便结果可复现
np.random.seed(42)
# 总点数
num_points = 10000
# 在单位正方形内生成随机点
points = np.random.rand(num_points, 2)
# 计算每个点到原点的距离
distances = np.sqrt(points[:, 0]**2 + points[:, 1]**2)
# 判断点是否在单位圆内
inside = distances <= 1
# 估算π值
pi_estimate = 4 * np.sum(inside) / num_points
print(f"估算的π值: {pi_estimate}")
# 绘制结果
plt.figure(figsize=(8, 8))
plt.scatter(points[inside, 0], points[inside, 1], c='blue', s=1, label='圆内点')
plt.scatter(points[~inside, 0], points[~inside, 1], c='red', s=1, label='圆外点')
# 绘制理论上的圆
theta = np.linspace(0, np.pi/2, 100)
plt.plot(np.cos(theta), np.sin(theta), c='green', linewidth=2, label='理论圆')
plt.axis('equal')
plt.xlabel('x')
plt.ylabel('y')
plt.title(f'蒙特卡洛方法估算π值 (估算值: {pi_estimate:.4f})')
plt.legend()
plt.grid(True)
plt.show()