Monte Carlo Simulation
Whenever a quantity has no tidy analytical formula, random sampling provides a defensible answer instead. You draw inputs from a known distribution, push each draw through the function you care about, and average the results. That single idea powers option pricing, capacity planning, survey estimation, A/B test analysis, and inventory forecasting. In this lesson you will build the estimator from scratch, learn to attach a credible error bar to it, and apply the same machinery to bootstrapping and permutation testing.
Where closed-form math runs out
Plenty of real questions resist a neat formula. What is the expected total cost of a construction project whose labor, materials, and duration each vary? What is the 5th percentile of next quarter's revenue under three uncertain drivers? How likely is it that one marketing channel outperforms another when the observed difference is small and the data are skewed?
Analysts often reach for a normal approximation here, and that is exactly where trouble starts. Cost overruns are right-skewed, downtime is bursty, and revenue distributions are frequently bimodal. A symmetric approximation hides the tail risk that decision makers actually care about. Simulation sidesteps the derivation entirely: you never need to integrate the joint density by hand because you let thousands of random draws do the integration for you.
The practical payoff is that the output is a full distribution rather than a single number, so you can report medians, percentiles, and probability of breaching a budget instead of a fragile point estimate.
The estimator and its error bar
A Monte Carlo estimate is simply the sample mean of a function evaluated on independent draws. If you evaluate the function n times, the standard error of that mean shrinks at the rate of the square root of n. Halving the error therefore requires quadrupling the sample count, which is the single most important cost intuition in simulation work.
| Scenario | Draws | Typical error | Cost profile |
|---|---|---|---|
| Quick feasibility check | 1,000 | Wide, directionally useful | Milliseconds |
| Dashboard risk tile | 50,000 | Acceptable for decisions | Tens of milliseconds |
| Pricing or capital model | 1,000,000 | Stable percentiles | Seconds, parallelizable |
| Tail probability below 1 in 10,000 | 10,000,000+ | Still noisy | Batch job, needs care |
Always report the standard error alongside the estimate. A number without an error bar invites false precision, and readers cannot tell whether a 3 percent difference between two scenarios is signal or noise.
Estimating an integral by throwing darts
The classic demonstration estimates the area of a circle by scattering random points across a square and counting how many land inside. The same routine generalises to any integral: sample uniformly across the bounds, evaluate the integrand, scale by the width of the interval.
import numpy as np
def monte_carlo_integral(func, low, high, n_samples=500_000, seed=0):
"""Estimate a definite integral by uniform sampling."""
rng = np.random.default_rng(seed)
x = rng.uniform(low, high, n_samples)
values = func(x)
width = high - low
estimate = width * values.mean()
std_error = width * values.std(ddof=1) / np.sqrt(n_samples)
return estimate, std_error
def estimate_pi(n_samples=1_000_000, seed=1):
"""Throw darts at a square and count how many land in the circle."""
rng = np.random.default_rng(seed)
x = rng.uniform(-1, 1, n_samples)
y = rng.uniform(-1, 1, n_samples)
inside = np.count_nonzero(x**2 + y**2 <= 1)
return 4 * inside / n_samples
value, err = monte_carlo_integral(lambda x: np.exp(-x**2), 0.0, 2.0)
print(f"integral of exp(-x^2) on [0, 2] = {value:.6f} +/- {err:.6f}")
print(f"pi estimate = {estimate_pi():.5f}")
Notice that the function receives the whole array at once. Vectorising the evaluation is not a micro-optimisation; it is the difference between a script that finishes in a second and one that chews through a Python loop for minutes.
Bootstrap confidence intervals for messy statistics
The bootstrap applies the same sampling logic to your own dataset. You resample the observed data with replacement, recompute the statistic of interest on each resample, and look at the spread of those recomputed values. The beauty is that no distributional assumption is required, so it works for medians, ratios, correlations, quantiles, and other statistics that lack a textbook standard error.
The construction is honest about what the data can support. If your sample is small or the statistic is unstable, the bootstrap distribution comes out wide, and the confidence interval tells you so. If you report only the point estimate, that instability stays invisible.
import numpy as np
def bootstrap_ci(data, statistic=np.mean, n_boot=10_000, alpha=0.05, seed=42):
"""Percentile bootstrap confidence interval."""
rng = np.random.default_rng(seed)
data = np.asarray(data)
n = data.size
estimates = np.empty(n_boot)
for i in range(n_boot):
sample = data[rng.integers(0, n, n)]
estimates[i] = statistic(sample)
lower = np.percentile(estimates, 100 * alpha / 2)
upper = np.percentile(estimates, 100 * (1 - alpha / 2))
return {
"point": statistic(data),
"lower": lower,
"upper": upper,
"std_error": estimates.std(ddof=1),
}
session_lengths = [42, 51, 38, 96, 44, 61, 47, 88, 53, 120,
45, 39, 57, 72, 49, 63, 41, 95, 58, 46]
print(bootstrap_ci(session_lengths, statistic=np.median))
Swap the statistic function for a 90th percentile or a conversion ratio and the same code still works, which is why practitioners keep the bootstrap in their default toolkit.
Permutation tests for a difference in means
A permutation test answers a sharp question: if the group labels carried no information, how often would we see a gap at least this large? You pool the observations, shuffle the labels many times, recompute the difference in means each round, and compare the real gap against that null distribution.
Unlike a t-test, the permutation test inherits no normality assumption, and unlike a bootstrap on a single sample, it directly encodes the null hypothesis you are trying to reject. The p-value you compute is the share of shuffles that produced an equally extreme or more extreme result.
import numpy as np
def permutation_test(group_a, group_b, n_perm=20_000, seed=7):
"""Two-sided permutation test on the difference in means."""
rng = np.random.default_rng(seed)
a, b = np.asarray(group_a, float), np.asarray(group_b, float)
observed = a.mean() - b.mean()
pooled = np.concatenate([a, b])
n_a = a.size
null = np.empty(n_perm)
for i in range(n_perm):
shuffled = rng.permutation(pooled)
null[i] = shuffled[:n_a].mean() - shuffled[n_a:].mean()
p_value = (np.count_nonzero(np.abs(null) >= abs(observed)) + 1) / (n_perm + 1)
return observed, p_value, null
control = [12.1, 11.4, 13.0, 12.6, 11.9, 12.3, 12.8, 11.7, 12.5, 12.0]
treatment = [13.4, 12.9, 13.8, 13.1, 12.7, 13.6, 13.2, 12.8, 13.5, 13.0]
diff, p, null = permutation_test(control, treatment)
print(f"observed difference = {diff:.3f}, p-value = {p:.4f}")
The plus-one correction in the numerator and denominator keeps the estimate finite even when no shuffle beats the observed statistic.
Turning a budget estimate into a risk distribution
Once you can sample, a spreadsheet-style estimate becomes a distribution. Give each uncertain driver a distribution that matches how it behaves in practice: triangular for estimates with a most-likely value and hard bounds, lognormal for quantities that cannot go negative and have a long right tail, and uniform when you genuinely know only the range.
From the resulting distribution you extract the metrics stakeholders ask for: expected value, the value at risk, and the conditional tail expectation. Value at risk is the percentile you would lose at, while the conditional tail expectation averages the losses beyond that percentile and is usually the more honest number for worst-case planning.
import numpy as np
rng = np.random.default_rng(11)
n = 50_000
labor = rng.triangular(80_000, 100_000, 150_000, n)
materials = rng.normal(50_000, 10_000, n)
duration_months = rng.uniform(6, 12, n)
total = labor + materials + duration_months * 5_000
var_95 = np.percentile(total, 5)
cvar_95 = total[total <= var_95].mean()
print(f"expected cost ${total.mean():,.0f}")
print(f"median cost ${np.median(total):,.0f}")
print(f"5th percentile ${var_95:,.0f}")
print(f"tail average ${cvar_95:,.0f}")
print(f"P(over 200k) {(total > 200_000).mean():.3%}")
Because every driver is sampled independently here, the model assumes no correlation between labor and duration. Adding correlated draws is a deliberate modelling decision, and stating that assumption out loud is part of the result.
Convergence checks and variance reduction
A simulation that has not converged is worse than useless, because it looks precise while still being wrong. The cheap diagnostic is to run the estimate at increasing sample sizes and watch it settle: if the value at 100,000 draws differs materially from the value at 1,000,000, you are not ready to publish. A stronger check compares independent seeds; agreement across seeds suggests you have averaged out the sampling noise.
Variance reduction makes each draw count for more. Antithetic sampling draws a value and its mirror image, so the two cancel part of the randomness. Control variates subtract a quantity you already know analytically and add it back. Stratified sampling guarantees coverage of each region instead of trusting luck. All three leave the estimator unbiased while shrinking the error bar, which means you reach the same confidence with far fewer draws.
The habit worth building is mechanical: fix a seed, print the estimate with its standard error, double the sample size, and confirm the two agree before you send the number to anyone.
Best Practices
- Always report an estimate together with its standard error or percentile interval
- Vectorise function evaluation with NumPy arrays instead of looping over draws
- Run the same simulation with two seeds and increasing sample sizes before trusting it
- Choose distributions that match each driver's real-world shape, not just its mean
- State independence and correlation assumptions explicitly when presenting risk numbers
Common Mistakes
Quadrupling draws to halve the error, then wondering why the model feels slow
Fix: Start with 10,000 draws, measure the standard error, and only escalate the sample size when the decision needs the extra precision.
Treating a point estimate from simulation as ground truth
Fix: Publish the interval alongside the point estimate so readers can see how much of the number is sampling noise.
Using a normal approximation for a skewed cost or revenue driver
Fix: Sample the skewed distribution directly and report percentiles instead of a mean plus or minus two standard deviations.
Key Takeaways
- Monte Carlo integration estimates any quantity as the mean of a function evaluated on random draws
- Standard error shrinks with the square root of sample size, so precision gets expensive
- Bootstrapping gives confidence intervals for statistics without closed-form formulas
- Permutation tests produce p-values without assuming normality
- Percentile and tail metrics communicate risk far better than a single expected value