Skip to content
Tactiverge

Monte Carlo simulation and randomness

Use random numbers to estimate π, see how the error shrinks with more samples, and propagate measurement uncertainty through a calculation or a whole simulation.

Lesson 6 of 6 · 30 min · Self-paced · Free

Answers from randomness

So far, every simulation in this module has been deterministic: the same inputs always give the same output. But real engineering inputs are rarely known exactly. A part's length has a tolerance. A drag coefficient is an estimate. A sensor reading has noise. Engineers want to know: given that the inputs are uncertain, how uncertain is the answer?

Monte Carlo simulation answers this by brute force. Draw random inputs that match what you know about the uncertainty, run the calculation, repeat thousands of times, and look at the spread of the outputs. The name comes from the famous casino in Monaco, a nod to the role of chance. The method needs no advanced mathematics, works on almost any model, and is used everywhere from reliability engineering to robot motion planning.

A first example: estimating π

Imagine a square of side 1 with a quarter circle of radius 1 drawn inside it, centred on one corner. The quarter circle's area is π/4; the square's is 1. Scatter points uniformly at random over the square. The fraction landing inside the quarter circle should be about π/4, so

π ≈ 4 × (points inside) / (total points)

A point (x, y) is inside if x² + y² ≤ 1.

import math
import random

random.seed(2024)

def estimate_pi(n):
    inside = 0
    for _ in range(n):
        x, y = random.random(), random.random()
        if x * x + y * y <= 1.0:
            inside += 1
    return 4 * inside / n

for n in [100, 10_000, 1_000_000]:
    est = estimate_pi(n)
    print(f"N = {n:>9,}   estimate = {est:.5f}   error = {est - math.pi:+.5f}")

Output:

N =       100   estimate = 3.32000   error = +0.17841
N =    10,000   estimate = 3.11520   error = -0.02639
N = 1,000,000   estimate = 3.14267   error = +0.00108

random.random() returns a number between 0 and 1. random.seed(2024) makes the sequence repeatable: anyone running this code gets exactly these numbers. Computers produce pseudo-random numbers from a formula, which look random for practical purposes but are fully determined by the seed. That is a feature: a Monte Carlo result you cannot reproduce is hard to check.

How fast does the error shrink?

Each point is like a coin flip that lands "inside" with probability π/4. The same √n law from the measurement uncertainty lesson applies: the typical error is about √(π(4 − π) / N) ≈ 1.64 / √N. That predicts about 0.16 for N = 100, 0.016 for N = 10,000 and 0.0016 for N = 1,000,000, consistent with the errors above. Each extra correct digit costs 100 times more samples. Monte Carlo is a poor way to compute π precisely, but the same 1/√N behaviour holds no matter how complicated the model is, and that is where Monte Carlo shines.

Propagating measurement uncertainty

A pendulum's period T and length L give the local gravitational acceleration:

g = 4π² L / T²

Suppose you measured (made-up values for illustration) L = 1.000 m with an uncertainty of 0.005 m, and T = 2.006 s with an uncertainty of 0.010 s, where each uncertainty is one standard deviation. How uncertain is g?

import math
import random
import statistics

random.seed(7)
# Made-up measurements for illustration: a simple pendulum
L_MEAN, L_SD = 1.000, 0.005   # length, m
T_MEAN, T_SD = 2.006, 0.010   # period, s

samples = []
for _ in range(100_000):
    L = random.gauss(L_MEAN, L_SD)
    T = random.gauss(T_MEAN, T_SD)
    samples.append(4 * math.pi**2 * L / T**2)

g_mean = statistics.mean(samples)
g_sd = statistics.stdev(samples)
print(f"g = {g_mean:.3f} ± {g_sd:.3f} m/s² (Monte Carlo, 100,000 samples)")

# Compare with the usual first-order formula for relative uncertainty
g0 = 4 * math.pi**2 * L_MEAN / T_MEAN**2
rel = math.sqrt((L_SD / L_MEAN) ** 2 + (2 * T_SD / T_MEAN) ** 2)
print(f"g = {g0:.3f} ± {g0 * rel:.3f} m/s² (formula)")

Output:

g = 9.811 ± 0.109 m/s² (Monte Carlo, 100,000 samples)
g = 9.811 ± 0.109 m/s² (formula)

random.gauss(mean, sd) draws from a normal (bell-shaped) distribution. The Monte Carlo answer matches the standard propagation of uncertainty formula, which adds relative uncertainties in quadrature, counting T twice because it is squared. Notice that the period's 0.5% uncertainty contributes a 1% uncertainty to g, twice the length's contribution. That tells you where to spend effort: time more swings.

When the formula applies, it is quicker. Monte Carlo's advantage is that it still works when the formula does not: when uncertainties are large, when the calculation is a whole simulation, or when you want the full spread of outcomes rather than one number.

Uncertainty through a whole simulation

In the drag lesson we assumed a table-tennis ball has C_d = 0.47. Suppose (an assumption for illustration) we only know C_d to about ±0.05, as one standard deviation. How uncertain is the landing time from 10 m? There is no formula for it, but we can run the drag simulation a thousand times:

import math
import random
import statistics

random.seed(5)
G, RHO, MASS = 9.81, 1.2, 0.0027
AREA = math.pi * 0.020 ** 2

def drop_time(cd, height=10.0, dt=0.001):
    t, y, v = 0.0, 0.0, 0.0
    while y < height:
        a = G - 0.5 * RHO * cd * AREA * v * v / MASS
        y, v, t = y + v * dt, v + a * dt, t + dt
    return t

# Assumption for illustration: Cd is 0.47 give or take 0.05 (one sd)
times = [drop_time(random.gauss(0.47, 0.05)) for _ in range(1000)]
times.sort()
print(f"mean landing time: {statistics.mean(times):.3f} s")
print(f"sd:                {statistics.stdev(times):.3f} s")
print(f"middle 95%:        {times[25]:.3f} s to {times[974]:.3f} s")

Output:

mean landing time: 1.751 s
sd:                0.035 s
middle 95%:        1.679 s to 1.822 s

After sorting, the 26th and 975th values bracket the middle 95% of the 1000 outcomes. So a fair statement is: "assuming C_d = 0.47 ± 0.05, the simulated landing time is about 1.75 s, with 95% of simulated outcomes between 1.68 and 1.82 s." That is far more useful than a single number, because it says how much to trust the prediction.

Recap

  • Monte Carlo methods estimate answers by repeating a calculation with random inputs and studying the outputs.
  • Random-number generators are pseudo-random; set a seed so results can be reproduced.
  • The error of a Monte Carlo estimate shrinks as 1/√N: 100 times more samples for each extra digit.
  • To propagate uncertainty, draw each uncertain input from its distribution, compute the result, and report the spread.
  • Monte Carlo works even when there is no formula, including through a whole simulation.

Knowledge check

Check your understanding

  1. 1. In the π estimate, 7,850 of 10,000 random points land inside the quarter circle. What is the estimate of π?
  2. 2. A Monte Carlo estimate has a typical error of 0.02 with 10,000 samples. About how many samples are needed for an error of 0.002?
  3. 3. Why set a random seed in a Monte Carlo program?
  4. 4. In g = 4π²L/T², why did the 0.5% uncertainty in T matter more than the 0.5% uncertainty in L?
  5. 5. What is the main advantage of Monte Carlo over the propagation-of-uncertainty formula?

Go further