Mô phỏng Monte Carlo với Python
Izzy Weber
Curriculum Manager, DataCamp
Câu hỏi

total_dice: số xúc xắc trong túi của Tom sau $n$ lần mean_point_dice: trung bình tất cả kết quả sau $n$ lầnimport random import numpy as npdef 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])
Mô phỏng 1:
seed=1231print(roll_dice(10, seed))print(roll_dice(100, seed))print(roll_dice(1000, seed))print(roll_dice(10000, seed))
Mô phỏng 2:
seed=3124
print(roll_dice(10, seed))
print(roll_dice(100, seed))
print(roll_dice(1000, seed))
print(roll_dice(10000, seed))
Kết quả:
[10, 3.6][100, 3.5][1000, 3.495][10000, 3.503]
Kết quả:
[10, 3.8]
[100, 3.28]
[1000, 3.474]
[10000, 3.5508]
Khi số biến ngẫu nhiên, phân phối giống nhau tăng, trung bình mẫu sẽ tiến gần trung bình lý thuyết.
Mô phỏng 3 (seed = 3124):
print(roll_dice(100000, seed))
print(roll_dice(500000, seed))
print(roll_dice(1000000, seed))
Kết quả:
[100000, 3.51344]
[500000, 3.50428]
[1000000, 3.501995]
Mô phỏng Monte Carlo với Python