大數法則
你在前一個練習中學到,因為 Monte Carlo 模擬具有隨機性,每次的模擬結果可能差異很大。這個練習中,你會運用大數法則,透過大量模擬的平均值來推估 2050 年的通膨。
你在前一個練習中寫好的 monte_carlo_inflation() 函式已可供使用。提醒你,函式程式碼如下:
def monte_carlo_inflation(year, seed):
random.seed(seed)
inflation_rate = 8.6
yearly_increase = random.randint(1, 3)
for i in range(year - 2022):
inflation_rate = inflation_rate * ((100 + yearly_increase)/100)
return(inflation_rate)
已為你匯入 numpy 與 random 套件。
本練習屬於課程
Python 的 Monte Carlo 模擬
練習說明
- 計算 1,000 次模擬的平均值;每次都隨機選擇介於 0 到 20,000 的種子。
- 計算 10,000 次模擬的平均值;每次都隨機選擇介於 0 到 20,000 的種子。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Calculate the average of 1,000 simulation results with a seed between 0 and 20000
rates_1 = []
for i in range(____):
seed = random.randint(____, ____)
rates_1.append(monte_carlo_inflation(2050, ____))
print(np.mean(rates_1))
# Calculate the average of 10,000 simulation results with a seed between 0 and 20000
rates_2 = []
for i in range(____):
seed = random.randint(____, ____)
rates_2.append(monte_carlo_inflation(2050, ____))
print(np.mean(rates_2))