15  Monte Carlo

A Monte Carlo simulation is a method that uses repeated random sampling to approximate a solution or gain insight into a problem. Monte Carlo simulations are often straight forward, and are parituclarly useful when analytical solutions are challenging or impractical.

In this chapter, we will make heavy use of numpy’s pseudorandom number generator along with pyplt. Recall that np.random.rand() returns a uniform random number between \(0\) and \(1\).

import numpy as np 
import matplotlib.pyplot as plt

print( np.random.rand() )
0.5498236409094327

15.1 Monte Carlo Simulations

Let’s say that you wanted to know if a coin was fair with equal probability of heads or tails. One test you can do is to flip the coin a million times and see if you get heads about as many times as you get tails. This is a Monte Carlos simulation!

The examples below all have a similar structure: some random process is simulated and tracked over many iterations. The Coin simulation counts the number of heads and tails for \(100\) trials.

15.2 Coin

heads = 0
tails = 0

for i in range(100):
  n = np.random.rand() 
  if n > 0.5:
    heads += 1
  else:
    tails += 1

plt.bar( ["H", "T"], [heads, tails] )

15.3 Die

15.4 Dice

15.5 Cards