什麼是蒙地卡羅模擬?

Python 的 Monte Carlo 模擬

Izzy Weber

Curriculum Manager, DataCamp

模擬與蒙地卡羅模擬

模擬:
  • 嘗試仿真現實的實驗
  • 常用電腦程式執行

 

蒙地卡羅模擬:
  • 用於預測受「隨機變數」影響的各種結果機率
  • 依賴重複隨機取樣以取得數值結果
  • 結果具隨機性,因模型依賴隨機取樣
Python 的 Monte Carlo 模擬

模擬範例

擲六面骰
  • Tom 擲一顆公平的六面骰 $n$ 次
  • 每次擲完,他記錄點數
  • 接著將該骰放入袋中,下一次改抽新骰

問題

  1. 經過 $n$ 次後,Tom 袋中會有幾顆骰?
  2. 經過 $n$ 次後,點數的平均是多少?

 

一隻手在擲骰子

Python 的 Monte Carlo 模擬

模擬 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 的 Monte Carlo 模擬

模擬結果

模擬一:

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 的 Monte Carlo 模擬

大數法則

當同分布的隨機變數數量增加,其樣本平均會趨近理論平均。

模擬三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 的 Monte Carlo 模擬

一起來練習吧!

Python 的 Monte Carlo 模擬

Preparing Video For Download...