蒙特卡洛流程

Python 中的蒙特卡洛模拟

Izzy Weber

Curriculum Manager, DataCamp

模拟步骤

  1. 定义输入变量并选择其概率分布

  2. 从这些分布中采样生成输入

  3. 对模拟输入进行确定性计算

  4. 汇总结果

Python 中的蒙特卡洛模拟

计算圆周率

生成随机点 $(x, y)$,其中 $x$ 和 $y$ 取值范围为 -1 到 1。

一个包含随机采样点的正方形内切圆示意图

$$Area_{circle} = \pi $$

$$Area_{square} = 2 \times 2 = 4 $$

$$\frac{Area_{circle}}{Area_{square}} = \frac{\pi}{4} $$

$$\frac{n_{red}}{n_{all}} = \frac{\pi}{4} $$

$$ \pi = 4 \times \frac{n_{red}}{n_{all}}$$

Python 中的蒙特卡洛模拟

步骤 1

定义输入变量并选择其概率分布

  • 输入:由 $(x, y)$ 坐标表示的各个点
  • 概率分布:$x$ 和 $y$ 服从 -1 到 1 的均匀分布。

 

circle_points = 0 
square_points = 0
Python 中的蒙特卡洛模拟

步骤 2

从这些分布中采样生成输入

 

对 $x$ 和 $y$ 进行均匀采样,范围为 -1 到 1:

for i in range(n):
    x = random.uniform(-1, 1)
    y = random.uniform(-1, 1)
Python 中的蒙特卡洛模拟

步骤 3

对模拟输入进行确定性计算

检查每个点是否在圆内:给定 $x$ 和 $y$ 时是确定的

dist_from_origin = x**2 + y**2

若在圆内,将该点计入 circle_points;始终将该点计入 square_points

if dist_from_origin <= 1:
     circle_points += 1
square_points += 1
Python 中的蒙特卡洛模拟

步骤 4

汇总结果以回答关注的问题

 

经过多轮模拟,计算圆周率!

pi = 4 * circle_points/ square_points
Python 中的蒙特卡洛模拟

合并在一起

n = 4000000
circle_points = 0 
square_points = 0

for i in range(n): x = random.uniform(-1, 1) y = random.uniform(-1, 1) dist_from_origin = x**2 + y**2 if dist_from_origin <= 1: circle_points += 1 square_point += 1
pi = 4 * circle_points / square_points print(pi)
3.142518
Python 中的蒙特卡洛模拟

Vamos praticar!

Python 中的蒙特卡洛模拟

Preparing Video For Download...