Monte Carlo Simulations in Python
Izzy Weber
Curriculum Manager, DataCamp
Questions
total_dice
: the number of dice in Tom's bag after $n$ rolls mean_point_dice
: the mean of all outcomes after $n$ rollsimport 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])
Simulation One:
seed=1231
print(roll_dice(10, seed))
print(roll_dice(100, seed))
print(roll_dice(1000, seed))
print(roll_dice(10000, seed))
Simulation Two:
seed=3124
print(roll_dice(10, seed))
print(roll_dice(100, seed))
print(roll_dice(1000, seed))
print(roll_dice(10000, seed))
Results:
[10, 3.6]
[100, 3.5]
[1000, 3.495]
[10000, 3.503]
Results:
[10, 3.8]
[100, 3.28]
[1000, 3.474]
[10000, 3.5508]
As the number of identically distributed, randomly generated variables increases, their sample mean approaches their theoretical mean.
Simulation Three (seed = 3124
):
print(roll_dice(100000, seed))
print(roll_dice(500000, seed))
print(roll_dice(1000000, seed))
Results:
[100000, 3.51344]
[500000, 3.50428]
[1000000, 3.501995]
Monte Carlo Simulations in Python