什么是蒙特卡洛模拟?

Python 中的蒙特卡洛模拟

Izzy Weber

Curriculum Manager, DataCamp

模拟与蒙特卡洛模拟

模拟:
  • 模仿现实的实验
  • 常用计算机程序

 

蒙特卡洛模拟:
  • 用于预测受"随机变量"影响的不同结果的概率
  • 依赖反复随机抽样以获得数值结果
  • 结果具随机性,因为模型依赖随机抽样
Python 中的蒙特卡洛模拟

模拟示例

掷六面骰
  • Tom 掷一枚公平的六面骰 $n$ 次
  • 每次记录点数
  • 然后将骰子放入袋中,下一次从中取一枚新骰子

问题

  1. 经过 $n$ 次掷骰,Tom 的袋中有多少枚骰子?
  2. $n$ 次后的平均点数是多少?

 

一只手在掷骰子

Python 中的蒙特卡洛模拟

模拟 Tom 的结果

  • total_dice:$n$ 次后 Tom 袋中的骰子数量
  • mean_point_dice:$n$ 次后的所有点数均值
import random
import numpy as np

def roll_dice(n, seed): random.seed(seed) total_dice = 0 point_dice = []
for i in range(n): total_dice += 1 point_dice.append(random.randint(1, 6))
mean_point_dice = np.mean(point_dice)
return([total_dice, mean_point_dice])
Python 中的蒙特卡洛模拟

模拟结果

模拟一:

seed=1231

print(roll_dice(10, seed))
print(roll_dice(100, seed))
print(roll_dice(1000, seed))
print(roll_dice(10000, seed))

模拟二:

seed=3124
print(roll_dice(10, seed))
print(roll_dice(100, seed))
print(roll_dice(1000, seed))
print(roll_dice(10000, seed))

结果:

[10, 3.6]

[100, 3.5]
[1000, 3.495]
[10000, 3.503]

结果:

[10, 3.8]
[100, 3.28]
[1000, 3.474]
[10000, 3.5508]
Python 中的蒙特卡洛模拟

大数定律

当同分布的随机变量数量增加时,其样本均值会趋近于理论均值。

模拟三seed = 3124):

print(roll_dice(100000, seed))
print(roll_dice(500000, seed))
print(roll_dice(1000000, seed))

结果:

[100000, 3.51344]
[500000, 3.50428]
[1000000, 3.501995]
Python 中的蒙特卡洛模拟

Passons à la pratique !

Python 中的蒙特卡洛模拟

Preparing Video For Download...