蒙特卡罗模拟 python Monte Carlo Simulation

1. 蒙特卡罗模拟

与普通预测模型不同,蒙特卡罗模拟根据估计值范围与一组固定输入值来预测一组结果。换句话说,蒙特卡洛模拟通过利用概率分布(例如均匀分布或正态分布),为任何具有固有不确定性的变量构建可能结果的模型。然后,它一遍又一遍地重新计算结果,每次都使用最小值和最大值之间的一组不同的随机数。在典型的蒙特卡罗实验中,可以重复此练习数千次以产生大量可能的结果。

由于其准确性,蒙特卡罗模拟也可用于长期预测。随着输入数量的增加,预测数量也会增加,使您能够更准确地预测更远的时间结果。当蒙特卡罗模拟完成时,它会产生一系列可能的结果以及每个结果发生的概率。

蒙特卡洛模拟的一个简单示例是考虑计算掷出两个标准骰子的概率。骰子有 36 种组合。基于此,您可以手动计算特定结果的概率。使用蒙特卡罗模拟,您可以模拟掷骰子 10,000 次(或更多),以实现更准确的预测。

无论您使用什么工具,蒙特卡罗技术都涉及三个基本步骤:

  1. 设置预测模型,确定要预测的因变量和驱动预测的自变量(也称为输入、风险或预测变量)。
  2. 指定自变量的概率分布。使用历史数据和/或分析师的主观判断来定义可能值的范围并为每个值分配概率权重。
  3. 重复运行模拟,生成自变量的随机值。这样做,直到收集到足够的结果来构成近乎无限数量的可能组合的代表性样本。

您可以通过修改用于模拟数据的基础参数来运行任意数量的蒙特卡罗模拟。但是,您还需要通过计算方差和标准差(这是常用的散布度量)来计算样本内的变异范围。给定变量的方差是变量与其期望值之间的平方差的期望值。标准差是方差的平方根。通常,方差越小越好。

2. Python 蒙特卡罗模拟计算 π \pi π

# import libraries
import numpy as np

# initialize variables
n_simulations = 100000
n_points_circle = 0
n_points_square = 0

# create lists to store x and y values
l_xs = []
l_ys = []

# loop n_simulations times
for _ in range(n_simulations):
    
    # x is randomly drawn from a continuous uniform distritbuion
    x = np.random.uniform(-1, 1)
    # store x in the list
    l_xs.append(x)
    
    # y is randomly drawn from a continuous uniform distribution
    y = np.random.uniform(-1, 1)
    # store y in the list
    l_ys.append(y)


# loop n_simulations times
for i in range(n_simulations):
    
    # calculate the distance between the point and the origin
    dist_from_origin = l_xs[i] ** 2 + l_ys[i] ** 2
    
    # if the distance is smaller than or equal to 1, the point is in the circle
    if dist_from_origin <= 1:
        n_points_circle += 1
    
    # by definition of the uniform distribution, the point is in the square
    n_points_square += 1

# estimate the value of pi
pi = 4 * n_points_circle / n_points_square
print(pi)

3. Reference

[1] https://www.ibm.com/topics/monte-carlo-simulation
[2] https://medium.com/@whystudying/monte-carlo-simulation-with-python-13e09731d500