What is a Monte Carlo simulation?

Monte Carlo Simulations in Python

Izzy Weber

Curriculum Manager, DataCamp

Simulations and Monte Carlo simulations

Simulations:
  • Experiments that attempt to imitate reality
  • Often use computer programs

 

Monte Carlo simulations:
  • Used to predict the probability of different outcomes impacted by the presence of random variables
  • Rely on repeated random sampling to obtain numerical results
  • Results are stochastic since the model relies on random sampling
Monte Carlo Simulations in Python

Simulation example

Rolling six-sided die
  • Tom rolls a fair six-sided die $n$ times
  • After each roll, he records the outcome
  • He then places the die in a bag and selects a new one for the next roll

Questions

  1. How many dice will Tom collect after $n$ rolls?
  2. What will be the mean outcome after $n$ rolls?

 

a hand rolling a die

Monte Carlo Simulations in Python

Simulating Tom's outcomes

  • total_dice: the number of dice in Tom's bag after $n$ rolls
  • mean_point_dice: the mean of all outcomes after $n$ rolls
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])
Monte Carlo Simulations in Python

Simulation results

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]
Monte Carlo Simulations in Python

The Law of Large Numbers

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

Let's practice!

Monte Carlo Simulations in Python

Preparing Video For Download...