蒙特卡洛方法手搓图形

估算丌值并绘制圆

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值