เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

กฎของจำนวนมาก

จากแบบฝึกหัดที่แล้ว เราพบว่าเนื่องจากลักษณะแบบสุ่มของการจำลอง Monte Carlo แต่ละครั้งจึงอาจให้ผลลัพธ์ที่แตกต่างกันมาก ในแบบฝึกหัดนี้ จะนำกฎของจำนวนมาก (Law of Large Numbers) มาใช้จำลองอัตราเงินเฟ้อในปี 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 ให้แล้ว

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

Monte Carlo Simulations ใน Python

ดูคอร์ส

คำแนะนำการฝึกหัด

  • คำนวณค่าเฉลี่ยจากการจำลอง 1,000 ครั้ง โดยแต่ละครั้งสุ่มค่า seed ในช่วง 0 ถึง 20,000
  • คำนวณค่าเฉลี่ยจากการจำลอง 10,000 ครั้ง โดยแต่ละครั้งสุ่มค่า seed ในช่วง 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))
แก้ไขและรันโค้ด