温馨提示×

SciPy中如何实现蒙特卡洛模拟

小亿
82
2024-05-25 13:01:13
栏目: 编程语言

在SciPy中,可以使用numpy.random模块来实现蒙特卡洛模拟。下面是一个简单的示例,演示如何使用蒙特卡洛模拟来计算圆周率的近似值:

import numpy as np

# 设置随机种子
np.random.seed(0)

# 模拟的次数
n = 1000000

# 在单位正方形内生成随机点
points = np.random.rand(n, 2)

# 计算点到原点的距离
distances = np.linalg.norm(points, axis=1)

# 统计落在单位圆内的点的数量
inside_circle = np.sum(distances < 1)

# 计算圆的面积
area_square = 1
area_circle = inside_circle / n * area_square

# 估计圆周率
pi_estimate = 4 * area_circle

print("估计的圆周率为:", pi_estimate)

上面的代码首先生成了1000000个在单位正方形内的随机点,然后计算每个点到原点的距离,统计落在单位圆内的点的数量,进而估计圆的面积和圆周率的近似值。

通过运行上面的代码,您可以得到一个估计的圆周率值。您也可以调整模拟的次数n来获得更精确的估计值。

0