蒙特卡罗方法手搓图形

以下是使用蒙特卡罗方法生成单位圆的Python实现,通过随机采样点并可视化结果:

import numpy as np
import matplotlib.pyplot as plt

# 设置随机点数量
n_points = 10000

# 生成随机点
x = np.random.uniform(-1, 1, n_points)
y = np.random.uniform(-1, 1, n_points)

# 计算点到原点的距离
distances = np.sqrt(x**2 + y**2)

# 筛选出在单位圆内的点
inside_circle = distances <= 1

# 绘制图形
plt.figure(figsize=(6, 6))
plt.scatter(x[inside_circle], y[inside_circle], color='blue', s=1, label='Inside Circle')
plt.scatter(x[~inside_circle], y[~inside_circle], color='red', s=1, label='Outside Circle')
plt.gca().set_aspect('equal', adjustable='box')
plt.title('Monte Carlo Estimation of Pi')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()

# 计算π的近似值
pi_estimate = 4 * np.sum(inside_circle) / n_points
print(f"Estimated value of π: {pi_estimate}")
# 输出 Estimated value of π: 3.1488

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值