Module contents
Lesson 18 of 26Core 100 min

Monte Carlo: integration, error and stochastic simulation

Monte Carlo turns integrals and expectations into sample averages, with error decreasing as N^(-1/2) regardless of dimension. Formalize the estimator, error and confidence intervals, see when it beats quadrature and when it fails with heavy tails or rare events, and build a discrete-event simulator. Variance reduction and quasi-Monte Carlo are covered in m29.

After this lesson you can

  • Formulate an integral or expectation as a Monte Carlo estimator and prove its unbiasedness and variance.
  • Construct confidence intervals using the CLT and calculate the sample size needed for a given accuracy.
  • Compare Monte Carlo empirically with quadrature as dimension grows.
  • Detect infinite variance and rare events and explain why confidence intervals can mislead.
  • Implement a discrete-event simulator and estimate measures using batch means.

Before you start

Motivation: three questions without a formula

Three problems that arise sooner or later when building something real:

  • The expected value of a strategy. A trading rule with stop-loss, a reinforcement agent or an inventory policy produces a random outcome depending on the whole trajectory. Its expectation is an integral over trajectory space without a closed form, but you can simulate the strategy many times and average.
  • A system’s failure probability. A bridge, power grid or risk model must fail with probability below 10−610^{-6}. That probability is the expectation of an indicator, and simulating it seems easy until you realize that normally no failures appear in a million simulations.
  • An integral in 50 dimensions. The price of an option on a basket of 50 assets, or a posterior expectation with 50 parameters, is an integral in R50\R^{50}. In the quadrature lesson you saw that a grid with only 2 points per axis would have 250≈10152^{50} \approx 10^{15} nodes.

The Monte Carlo method answers all three with the same idea: write the quantity as an expectation, I=E[f(X)]I = \E[f(X)], draw independent samples from XX and average. What makes it an engineering tool is that the experiment itself tells you how much to trust the result: sample dispersion gives a standard error and confidence interval without knowing the answer. And that error decreases as N−1/2N^{-1/2} regardless of dimension.

The idea is old. In 1733 Buffon posed the probability that a needle thrown onto a plank floor crosses a joint, and published the solution in 1777: with needles of length ℓ\ell and joints separated by t≥ℓt \ge \ell it is 2ℓ/(πt)2\ell/(\pi t), so throwing needles estimates π\pi. Systematic use began at Los Alamos in the late 1940s with Stanislaw Ulam, John von Neumann and Nicholas Metropolis studying neutron diffusion; Metropolis proposed the casino-inspired name, and the first paper with that title was by Metropolis and Ulam (1949).

InteractiveBuffon and error bands
10 throws; hits in blue
2.83.03.23.43.6
40 replicates with the same N; red indicates intervals that miss π
  • Estimate ± 1.96 SE
  • π
Experiment
N = 10
Estimate of π2.8000
Estimated standard error0.5797
σ per throw1.642
Exact 95% CI coverage90.2 %
Replicates containing π37 of 40
With this seed, π\pi is inside the band at N=10N = 10.
Uniform darts in the unit square (hits fall inside the quarter circle, with probability π/4\pi/4), or Buffon needles as long as the spacing between lines (crossing with probability 2/π2/\pi; direction is drawn by rejection in the disk, without using π\pi). Below, the estimate of π\pi with one seed as NN grows and its band of ±1.96\pm 1.96 estimated standard errors, narrowing as 1/N1/\sqrt N. On the right, 40 independent replicas with the same NN; exact coverage sums the binomial probability of every count whose interval contains π\pi. How many red replicas do you expect? What happens to coverage with N=10N = 10? Which experiment gives narrower bands with the same NN?

Before reading the theory, notice three things. The band halves in width each time NN is multiplied by 4. About 2 of 40 replicas exclude π\pi, which is what “95%” means. And with small NN exact coverage departs from 95%, because the interval relies on a normal approximation that is not yet valid. This lesson explains all three.

The Monte Carlo estimator

Almost any numerical quantity in a stochastic model can be written as an expectation:

  • an integral over a bounded domain, ∫Dg(x) ⁣dx=∣D∣ E[g(U)]\int_D g(\vb{x})\dd\vb{x} = \abs{D}\,\E[g(\vb{U})] with U\vb{U} uniform on DD;
  • an integral against a density, ∫h(x) p(x) ⁣dx=Ep[h(X)]\int h(\vb{x})\,p(\vb{x})\dd\vb{x} = \E_p[h(\vb{X})];
  • a probability, P(A)=E[1[A]]\Pr(A) = \E[\ind[A]];
  • the value of a strategy or system, E[resultado]\E[\text{resultado}], where “outcome” is the output of a simulator fed random numbers.

To generate XiX_i you need the previous lesson: a pseudorandom generator producing uniforms and a transformation, such as the inversion method, taking them to the distribution of XX.

Proof

(1) By linearity of expectation, E[I^N]=1N∑iE[f(Xi)]=1N⋅NI=I\E[\hat I_N] = \frac1N\sum_i \E[f(X_i)] = \frac1N \cdot N I = I. Independence is unnecessary.

(2) The f(Xi)f(X_i) are independent, so their covariances vanish and the variance of the sum is the sum of variances: Var⁡(I^N)=1N2∑iVar⁡(f(Xi))=1N2⋅Nσ2=σ2/N\Var(\hat I_N) = \frac{1}{N^2}\sum_i \Var(f(X_i)) = \frac{1}{N^2}\cdot N\sigma^2 = \sigma^2/N. Since the estimator is unbiased, its mean squared error equals its variance.

(3) This is Kolmogorov’s strong law of large numbers applied to the f(Xi)f(X_i), which are iid and integrable. It requires only E∣f(X)∣<∞\E\abs{f(X)} < \infty. The weak law gives convergence in probability, and with σ2<∞\sigma^2 < \infty it follows directly from Chebyshev: P(∣I^N−I∣>ε)≤σ2/(Nε2)\Pr(\abs{\hat I_N - I} > \eps) \le \sigma^2/(N\eps^2).

∎

Point 2 is the lesson’s most important statement: typical error is σ/N\sigma/\sqrt N. To gain one decimal digit multiply NN by 100, without exception; and the only remaining lever if NN is limited is to reduce σ\sigma. Point 3 warns of something seen later: consistency does not require finite variance, but then there is no N−1/2N^{-1/2} rate or reliable standard error.

The same quantity has many representations as an expectation, each with its own σ\sigma. For π\pi there are two natural ones: the darts’ hit or miss, π=E[4 1[U2+V2≤1]]\pi = \E\big[4\,\ind[U^2 + V^2 \le 1]\big], and the mean value, π=∫0141+x2 ⁣dx=E[4/(1+U2)]\pi = \int_0^1 \frac{4}{1 + x^2}\dd x = \E\big[4/(1 + U^2)\big], with independent uniform U,VU, V on [0,1][0, 1].

[ ]Monte Carlo from scratch: π two waysBrowser
import numpy as np

rng = np.random.default_rng(2024)
N = 100_000

def resumen(nombre, y):
    """Estimación, error estándar e intervalo al 95 % de la media de y."""
    m = y.mean()
    se = y.std(ddof=1) / np.sqrt(len(y))
    print(f"{nombre:<26} {m:.5f} ± {se:.5f}   IC 95 % [{m - 1.96 * se:.5f}, {m + 1.96 * se:.5f}]   s = {y.std(ddof=1):.3f}")

# 1) acierto o fallo: 4·1[U² + V² ≤ 1], con (U, V) uniforme en el cuadrado unidad
u, v = rng.random(N), rng.random(N)
resumen("dardos 4·1[u² + v² ≤ 1]", 4.0 * (u * u + v * v <= 1.0))

# 2) valor medio: π = ∫₀¹ 4/(1 + x²) dx = E[4/(1 + U²)]
x = rng.random(N)
resumen("valor medio 4/(1 + U²)", 4.0 / (1.0 + x * x))

# varianzas exactas por muestra
p = np.pi / 4
var_dardos = 16 * p * (1 - p)
var_medio = 16 * (np.pi / 8 + 0.25) - np.pi**2      # E[16/(1+U²)²] - π², con ∫₀¹ dx/(1+x²)² = π/8 + 1/4
print(f"\nσ² exactas: dardos {var_dardos:.4f}, valor medio {var_medio:.4f}, cociente {var_dardos / var_medio:.2f}")
print(f"muestras para un error estándar de 1e-4: dardos {var_dardos / 1e-8:.2e}, valor medio {var_medio / 1e-8:.2e}")

With 10510^5 samples, darts give 3.14652±0.005183.14652 \pm 0.00518 and mean value 3.14019±0.002033.14019 \pm 0.00203: both intervals contain π\pi, but the second is 2.5 times narrower. Exact per-sample variances, 2.69682.6968 and 0.41360.4136, explain the difference: at equal accuracy, darts need 6.526.52 times more samples (2.70×1082.70 \times 10^8 versus 4.14×1074.14 \times 10^7 for standard error 10−410^{-4}). Here the two representations use different functions, but the conclusion is general: compared with the mean value of the same function, the indicator always loses. If 0≤g≤c0 \le g \le c on [0,1][0, 1], hit or miss uses Y=c 1[cV≤g(U)]Y = c\,\ind[cV \le g(U)], with E[Y2]=c E[g(U)]≥E[g(U)2]\E[Y^2] = c\,\E[g(U)] \ge \E[g(U)^2] because g≤cg \le c: their variances are c I−I2≥E[g2]−I2c\,I - I^2 \ge \E[g^2] - I^2, equal only if gg is 0 or cc almost everywhere. Darts are hit or miss for g(u)=41−u2g(u) = 4\sqrt{1 - u^2} with c=4c = 4, whose mean value has σ2=32/3−π2=0.797\sigma^2 = 32/3 - \pi^2 = 0.797, versus 2.6972.697. Throwing away information about how much gg is worth and keeping yes or no costs variance.

Buffon’s needles are even worse. With ℓ=t\ell = t they cross with probability p=2/πp = 2/\pi, and the natural estimate is π^=2/p^\hat\pi = 2/\hat p, a ratio. Its standard error follows from the delta method: if g(p)=2/pg(p) = 2/p, then Var⁡(π^)≈g′(p)2 p(1−p)N=π2 1−pNp\Var(\hat\pi) \approx g'(p)^2\,\frac{p(1 - p)}{N} = \pi^2\,\frac{1 - p}{Np}, which with p=2/πp = 2/\pi gives σeff=π3/2−π2≈2.37\sigma_{\text{eff}} = \sqrt{\pi^3/2 - \pi^2} \approx 2.37 per needle, versus 1.641.64 for darts.

Error, intervals and sample size

Typical error σ/N\sigma/\sqrt N depends on σ\sigma, which you do not know (if you knew E[f2]\E[f^2] you would probably know II). Estimate it using the same samples:

sN2=1N−1∑i=1N(f(Xi)−I^N)2,SE^=sNN.s_N^2 = \frac{1}{N - 1}\sum_{i=1}^N \big(f(X_i) - \hat I_N\big)^2, \qquad \widehat{\text{SE}} = \frac{s_N}{\sqrt N}.
Proof

The central limit theorem for iid f(Xi)f(X_i) with finite variance gives N(I^N−I)/σ→N(0,1)\sqrt N(\hat I_N - I)/\sigma \to \Normal(0, 1) in distribution. By the strong law applied to f(Xi)f(X_i) and f(Xi)2f(X_i)^2 (integrable because σ2<∞\sigma^2 < \infty), 1N∑f(Xi)2→E[f2]\frac1N\sum f(X_i)^2 \to \E[f^2] and I^N→I\hat I_N \to I almost surely, so sN2=NN−1(1N∑f(Xi)2−I^N2)→σ2s_N^2 = \frac{N}{N-1}\big(\frac1N\sum f(X_i)^2 - \hat I_N^2\big) \to \sigma^2 and, by continuity of the square root, sN→σ>0s_N \to \sigma > 0. Slutsky’s lemma allows σ\sigma to be replaced with sNs_N: N(I^N−I)sN=σsN⋅N(I^N−I)σ→1⋅Z\frac{\sqrt N(\hat I_N - I)}{s_N} = \frac{\sigma}{s_N}\cdot\frac{\sqrt N(\hat I_N - I)}{\sigma} \to 1 \cdot Z. Finally, II lies in the interval if and only if the preceding quotient has absolute value ≤z1−α/2\le z_{1-\alpha/2}, and since the normal distribution function is continuous at ±z1−α/2\pm z_{1-\alpha/2}, that probability tends to Φ(z1−α/2)−Φ(−z1−α/2)=1−α\Phi(z_{1-\alpha/2}) - \Phi(-z_{1-\alpha/2}) = 1 - \alpha.

∎

This is Monte Carlo error and its confidence interval: estimated standard error sN/Ns_N/\sqrt N and the 95% interval I^N±1.96 sN/N\hat I_N \pm 1.96\,s_N/\sqrt N. Three practical consequences:

  • How many samples. For half-width at level 1−α1 - \alpha to be ε\eps requires N≈(z1−α/2 σ/ε)2N \approx (z_{1-\alpha/2}\,\sigma/\eps)^2. Since σ\sigma is unknown, make a short pilot run, estimate ss and compute NN; or simulate in batches until half-width drops below ε\eps. For relative error εrel\eps_{\text{rel}}, N≈(z σ/(εrel∣I∣))2N \approx (z\,\sigma/(\eps_{\text{rel}}\abs{I}))^2: the determining quantity is coefficient of variation σ/∣I∣\sigma/\abs{I}.
  • What 95% means. It is a property of the procedure: if you repeat the experiment many times, 95% of intervals contain II. A particular interval either contains it or does not. This is what you saw in the interactive’s red replicas (the statistical confidence interval, with all its subtleties).
  • It is asymptotic. With finite NN coverage is not exactly 1−α1 - \alpha. If E∣f−I∣3=ρ3<∞\E\abs{f - I}^3 = \rho_3 < \infty, the Berry–Esseen bound limits normal approximation error: sup⁡x∣P(N(I^N−I)/σ≤x)−Φ(x)∣≤Cρ3/(σ3N)\sup_x \abs{\Pr(\sqrt N(\hat I_N - I)/\sigma \le x) - \Phi(x)} \le C\rho_3/(\sigma^3\sqrt N), with C≤0.4748C \le 0.4748 (Shevtsova, 2011). A very skewed integrand (with large ρ3/σ3\rho_3/\sigma^3) needs many samples before the interval deserves its name.

The cell measures actual coverage by repeating each experiment 2000 times, with a smooth integrand, a highly skewed one (e1.5Ze^{1.5Z}, lognormal) and an indicator of an event with probability 0.010.01.

[ ]Actual coverage of the 95% intervalBrowser
import numpy as np

rng = np.random.default_rng(1)
M = 2000                                   # repeticiones independientes del experimento

casos = {
    "U², suave":               (lambda m, n: rng.random((m, n))**2, 1 / 3),
    "lognormal, σ = 1.5":      (lambda m, n: np.exp(1.5 * rng.standard_normal((m, n))), np.exp(1.5**2 / 2)),
    "indicadora, p = 0.01":    (lambda m, n: (rng.random((m, n)) < 0.01).astype(float), 0.01),
}
print(f"{'integrando':<24}" + "".join(f"   N = {n:<5d}" for n in (10, 100, 1000)))
for nombre, (gen, mu) in casos.items():
    fila = []
    for n in (10, 100, 1000):
        Y = gen(M, n)
        m = Y.mean(axis=1)
        se = Y.std(axis=1, ddof=1) / np.sqrt(n)
        fila.append(np.mean(np.abs(m - mu) <= 1.96 * se))
    print(f"{nombre:<24}" + "".join(f"   {c:9.3f}" for c in fila))

# por qué falla la indicadora con N pequeño: muestras sin ningún acierto
for n in (10, 100, 1000):
    print(f"p = 0.01, N = {n:4d}: P(ningún acierto) = {(1 - 0.01)**n:.3f}  (el intervalo sale [0, 0])")

With the smooth integrand coverage is 0.8950.895 with N=10N = 10 and already 0.9450.945 with N=100N = 100. With the highly skewed lognormal it remains 0.7040.704, 0.8490.849 and 0.9240.924: even 1000 samples are insufficient. The indicator is extreme: with N=10N = 10 coverage is 0.0940.094, because 90.4% of experiments have no hits, I^N=0\hat I_N = 0, sN=0s_N = 0 and the interval is the point {0}\{0\}, which does not contain 0.010.01. It remains poor with N=100N = 100 (0.6640.664; 36.6% of experiments without hits). We return to this with rare events.

Streaming estimation: batched Welford

In a large Monte Carlo run you do not save 10910^9 samples: generate them in batches of 10410^4 to 10610^6 (for vectorization) and accumulate only what is needed for mean and variance. The temptation is to accumulate ∑y\sum y and ∑y2\sum y^2 and use s2=(∑y2−(∑y)2/n)/(n−1)s^2 = (\sum y^2 - (\sum y)^2/n)/(n-1). This is exactly the catastrophic cancellation from the rounding-errors lesson: subtracting two enormous, nearly equal numbers.

[ ]Variance with a naive one-pass methodBrowser
import numpy as np

rng = np.random.default_rng(3)
y = 1e9 + rng.random(100_000)              # σ² = 1/12 ≈ 0.0833 alrededor de un desplazamiento grande
n = len(y)
ingenua = (np.sum(y * y) - np.sum(y)**2 / n) / (n - 1)
print(f"Σy² - (Σy)²/n:      {ingenua:.4f}")
print(f"dos pasadas np.var: {np.var(y, ddof=1):.4f}")
print(f"exacta:             {1 / 12:.4f}")

The naive formula returns 0.00000.0000: with y≈109y \approx 10^9, ∑y2≈1023\sum y^2 \approx 10^{23} and its relative rounding error 2−532^{-53} already amounts to about 10710^7 units, much more than the centered sum of squares (≈8×103\approx 8 \times 10^3). The solution is to accumulate the triple (n,yˉ,M2)(n, \bar y, M_2) with M2=∑(yi−yˉ)2M_2 = \sum (y_i - \bar y)^2 instead of sums, as in Welford’s algorithm, and merge batch triples with the formula of Chan, Golub and LeVeque (1983).

Proof

The union’s mean is the weighted mean (nayˉa+nbyˉb)/n=yˉa+nbn(yˉb−yˉa)(n_a\bar y_a + n_b\bar y_b)/n = \bar y_a + \frac{n_b}{n}(\bar y_b - \bar y_a). For M2M_2, decompose each deviation: yi−yˉ=(yi−yˉa)+(yˉa−yˉ)y_i - \bar y = (y_i - \bar y_a) + (\bar y_a - \bar y) in batch aa. Squaring and summing over aa, the cross term vanishes because ∑a(yi−yˉa)=0\sum_a (y_i - \bar y_a) = 0, leaving Ma+na(yˉa−yˉ)2M_a + n_a(\bar y_a - \bar y)^2. Likewise for bb. Since yˉa−yˉ=−δnb/n\bar y_a - \bar y = -\delta n_b/n and yˉb−yˉ=δna/n\bar y_b - \bar y = \delta n_a/n, the sum is Ma+Mb+δ2(nanb2+nbna2)/n2=Ma+Mb+δ2nanb/nM_a + M_b + \delta^2\big(n_a n_b^2 + n_b n_a^2\big)/n^2 = M_a + M_b + \delta^2 n_a n_b/n.

∎

All subtractions involve quantities on the order of the dispersion rather than the data size, and each batch is summarized with vectorized operations (y.mean() and ((y - m)**2).sum(), which NumPy sums pairwise). This is what you implement in code exercise mc_estimate, the lab’s centerpiece: a batched estimator with standard error and interval that works with any batch size, offset and NN.

Dimension: the rate does not depend on d, but σ does

In the Monte Carlo estimator, the dimension of XX appears nowhere: error is σ/N\sigma/\sqrt N whether XX is a number or a million-component vector. Compare this with the product rule of lesson 11, whose error with N=ndN = n^d evaluations is O(N−r/d)\bigO(N^{-r/d}) for a 1D rule of order rr. Trapezoidal quadrature (r=2r = 2) has slope −2/d-2/d on a log–log scale: steeper than Monte Carlo’s −1/2-1/2 if d<4d < 4, equal at d=4d = 4 and flatter thereafter.

The rate not depending on dd does not make dimension free: constant σ\sigma does depend on dd, potentially in any way. Two extreme examples with gg on [0,1][0, 1], ∫g=μg\int g = \mu_g and UU uniform on [0,1]d[0, 1]^d:

  • Product. For f(x)=∏k=1dg(xk)f(\vb{x}) = \prod_{k=1}^d g(x_k), coordinate independence gives E[f]=μgd\E[f] = \mu_g^d and E[f2]=E[g2]d\E[f^2] = \E[g^2]^d, and the coefficient of variation is σdI=(E[g2]μg2)d−1,\frac{\sigma_d}{I} = \sqrt{\Big(\frac{\E[g^2]}{\mu_g^2}\Big)^{d} - 1}, which grows exponentially with dd whenever gg is nonconstant (by Jensen, E[g2]>μg2\E[g^2] > \mu_g^2).
  • Mean. For f(x)=1d∑k=1dg(xk)f(\vb{x}) = \frac1d\sum_{k=1}^d g(x_k), Var⁡(f)=Var⁡(g)/d\Var(f) = \Var(g)/d: variance decreases with dd and the problem gets easier as dimension grows.

Real integrands lie between the two. This is what Monte Carlo in high dimensions means: the N−1/2N^{-1/2} rate is the same in any dimension, making it competitive exactly where quadrature suffers the curse of dimensionality, but the problem’s difficulty transfers entirely to σ\sigma.

InteractiveMonte Carlo versus the grid by dimension
  • Product trapezoid
  • Monte Carlo, σ/√N
  • Monte Carlo, one run
6
3
Theoretical grid slope, −2/d−0.333
Measured trapezoid slope−0.366
Measured Monte Carlo slope (one run)−0.40
Exact relative Monte Carlo σ0.722
With about 10610^6 evaluations (n=10n = 10 per axis): trapezoid 6.1·10⁻³, Monte Carlo 7.2·10⁻⁴. The grid slope −2/d-2/d is less than 1/21/2 in absolute value: Monte Carlo wins beyond a certain NN, sooner for larger dd.
Relative error versus number of evaluations NN for f(x)=e−∥x∥2f(\vb{x}) = e^{-\norm{\vb{x}}^2} on [0,1]d[0, 1]^d. Since ff is separable, the product rule with nn points per axis gives exactly QndQ_n^d and error ∣(Qn/I1)d−1∣\abs{(Q_n/I_1)^d - 1}, computed here for each nn; the dashed magenta line is Monte Carlo's exact root-mean-square error, σrel(d)/N\sigma_{\text{rel}}(d)/\sqrt N, and the blue one an actual run. Increase dd: what happens to the grid slope? And Monte Carlo's? Why does the magenta line rise? Enable Gauss–Legendre: with an analytic integrand, up to what dimension does it keep up with Monte Carlo?

The grid benefits from this integrand being separable and analytic, its ideal case. The cell compares all three methods with a budget of about 10510^5 evaluations, using the same 1D rules as lesson 11, and adds an integrand that is neither: the unit-ball indicator, whose integral in [0,1]d[0, 1]^d is vol⁡(Bd)/2d=πd/2/(Γ(d/2+1) 2d)\operatorname{vol}(B_d)/2^d = \pi^{d/2}/(\Gamma(d/2 + 1)\,2^d).

[ ]Monte Carlo versus the lesson 11 gridBrowser
import numpy as np
from math import erf, lgamma, log, pi, sqrt, exp

# integrando gaussiano separable en [0, 1]^d: f(x) = exp(-|x|²), I = I1^d
I1 = sqrt(pi) / 2 * erf(1.0)
Eg2 = sqrt(pi / 8) * erf(sqrt(2.0))               # ∫₀¹ e^{-2x²} dx

def trap(n):
    x = np.linspace(0, 1, n)
    y = np.exp(-x * x)
    return (y.sum() - 0.5 * (y[0] + y[-1])) / (n - 1)

def gauss(n):
    t, w = np.polynomial.legendre.leggauss(n)
    return 0.5 * w @ np.exp(-((t + 1) / 2) ** 2)

rng = np.random.default_rng(7)
B = 100_000                                        # presupuesto de evaluaciones
print("error relativo con unas 10^5 evaluaciones de f(x) = exp(-|x|²) en [0, 1]^d")
print("  d    n   N = n^d   trapecio    Gauss     MC (real)  MC (SE est.)  σ_rel exacta")
for d in (1, 2, 3, 5, 10, 20, 50):
    n = int(np.floor(B ** (1 / d) + 1e-9))
    N = n ** d
    e_t = abs((trap(n) / I1) ** d - 1) if n >= 2 else float("nan")
    e_g = abs((gauss(min(n, 40)) / I1) ** d - 1)   # Gauss con como mucho 40 nodos por eje: ya es exacta en 1D
    X = rng.random((B, d))
    f = np.exp(-(X * X).sum(axis=1)) / I1 ** d     # normalizada: su media es 1
    s_rel = sqrt((Eg2 / I1 ** 2) ** d - 1)
    print(f" {d:3d} {n:5d} {N:9d}   {e_t:9.1e} {e_g:9.1e}   {abs(f.mean() - 1):9.1e}  {f.std(ddof=1) / sqrt(B):9.1e}     {s_rel:7.3f}")

print("\nvolumen de la bola unidad dentro de [0, 1]^d (indicadora, no separable)")
for d in (2, 5, 10, 20):
    I = exp(d / 2 * log(pi) - lgamma(d / 2 + 1)) / 2 ** d
    X = rng.random((B, d))
    f = ((X * X).sum(axis=1) <= 1.0).astype(float)
    print(f" d = {d:2d}: exacto {I:.3e}   σ_rel = {sqrt((1 - I) / I):8.1f}   MC {f.mean():.3e} ± {f.std(ddof=1) / sqrt(B):.1e}   ({int(f.sum())} aciertos)")

Read the table by rows. At d=1d = 1 trapezoidal quadrature with 10510^5 points has error 8.2×10−128.2 \times 10^{-12} and Monte Carlo 4.3×10−44.3 \times 10^{-4}: in low dimensions Monte Carlo cannot compete. At d=5d = 5 the grid fits only 10 points per axis and trapezoidal error is 5.1×10−35.1 \times 10^{-3}, worse than Monte Carlo (5.7×10−45.7 \times 10^{-4}, with estimated standard error 2.0×10−32.0 \times 10^{-3}). At d=10d = 10 trapezoidal quadrature with 3 points per axis is at 0.190.19; Gauss, which uses its 3 nodes very effectively on an analytic integrand, still wins (1.3×10−41.3 \times 10^{-4} versus 3.7×10−33.7 \times 10^{-3}), as seen in lesson 11. At d=20d = 20 and d=50d = 50 no grid with 2 points per axis fits the budget (220≈1062^{20} \approx 10^6), the 1-point grid is useless (error 1.31.3 and 7.17.1), and Monte Carlo gives 1.0×10−21.0 \times 10^{-2} and 1.8×10−21.8 \times 10^{-2}, consistent with its estimated standard errors. Notice the last column too: σrel\sigma_{\text{rel}} goes from 0.2690.269 at d=1d = 1 to 5.665.66 at d=50d = 50, the product case’s exponential growth.

The ball shows the other side. Its σrel=(1−I)/I\sigma_{\text{rel}} = \sqrt{(1 - I)/I} goes from 0.50.5 at d=2d = 2 to 20.020.0 at d=10d = 10 and 63746374 at d=20d = 20, because relative volume plummets (2.5×10−32.5 \times 10^{-3} and 2.5×10−82.5 \times 10^{-8}). With 10510^5 samples in d=20d = 20 none falls inside: Monte Carlo returns 0±00 \pm 0. Dimension has not changed the rate; it has turned the problem into one of rare events.

When Monte Carlo fails

Everything above rests on σ2<∞\sigma^2 < \infty and NN being large enough for the CLT to work. There are two common ways to break this, both dangerous because the estimator gives no warning: it returns a number and a plausible-looking standard error.

Heavy tails and infinite variance

A typical heavy-tailed variable is Pareto with P(X>x)=x−α\Pr(X > x) = x^{-\alpha} for x≥1x \ge 1, sampled by inversion as X=U−1/αX = U^{-1/\alpha}. Its moments are E[Xk]=α/(α−k)\E[X^k] = \alpha/(\alpha - k) if k<αk < \alpha and infinite if k≥αk \ge \alpha. For 1<α≤21 < \alpha \le 2 mean α/(α−1)\alpha/(\alpha - 1) is finite and variance infinite: the strong law holds and I^N→I\hat I_N \to I, but the classical CLT does not. (The boundary case α=2\alpha = 2 still admits a CLT with normalization Nlog⁡N\sqrt{N\log N}; the serious problem is α<2\alpha < 2.)

What happens instead is described by the generalized CLT: for 1<α<21 < \alpha < 2, (SN−Nμ)/N1/α(S_N - N\mu)/N^{1/\alpha} converges to a stable law, so mean error is of order N1/α−1N^{1/\alpha - 1} instead of N−1/2N^{-1/2}. With α=1.5\alpha = 1.5, N−1/3N^{-1/3}: to gain one digit multiply NN by 1000, not 100. And estimated standard error is misleading: sNs_N is dominated by the few largest samples seen so far, and because the truly important ones usually have not yet appeared, it tends to be too small. Giné, Götze and Mason (1997) proved that statistic tt, N(I^N−I)/sN\sqrt N(\hat I_N - I)/s_N, is asymptotically N(0,1)\Normal(0, 1) if and only if the law of f(X)f(X) is in the normal domain of attraction; with α<2\alpha < 2 it is not, and interval coverage does not tend to 95% however large NN grows. This section studies heavy tails and Monte Carlo failures, where the mean converges very slowly and the calculated interval misleads.

[ ]Heavy tails: the mean of a ParetoBrowser
import numpy as np

rng = np.random.default_rng(11)

def pareto(alpha, size):                           # inversión: X = U^{-1/α} tiene P(X > x) = x^{-α}, x ≥ 1
    return (1.0 - rng.random(size)) ** (-1.0 / alpha)

print("cobertura del intervalo al 95 % para la media de una Pareto (500 repeticiones)")
print(f"{'α':>5} {'media':>7} {'varianza':>9}   N = 100   N = 1000   N = 10000")
for alpha in (1.5, 2.5, 4.0):
    mu = alpha / (alpha - 1)
    var = alpha / ((alpha - 1) ** 2 * (alpha - 2)) if alpha > 2 else np.inf
    fila = []
    for n in (100, 1000, 10_000):
        Y = pareto(alpha, (500, n))
        m = Y.mean(axis=1)
        se = Y.std(axis=1, ddof=1) / np.sqrt(n)
        fila.append(np.mean(np.abs(m - mu) <= 1.96 * se))
    print(f"{alpha:5.1f} {mu:7.3f} {var:9.3f}   " + "   ".join(f"{c:7.3f}" for c in fila))

# una trayectoria con α = 1.5: la media salta cuando llega una muestra enorme
alpha, n = 1.5, 100_000
y = pareto(alpha, n)
k = np.arange(1, n + 1)
media = np.cumsum(y) / k
i_max = int(np.argmax(y))
print(f"\nα = 1.5, media real 3: la mayor de {n} muestras es {y[i_max]:.0f} (posición {i_max + 1}), el {100 * y[i_max] / y.sum():.1f} % de la suma")
print(f"media acumulada justo antes: {media[i_max - 1]:.3f}, justo después: {media[i_max]:.3f}, al final: {media[-1]:.3f}")
print(f"error estándar estimado antes del salto: {y[:i_max].std(ddof=1) / np.sqrt(i_max):.3f}")

With α=1.5\alpha = 1.5 nominal 95% coverage remains 0.6920.692, 0.7660.766 and 0.7520.752 for N=102N = 10^2, 10310^3 and 10410^4: it does not improve with NN, as Giné, Götze and Mason predict. With α=2.5\alpha = 2.5 (finite variance but infinite third moment) it reaches 0.9300.930 and 0.9340.934, and with α=4\alpha = 4, 0.940.94. The trajectory shows the mechanism: after 31 63831\,638 samples the mean was 2.8562.856 with estimated standard error 0.0570.057, so its interval, [2.74,2.97][2.74, 2.97], excluded the true mean 3; a sample of 15 73515\,735 arrives (5.2% of the sum of 10510^5) and the mean jumps to 3.3533.353, almost nine of those standard errors at once.

InteractiveThe heavy-tail trap
  • Running mean ± 1.96 SE
  • True mean
1.50
True mean α/(α − 1)3.000
Variance∞
Mean with N = 100 k3.242 ± 0.538
Share of the sum from the largest sample (27.2 k, at n = 89.4 k)8.4 %
Actual 95% CI coverage (400 replicates, N = 1000)72.5 %
With α≤2\alpha \le 2 the variance is infinite: the estimated standard error is random and often too small. Right before its largest sample, this run had mean 2.95 and standard error 0.032.
Running mean of Pareto samples X=U−1/αX = U^{-1/\alpha} with its band of ±1.96\pm 1.96 standard errors estimated with Welford, and true mean α/(α−1)\alpha/(\alpha - 1) dashed; actual coverage is measured with 400 replicas of N=1000N = 1000. With α=1.5\alpha = 1.5, how long does the band fail to contain the true mean? What happens when the largest sample appears? Change the seed several times and then move α\alpha above 2: what changes in coverage?

In the interactive you will see the signature of infinite variance: long stretches where the mean is below the true one with a narrow, reassuring band, interrupted by vertical jumps. The closer α\alpha is to 1, the worse; for α<1\alpha < 1 there is not even a mean. How to detect it in practice:

  • Think before simulating. Does f(X)2f(X)^2 have finite expectation? A ratio with a denominator that can approach 0, importance weights with a lighter-tailed proposal than the target, or an exponential payoff of a normal variable are usual suspects.
  • Inspect the largest contribution. If the largest sample contributes an appreciable percentage of the sum, the mean depends on a few samples.
  • Estimate the tail. The Hill estimator on the largest samples gives index α\alpha; if near 2 or below, distrust the interval.
  • Compare standard error across halves or batches. With finite variance, independent batch standard errors are similar; with heavy tails they vary by orders of magnitude.

Rare events

To estimate p=P(A)p = \Pr(A) with the indicator, p^=K/N\hat p = K/N with K∼Bin⁡(N,p)K \sim \Bin(N, p) and σ2=p(1−p)\sigma^2 = p(1 - p). Absolute error p(1−p)/N\sqrt{p(1 - p)/N} seems small, but what matters is relative error,

Var⁡(p^)p=1−pNp≈1Np,\frac{\sqrt{\Var(\hat p)}}{p} = \sqrt{\frac{1 - p}{Np}} \approx \frac{1}{\sqrt{Np}},

which depends only on the expected number of events NpNp. For 10% about 100 events are needed, that is, N≈100/pN \approx 100/p: 10810^8 simulations for p=10−6p = 10^{-6}. And with NpNp of order 1 the estimator is almost always 0 or several times pp: the probability of seeing no event is (1−p)N≈e−Np(1 - p)^N \approx e^{-Np}.

[ ]Rare events: relative errorBrowser
import numpy as np

rng = np.random.default_rng(5)
print("p̂ = K/N con K ~ Bin(N, p): 2000 repeticiones simulando directamente el recuento")
for p, N in [(1e-4, 10_000), (1e-4, 1_000_000), (1e-6, 100_000_000)]:
    K = rng.binomial(N, p, size=2000)
    phat = K / N
    teor = np.sqrt((1 - p) / (N * p))
    print(f" p = {p:.0e}, N = {N:.0e}: Np = {N * p:6.0f}   error relativo teórico {teor:.3f}, observado {phat.std() / p:.3f}"
          f"   P(K = 0) = {np.mean(K == 0):.3f} (teórica {(1 - p) ** N:.3f})")

# regla del tres: con 0 aciertos en N, la cota superior al 95 % es -ln(0.05)/N ≈ 3/N
print(f"\n-ln(0.05) = {-np.log(0.05):.3f}")

The cell does not simulate 10810^8 indicators: it directly draws count KK from its binomial law, a legitimate and useful trick when only the number of samples falling in AA matters. With Np=1Np = 1 observed relative error is 1.0081.008 (theoretical 1.0001.000) and 37.0% of experiments see no event (theoretical e−1=0.368e^{-1} = 0.368). With Np=100Np = 100 relative error is 0.1000.100, both for p=10−4p = 10^{-4} with 10610^6 samples and for p=10−6p = 10^{-6} with 10810^8: all that counts is NpNp.

If you see no events, do not say “p=0±0p = 0 \pm 0”. You can give a bound: if pp were greater than c/Nc/N, the probability of seeing nothing would be (1−p)N≤e−c(1 - p)^N \le e^{-c}, and for that to be 0.050.05 requires c=−ln⁡0.05=2.996c = -\ln 0.05 = 2.996. This is the rule of three: with 0 events in NN attempts, p≤3/Np \le 3/N at 95%.

InteractiveCounting rare events
Exact distribution of estimate p̂ in units of p (red: p̂ = 0)
0pp̂ = p2p3p
95% intervals from 30 replicates, in units of p
Red: no events (interval [0, 0]); orange: interval that does not contain p.
10⁻⁴
10⁴
Expected events Np1.00
Relative error √((1 − p)/(Np))1.000
P(no events) = (1 − p)^N36.8 %
N for 10% relative error10⁶
Replicates with no events12 of 30
With Np=1.00Np = 1.00 the estimator is almost always 0 or several times pp. If it is 0, the rule of three gives the 95% upper bound: p≤3/Np \le 3/N, here 3.0·10⁻⁴.
Above, the exact distribution of p^/p\hat p/p with K∼Bin⁡(N,p)K \sim \Bin(N, p); in red, mass at p^=0\hat p = 0. Below, 30 simulated replicas (the count is drawn from a Poisson with mean NpNp, at most pp away from the binomial in total variation) with their 95% Wald interval in units of pp. How many replicas see 0 events with Np=1Np = 1? How wide is their interval? How much must you increase NN for all replicas to be within 20% of pp?

The remedy is to change the sampling distribution so the event is no longer rare and correct with weights: importance sampling for rare events in the simulation module can reduce cost by many orders of magnitude.

Stochastic simulation

Until now XX was a fixed-dimensional vector. In a stochastic simulation XX is an entire trajectory of a random system, potentially of random length, and ff is what you measure on it. Monte Carlo is unchanged: simulate NN independent trajectories and average.

Random walks

The simplest example is a simple random walk: a bet winning 1 with probability pp and losing 1 with probability q=1−pq = 1 - p, repeated until winning aa or losing aa. This is gambler’s ruin and has an exact solution: if hkh_k is the probability of reaching 2a2a before 0 from kk, first-step analysis gives hk=p hk+1+q hk−1h_k = p\,h_{k+1} + q\,h_{k-1} with h0=0h_0 = 0, h2a=1h_{2a} = 1, whose solution with r=q/p≠1r = q/p \ne 1 is hk=(1−rk)/(1−r2a)h_k = (1 - r^k)/(1 - r^{2a}), and starting at 0 means starting at k=ak = a. The vectorized simulation advances all surviving walks together.

[ ]Random walk: gambler's ruinBrowser
import numpy as np

rng = np.random.default_rng(8)
p, a, R = 0.48, 10, 20_000                         # sube con probabilidad p; se para en +a o en -a

pos = np.zeros(R, dtype=np.int64)
pasos = np.zeros(R, dtype=np.int64)
vivo = np.ones(R, dtype=bool)
while vivo.any():
    idx = np.flatnonzero(vivo)
    pos[idx] += np.where(rng.random(idx.size) < p, 1, -1)
    pasos[idx] += 1
    vivo[idx] = np.abs(pos[idx]) < a

gana = (pos == a).astype(float)
r = (1 - p) / p
exacta = (1 - r ** a) / (1 - r ** (2 * a))         # P(llegar a +a antes que a -a desde 0)
m, se = gana.mean(), gana.std(ddof=1) / np.sqrt(R)
print(f"P(ganar 10 antes de perder 10), p = {p}: Monte Carlo {m:.4f} ± {se:.4f}, exacta {exacta:.4f}")
print(f"duración media: {pasos.mean():.1f} ± {pasos.std(ddof=1) / np.sqrt(R):.1f} pasos; la más larga, {pasos.max()}")

With only a two-point house advantage (p=0.48p = 0.48), the probability of winning 10 before losing 10 falls to 0.30990.3099; Monte Carlo gives 0.3115±0.00330.3115 \pm 0.0033. Duration has no such handy formula, but Monte Carlo gives it just as easily: 95.1±0.595.1 \pm 0.5 steps on average, with one game lasting 816. This estimates a strategy’s expected value by simulating it in full.

Discrete-event simulation

Many systems (queues, networks, warehouses, order-book markets) change state only at specific times: a customer arrives, a service ends, an order arrives. Between two such events nothing relevant happens, so advancing the clock in fixed steps makes no sense. Discrete-event simulation advances the clock event by event with a priority queue, and its time-correlated outputs require batch means. Its pieces:

  1. the system state (customers waiting, server idle or busy, stock level);
  2. the clock tt;
  3. the future event list, a priority queue (a binary heap) of (time, event) pairs, ordered by time;
  4. one routine per event type updating state and scheduling events it causes;
  5. measurement accumulators: each customer’s wait or areas under curves such as queue length, for time averages.

The main loop is always the same: remove the nearest event from the heap, advance the clock to its time and execute its routine. An often-forgotten detail: two events may have the same time, and comparing actions to break ties either fails or depends on irrelevant details; each entry therefore carries an increasing counter fixing arrival order.

The reference system is the M/M/1 queue: Poisson arrivals at rate λ\lambda, exponential services at rate μ\mu, one server and FIFO order. Customer count is a birth–death process that, if utilization ρ=λ/μ\rho = \lambda/\mu is less than 1, has a stationary geometric distribution, πn=(1−ρ)ρn\pi_n = (1 - \rho)\rho^n. From this follow mean queue length Lq=ρ2/(1−ρ)L_q = \rho^2/(1 - \rho) and, by Little’s law (L=λWL = \lambda W, Little 1961), mean queue wait,

Wq=Lqλ=ρμ−λ.W_q = \frac{L_q}{\lambda} = \frac{\rho}{\mu - \lambda}.

If ρ≥1\rho \ge 1 there is no stationary regime: the queue grows without bound.

InteractiveM/M/1 queue simulator
arrivalsserverqueue: 0
Clock t = 0.00
System empty. The first arrival is scheduled.
Future event list
▸ 0.28: arrival 1
event 0 of 80
  • Running mean from customer 1
  • Theoretical W_q
0.80
1.00
Chart
Utilization ρ = λ/μ0.800
Theoretical W_q = ρ/(μ − λ)4.000
Simulated W_q (45.0 k customers)3.826
± 1.96 naive SE (as if independent)± 0.041
± t·SE by means of 20 batches± 0.323
Autocorrelation at lags 1 and 1000.955, 0.030
The batch standard error is 7.4 times the naive one: consecutive waits are correlated and the naive interval is 7.4 times too narrow.
Above, event simulation of the first 40 customers: the clock jumps to the first event in the future event list (in M/M/1 there are at most two: next arrival and next departure). Below, 50,000 customers with the same arrival and service times, whose waits are computed using Lindley's recursion Wk+1=max⁡(0,Wk+Sk−Ak+1)W_{k+1} = \max(0, W_k + S_k - A_{k+1}), giving exactly the same waits as event simulation in a single-server FIFO queue. Advance event by event: when does list order change? Raise λ\lambda until ρ=0.95\rho = 0.95: how long does the mean take to approach the theoretical one? How much wider is the honest interval than the naive one?

The first discrete-event lab is a generic engine of about twenty lines over heapq and, with it, the M/M/cM/M/c queue with cc servers. Wait intervals are computed with batch means, justified in the next section.

[ ]A discrete-event engine and the M/M/1 queueBrowser
import heapq
import itertools
import numpy as np

class Motor:
    """Reloj y lista de eventos futuros: (instante, desempate, acción, argumentos)."""
    def __init__(self):
        self.t = 0.0
        self.eventos = []
        self._orden = itertools.count()             # desempate FIFO entre eventos simultáneos
    def programa(self, retardo, accion, *args):
        heapq.heappush(self.eventos, (self.t + retardo, next(self._orden), accion, args))
    def ejecuta(self, hasta=np.inf):
        n = 0
        while self.eventos and self.eventos[0][0] <= hasta:
            self.t, _, accion, args = heapq.heappop(self.eventos)
            accion(*args)
            n += 1
        return n

def cola_mmc(lam, mu, c, n_clientes, semilla):
    """M/M/c FIFO. Devuelve las esperas en cola, la longitud media de la cola en el tiempo, los eventos y el tiempo final."""
    rng = np.random.default_rng(semilla)
    A = rng.exponential(1 / lam, n_clientes)        # tiempos entre llegadas
    S = rng.exponential(1 / mu, n_clientes)         # tiempos de servicio
    m = Motor()
    cola, libres = [], [c]
    espera = np.empty(n_clientes)
    area = [0.0, 0.0]                               # ∫ (clientes en cola) dt y último instante

    def acumula():
        area[0] += len(cola) * (m.t - area[1])
        area[1] = m.t

    def llegada(i):
        acumula()
        if i + 1 < n_clientes:
            m.programa(A[i + 1], llegada, i + 1)
        if libres[0] > 0:
            libres[0] -= 1
            espera[i] = 0.0
            m.programa(S[i], salida)
        else:
            cola.append((i, m.t))

    def salida():
        acumula()
        if cola:
            j, t_llegada = cola.pop(0)
            espera[j] = m.t - t_llegada
            m.programa(S[j], salida)
        else:
            libres[0] += 1

    m.programa(A[0], llegada, 0)
    n_eventos = m.ejecuta()
    return espera, area[0] / m.t, n_eventos, m.t

def ic_lotes(x, b=20, t=2.093):
    """Media e intervalo al 95 % por medias de b lotes contiguos (t: cuantil 0.975 de la t con b - 1 g.l.)."""
    lotes = x[: len(x) // b * b].reshape(b, -1).mean(axis=1)
    return lotes.mean(), t * lotes.std(ddof=1) / np.sqrt(b)

lam, mu = 0.8, 1.0
rho = lam / mu
espera, Lq, n_ev, T = cola_mmc(lam, mu, 1, 50_000, semilla=1)
m, h = ic_lotes(espera[5000:])
print(f"M/M/1, ρ = {rho}: {n_ev} eventos, {T:.0f} unidades de tiempo simuladas")
print(f"  espera media en cola W_q: simulada {m:.3f} ± {h:.3f}, teórica ρ/(μ - λ) = {rho / (mu - lam):.3f}")
print(f"  clientes en cola L_q:     simulada {Lq:.3f}, teórica ρ²/(1 - ρ) = {rho**2 / (1 - rho):.3f}")
print(f"  Little con todos los clientes: λ·(espera media) = {lam * espera.mean():.3f}")

The engine processes 10510^5 events (one arrival and one departure per customer) over about 62 50062\,500 simulated time units. For ρ=0.8\rho = 0.8 the simulated mean wait, discarding the first 5000 customers, is 4.075±0.3774.075 \pm 0.377, consistent with the theoretical 4. Notice the width: with 45,000 customers the interval has nearly 10% half-width because consecutive waits are highly correlated (as you will soon see). Mean queue length 3.2183.218 matches ρ2/(1−ρ)=3.2\rho^2/(1 - \rho) = 3.2. The last line is Little’s law from within: area under queue length divided by total time is exactly λobs\lambda_{\text{obs}} times mean wait, and with nominal rate λ\lambda agrees to three digits.

The same engine serves any system by changing only routines. Two examples with known theoretical results: the M/M/cM/M/c queue, whose waiting probability is Erlang’s C formula, and base-stock inventory: demand arrives as a Poisson process at rate λ\lambda, each unit sold triggers a replenishment order taking fixed lead time LL, and demand is backordered if stock is unavailable. Inventory position (stock plus orders in transit minus backorders) is always SS, so in stationarity available stock is (S−D)+(S - D)^+, with D∼Pois⁡(λL)D \sim \Pois(\lambda L) demand during a lead time, and demand is served immediately with probability P(D≤S−1)\Pr(D \le S - 1).

[ ]M/M/c and inventory with the same engineBrowser
import numpy as np
from math import factorial
from scipy import stats

def erlang_c(c, a):
    """Probabilidad de esperar en M/M/c con carga ofrecida a = λ/μ < c."""
    suma = sum(a**k / factorial(k) for k in range(c))
    cola = a**c / factorial(c) * c / (c - a)
    return cola / (suma + cola)

lam, mu, c = 2.4, 1.0, 3
espera, Lq, _, _ = cola_mmc(lam, mu, c, 60_000, semilla=2)
x = espera[5000:]
m, h = ic_lotes(x)
pe, he = ic_lotes((x > 0).astype(float))
print(f"M/M/3, ρ = {lam / (c * mu):.1f}: P(esperar) simulada {pe:.3f} ± {he:.3f}, Erlang C {erlang_c(c, lam / mu):.3f}")
print(f"  W_q simulada {m:.3f} ± {h:.3f}, teórica C/(cμ - λ) = {erlang_c(c, lam / mu) / (c * mu - lam):.3f}")

# Inventario con política de stock base: cada demanda (Poisson de tasa λ) dispara un pedido
# de una unidad que llega tras un plazo fijo L. Sin stock, la demanda queda pendiente.
def inventario(lam, L, S, horizonte, semilla):
    rng = np.random.default_rng(semilla)
    m = Motor()
    est = {"stock": S, "pendientes": 0, "servidas": 0, "demandas": 0, "area": 0.0, "t0": 0.0}

    def acumula():
        est["area"] += est["stock"] * (m.t - est["t0"])
        est["t0"] = m.t

    def demanda():
        acumula()
        est["demandas"] += 1
        if est["stock"] > 0:
            est["stock"] -= 1
            est["servidas"] += 1
        else:
            est["pendientes"] += 1
        m.programa(L, llega_pedido)
        m.programa(rng.exponential(1 / lam), demanda)

    def llega_pedido():
        acumula()
        if est["pendientes"] > 0:
            est["pendientes"] -= 1                  # la unidad se entrega a un cliente que esperaba
        else:
            est["stock"] += 1

    m.programa(rng.exponential(1 / lam), demanda)
    m.ejecuta(hasta=horizonte)
    acumula()
    return est["area"] / m.t, est["servidas"] / est["demandas"]

lam, L, S = 5.0, 2.0, 12
stock_medio, fill = inventario(lam, L, S, horizonte=20_000, semilla=3)
D = stats.poisson(lam * L)                          # demanda durante el plazo
k = np.arange(0, S + 1)
print(f"\nstock base S = {S}, demanda λ = {lam}, plazo L = {L}")
print(f"  stock medio: simulado {stock_medio:.3f}, teórico E[(S - D)⁺] = {np.sum((S - k) * D.pmf(k)):.3f}")
print(f"  tasa de servicio inmediato: simulada {fill:.4f}, teórica P(D ≤ S - 1) = {D.cdf(S - 1):.4f}")

With three servers at 80%, simulated waiting probability is 0.653±0.0130.653 \pm 0.013 versus Erlang C’s 0.6470.647, and mean wait 1.177±0.1561.177 \pm 0.156 versus 1.0791.079: a difference of 0.60.6 half-widths, noise. (Without the interval, 1.1771.177 versus 1.0791.079 would look like a 9% simulator error.) In inventory, with λL=10\lambda L = 10 units of mean lead-time demand and S=12S = 12, mean stock is 2.5512.551 versus theoretical 2.5312.531 and 69.9% of demands are served immediately, versus P(D≤11)=0.6968\Pr(D \le 11) = 0.6968. Notice what did not need changing: the engine is the same; only state and event routines change.

Correlated outputs and transients

A discrete-event simulation produces one long trajectory, W1,W2,…W_1, W_2, \dots, and we want its stationary mean. Two things distinguish it from textbook Monte Carlo.

The transient. Simulation begins in an arbitrary state (empty queue), not a sample from the stationary distribution. Early observations are biased, and bias lasts longer for slower systems. The standard solution is a warm-up period: discard early observations, choosing how many from the mean of many replicas Wˉk\bar W_k as a function of kk (Welch’s method), showing when it stabilizes.

Correlation. If a customer waits a long time, the next probably will too. For a stationary sequence with variance σ2\sigma^2 and autocorrelations ρh\rho_h,

Var⁡(WˉN)=σ2N[1+2∑h=1N−1(1−hN)ρh]  ≈  σ2 τN,τ=1+2∑h≥1ρh,\Var(\bar W_N) = \frac{\sigma^2}{N}\Big[1 + 2\sum_{h=1}^{N-1}\Big(1 - \frac hN\Big)\rho_h\Big] \;\approx\; \frac{\sigma^2\,\tau}{N}, \qquad \tau = 1 + 2\sum_{h \ge 1}\rho_h,

if autocorrelations are summable. Factor τ\tau (the integrated autocorrelation time) converts NN correlated observations into N/τN/\tau equivalent independent observations; it is the same factor seen in the Markov-chain CLT and MCMC effective sample size. Naive standard error s/Ns/\sqrt N ignores τ\tau and is τ\sqrt\tau times too small.

Batch means estimate σ2τ\sigma^2\tau without computing autocorrelations: split the series (after warm-up) into bb contiguous batches of length m=N/bm = N/b. If m≫τm \gg \tau, batch means Wˉ(1),…,Wˉ(b)\bar W^{(1)}, \dots, \bar W^{(b)} are nearly independent and nearly normal, each with variance ≈σ2τ/m\approx \sigma^2\tau/m, and the interval

Wˉ±tb−1, 0.975 slotesb\bar W \pm t_{b-1,\,0.975}\,\frac{s_{\text{lotes}}}{\sqrt b}

has correct coverage. Use few batches (between 10 and 30) so each is long; with b=20b = 20, t19, 0.975=2.093t_{19,\,0.975} = 2.093.

[ ]Warm-up and batch meansBrowser
import numpy as np

def lindley(lam, mu, n, R, rng, w0=0.0):
    """R réplicas independientes de M/M/1 a la vez: W_{k+1} = max(0, W_k + S_k - A_{k+1})."""
    W = np.empty((R, n))
    w = np.full(R, w0)
    for k in range(n):
        W[:, k] = w
        w = np.maximum(0.0, w + rng.exponential(1 / mu, R) - rng.exponential(1 / lam, R))
    return W

rng = np.random.default_rng(4)
mu = 1.0
lam = 0.9
Wq = lam / (mu * (mu - lam))
R = 2000
W = lindley(lam, mu, 3000, R, rng)
print(f"ρ = 0.9, W_q = {Wq:.1f}; arrancando vacía, media de {R} réplicas de W_k:")
for k in (10, 100, 300, 1000, 2999):
    col = W[:, k]
    print(f"  k = {k:4d}: {col.mean():5.2f} ± {col.std(ddof=1) / np.sqrt(R):.2f}")
print(f"media de los primeros 1000 clientes: {W[:, :1000].mean():.2f}  (sesgo {W[:, :1000].mean() - Wq:+.2f})")

# cobertura: intervalo ingenuo frente a medias por lotes, ρ = 0.8, 200 réplicas
lam = 0.8
Wq = lam / (mu * (mu - lam))
R, n, calent, b = 200, 20_000, 2000, 20
W = lindley(lam, mu, calent + n, R, rng)[:, calent:]
m = W.mean(axis=1)
se_ing = W.std(axis=1, ddof=1) / np.sqrt(n)
lotes = W.reshape(R, b, n // b).mean(axis=2)
se_lot = lotes.std(axis=1, ddof=1) / np.sqrt(b)
t975 = 2.093                                         # cuantil 0.975 de la t de Student con 19 grados de libertad
x = W[0] - W[0].mean()
acf = [float(x[:-h] @ x[h:] / (x @ x)) for h in (1, 10, 50)]
print(f"\nρ = 0.8, W_q = {Wq:.1f}, {n} clientes tras {calent} de calentamiento, {R} réplicas")
print(f"  autocorrelación de W_k a retardo 1, 10, 50 (una réplica): {acf[0]:.3f}, {acf[1]:.3f}, {acf[2]:.3f}")
print(f"  error estándar ingenuo medio {se_ing.mean():.3f}, por lotes {se_lot.mean():.3f}, real (entre réplicas) {m.std(ddof=1):.3f}")
print(f"  cobertura al 95 %: ingenuo {np.mean(np.abs(m - Wq) <= 1.96 * se_ing):.3f}, lotes {np.mean(np.abs(m - Wq) <= t975 * se_lot):.3f}")

Lindley’s recursion, vectorized across replicas, reveals the transient directly. With ρ=0.9\rho = 0.9 and the queue initially empty, customer 10’s mean wait is 2.332.33, customer 100’s 6.566.56, and customer 300’s 8.218.21, against stationary value 9; around customer 1000 the curve is indistinguishable from 9 within the noise of 2000 replicas (9.23±0.239.23 \pm 0.23). Averaging the first 1000 customers gives 8.208.20: bias −0.80-0.80, 9%, which no number of replicas fixes because it is not noise. The closer ρ\rho is to 1, the longer the transient.

The second part measures correlation’s damage with ρ=0.8\rho = 0.8. Waits have autocorrelation 0.9680.968 at lag 1, 0.7550.755 at lag 10 and still 0.3220.322 at lag 50. Mean naive standard error is 0.0350.035; batch-means error 0.2920.292; and actual error, measured as dispersion of 200 independent replica means, 0.3340.334. The naive one is wrong by a factor of 9.5, that is, τ≈90\tau \approx 90: twenty thousand customers are worth about two hundred independent ones. The practical result is coverage: the naive interval contains the true mean in 14.5% of replicas; the batch interval in 92.5%, somewhat below 95% because with batches of 1000 customers adjacent batch means remain slightly correlated. Longer batches (fewer batches or more simulation) bring it closer to nominal.

Large-scale, reproducible Monte Carlo

A serious Monte Carlo run uses 10810^8 or 101010^{10} samples, split into batches and often across several processes or GPUs. Two rules make it fast and correct.

Vectorize by batch. A Python loop generating and evaluating one sample at a time pays interpreter overhead each iteration; a batch of 10410^4 to 10610^6 samples is generated and evaluated with a few NumPy calls (or PyTorch on GPU). Batch size is a tradeoff: large enough to amortize overhead and small enough to fit in cache or memory. With batched Welford the result does not depend on chosen size, and during accumulation NumPy’s pairwise sum (the pairwise summation of lesson 2) keeps rounding error at O(log⁡N)\bigO(\log N) units of roundoff instead of O(N)\bigO(N).

One independent stream per worker. If every process creates its generator with the same seed, all generate the same samples: the combined mean does not improve, but calculated standard error is divided by procesos\sqrt{\text{procesos}}. Seeding with semilla + i works with default_rng because SeedSequence mixes the seed before use, but for generators naively converting seed to state, similar seeds yield correlated streams (Matsumoto and coauthors, 2007, document this for several classic generators). The correct approach, as seen with independent streams in tools, is to derive streams from a root seed with SeedSequence.spawn, which separates them with a hash, or use a counter-based generator like Philox, where each worker uses a distinct key and coordination is unnecessary.

[ ]In batches with independent streamsBrowser
import time
import numpy as np

# 1) vectorizar por lotes: el mismo estimador con un bucle de Python y con NumPy
rng = np.random.default_rng(0)
n = 200_000
t0 = time.perf_counter()
s = 0.0
for _ in range(n):
    u = rng.random()
    s += 4.0 / (1.0 + u * u)
t_bucle = time.perf_counter() - t0
t0 = time.perf_counter()
s2 = 0.0
for lote in range(20):
    u = rng.random(10_000)
    s2 += np.sum(4.0 / (1.0 + u * u))
t_lotes = time.perf_counter() - t0
print(f"bucle: {s / n:.5f}   lotes de 10^4: {s2 / n:.5f}   el bucle tarda {t_bucle / t_lotes:.0f} veces más")

# 2) flujos para 4 trabajadores: misma semilla frente a SeedSequence.spawn
def trabajador(gen, n=50_000):
    u = gen.random(n)
    return np.mean(4.0 / (1.0 + u * u))

misma = [trabajador(np.random.default_rng(42)) for _ in range(4)]
hijos = np.random.SeedSequence(42).spawn(4)
indep = [trabajador(np.random.default_rng(h)) for h in hijos]
print("misma semilla:  ", np.round(misma, 6))
print("spawn:          ", np.round(indep, 6))
print(f"error de la media combinada: misma semilla {abs(np.mean(misma) - np.pi):.1e}, spawn {abs(np.mean(indep) - np.pi):.1e}")
print(f"SE que se declararía con 4·50000 muestras: {np.sqrt(0.4136 / 200_000):.1e}; SE real con muestras repetidas: {np.sqrt(0.4136 / 50_000):.1e}")

# 3) un generador basado en contador: el flujo k es la clave k, sin coordinación
gens = [np.random.Generator(np.random.Philox(key=k)) for k in range(3)]
print("Philox, primeros valores de las claves 0, 1, 2:", [round(g.random(), 4) for g in gens])

In this browser’s Python, the sample-by-sample loop takes on the order of a hundred times longer than 10410^4 batches for the same estimator (the exact ratio varies by run; in ours, between 76 and 103). With the same seed, all four workers return exactly the same number, 3.1394033.139403: combined mean error is 2.2×10−32.2 \times 10^{-3}, while the standard error you would report believing you had 2×1052 \times 10^5 samples would be 1.4×10−31.4 \times 10^{-3}; the actual error is that of 5×1045 \times 10^4 samples, 2.9×10−32.9 \times 10^{-3}. With spawn, the four estimates differ and the combined one has error 3.0×10−43.0 \times 10^{-4}.

In libraries

ToolWhat it doesWhen
np.random.default_rng(semilla)PCG64 generator with vectorized samplers (random, normal, exponential, binomial, choice…)always; request batches, not individual samples
np.random.SeedSequence(s).spawn(k), rng.spawn(k)kk independent streams derived from a root seedparallel processes, threads or GPUs
np.random.Generator(np.random.Philox(key=k))counter-based generator; key identifies streammassive parallelism without coordination, reproducibility by key
rng.binomial(N, p), rng.poisson(lam)simulate a count without simulating each trialrare events, Monte Carlo histograms
scipy.stats.<dist>.rvs(size, random_state=rng)samples from any SciPy distributiondistributions without a NumPy sampler
scipy.stats.qmc, scipy.integrate.qmc_quadlow-discrepancy sequences and randomized quasi-Monte Carlo quadrature with error estimationsmooth integrals in moderate dimension (simulation module)
heapqbinary heap on a listcustom simulator event list
SimPyprocess-oriented discrete-event simulation (Python generators)large models with many resource types

What remains for other modules

This lesson quantifies Monte Carlo error; the simulation module reduces it. Antithetic variates, control variates and stratified sampling lower σ\sigma with the same NN; importance sampling tackles rare events; and quasi-Monte Carlo replaces random samples with Sobol sequences, with error bounded by the Koksma–Hlawka inequality and near N−1N^{-1} for regular integrands, recovering estimable error with the randomized version. When you cannot sample XX directly, only evaluate its density up to a constant, Markov chain Monte Carlo produces correlated samples, whose error analysis uses this lesson’s batch means. In quantitative finance, Monte Carlo option pricing, VaR and Expected Shortfall use this estimator; in reinforcement, Monte Carlo prediction estimates values by averaging returns; and the bootstrap is Monte Carlo on the empirical distribution.

Common mistakes

Exercises

NumericHow many samples?
An integrand has per-sample standard deviation σ=0.5\sigma = 0.5. How many samples does the Monte Carlo estimator need for standard error 10−310^{-3}?
NumericOne failure in a million
You estimate probability p=10−6p = 10^{-6} with N=108N = 10^8 independent simulations and the event indicator. Approximately what is the relative error (standard deviation of p^\hat p divided by pp)?
NumericLazzarini's standard error
Lazzarini threw N=3408N = 3408 needles with ℓ/t=5/6\ell/t = 5/6, so each crosses with probability p=2ℓ/(πt)p = 2\ell/(\pi t), and estimated π^=2(ℓ/t)N/K\hat\pi = 2(\ell/t)N/K. Using the delta method, what is the standard error of π^\hat\pi (evaluated at the true value of pp)?
NumericThe price of discarding information
You want to estimate ∫01x2 ⁣dx\int_0^1 x^2\dd x. Hit-or-miss uses Y=1[V≤U2]Y = \ind[V \le U^2]; mean value uses Y=U2Y = U^2 (independent uniform U,VU, V). How many times more samples does hit-or-miss need for the same standard error?
NumericA cashier at 90%
Customers arrive at a cashier as a Poisson process at 0.9 per minute and service times are exponential with mean 1 minute. In stationarity, how many minutes does a customer wait in the queue on average?
QuizFree in dimension 1000?
Monte Carlo error is σ/N\sigma/\sqrt N and does not depend on dimension. Why can a problem in dimension 1000 still be hard?
QuizAn overly reassuring interval
You estimate a portfolio's mean loss, whose losses approximately follow a Pareto law with tail index α=1.7\alpha = 1.7. With N=106N = 10^6 simulations you obtain 2.41±0.022.41 \pm 0.02 at 95%. Which statement is correct?
QuizTwo intervals for the same queue
You simulate a queue with ρ=0.8\rho = 0.8, discard warm-up and obtain Wˉ=4.05\bar W = 4.05 with 20,000 customers. The naive interval ±1.96 s/N\pm 1.96\,s/\sqrt N is ±0.069\pm 0.069; the one from 20 batch means is ±0.61\pm 0.61. What happens?
QuizEight processes, one seed
To speed up Monte Carlo you launch 8 processes; each executes rng = np.random.default_rng(42), generates 10610^6 samples and returns its mean. You combine all 8 means and standard error as if you had 8×1068\times 10^6 samples. What have you obtained?
ProofUnbiasedness, variance and interval
Prove: Let X1,…,XNX_1, \dots, X_N be iid with the law of XX, ff with 0<σ2=Var⁡(f(X))<∞0 < \sigma^2 = \Var(f(X)) < \infty, I=E[f(X)]I = \E[f(X)] and I^N=1N∑f(Xi)\hat I_N = \frac1N\sum f(X_i). Prove E[I^N]=I\E[\hat I_N] = I, Var⁡(I^N)=σ2/N\Var(\hat I_N) = \sigma^2/N and that I^N±z1−α/2 sN/N\hat I_N \pm z_{1-\alpha/2}\,s_N/\sqrt N has asymptotic coverage 1−α1 - \alpha.
0
Call Yi=f(Xi)Y_i = f(X_i): they are iid with mean II and variance σ2\sigma^2.

Step 1 of 5. Why is E[I^N]=I\E[\hat I_N] = I?

CodeA batched Monte Carlo estimator
Implement mc_estimate(f, sampler, n, batch, rng), processing exactly n samples in batches of size batch (the last may be smaller) and returning (estimacion, se, (lo, hi)): the mean, standard error s/ns/\sqrt n with ss the sample standard deviation (n−1n - 1 in the denominator), and the 95% interval with z=1.96z = 1.96. sampler(rng, k) returns k samples and f transforms them into an array of k values. Do not save all samples: summarize each batch with its mean and centered sum of squares and merge summaries. It must work with shifted data (for example 109+U10^9 + U) and give the same result regardless of batch.
import numpy as np

def mc_estimate(f, sampler, n, batch, rng):
  """Devuelve (estimacion, se, (lo, hi)) con el intervalo al 95 %."""
  # tu código: recorre n muestras en lotes, resume cada lote con (k, media, M2)
  # y fusiona los resúmenes
  return 0.0, 0.0, (0.0, 0.0)
Shift+Enter to run

Summary

Key idea
Monte Carlo writes the desired quantity as an expectation and estimates it with a mean of independent samples: it is unbiased, typical error is σ/N\sigma/\sqrt N in any dimension, and the experiment gives its own standard error and interval. Difficulty lies in σ\sigma (which can grow with dimension or be infinite) and the independence and finite-variance assumptions, which must be checked before trusting the interval.
  • Estimator I^N=1N∑f(Xi)\hat I_N = \frac1N\sum f(X_i) is unbiased, has variance σ2/N\sigma^2/N and converges almost surely even if σ2=∞\sigma^2 = \infty. Different representations of the same quantity have different σ\sigma: hit-or-miss always loses to mean value.
  • Interval I^N±1.96 sN/N\hat I_N \pm 1.96\,s_N/\sqrt N is asymptotic (CLT and Slutsky); with skewed integrands or small-probability indicators, coverage at moderate NN can be far below 95%. Error ε\eps requires N≈(1.96 σ/ε)2N \approx (1.96\,\sigma/\eps)^2 samples.
  • In streaming, summarize each batch with (n,yˉ,M2)(n, \bar y, M_2) and merge with Chan–Golub–LeVeque; formula ∑y2−(∑y)2/n\sum y^2 - (\sum y)^2/n is destroyed by cancellation.
  • Rate N−1/2N^{-1/2} does not depend on dd and beats the grid (N−r/dN^{-r/d}) once d>2rd > 2r; but σ\sigma depends on dd, and can grow exponentially or turn the problem into rare events.
  • With infinite variance (Pareto with α≤2\alpha \le 2) the mean converges slowly in jumps and the interval misleads regardless of NN. For rare events relative error is 1/Np1/\sqrt{Np}: 100/p100/p samples are needed for 10%, and zero events only give bound p≤3/Np \le 3/N.
  • Discrete-event simulation advances the clock event by event with a heap; its outputs have transients and correlation, analyzed with warm-up and batch means. Naive standard error can be τ\sqrt\tau times too small.
  • At scale: vectorized batches, pairwise sums and an independent stream per worker using SeedSequence.spawn or Philox keys.

Further reading. Chapters 1 and 2 of Owen’s freely available Monte Carlo theory, methods and examples are the best modern introduction, treating error and intervals carefully. Robert and Casella (chapter 3) cover Monte Carlo integration with more statistics, and Glasserman’s chapter 1 the financial motivation. Law’s Simulation Modeling and Analysis is the discrete-event simulation reference: output analysis, warm-up and batch means. The original Metropolis and Ulam paper (1949) is a quick read.