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
- 09Inverse transform samplingPseudorandom number generatorsCounter-based RNGsCurse of dimensionality in quadratureGauss-Hermite quadrature for Gaussian expectationsWelford's online mean and varianceRecursive and pairwise summation
- 04Weak law of large numbersStrong law of large numbersCentral limit theoremExpectationVariance and moments
- 00Pseudorandom generators and independent streams
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 . 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 . In the quadrature lesson you saw that a grid with only 2 points per axis would have nodes.
The Monte Carlo method answers all three with the same idea: write the quantity as an expectation, , draw independent samples from 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 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 and joints separated by it is , so throwing needles estimates . 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).
Before reading the theory, notice three things. The band halves in width each time is multiplied by 4. About 2 of 40 replicas exclude , which is what “95%” means. And with small 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, with uniform on ;
- an integral against a density, ;
- a probability, ;
- the value of a strategy or system, , where “outcome” is the output of a simulator fed random numbers.
To generate you need the previous lesson: a pseudorandom generator producing uniforms and a transformation, such as the inversion method, taking them to the distribution of .
Proof
(1) By linearity of expectation, . Independence is unnecessary.
(2) The are independent, so their covariances vanish and the variance of the sum is the sum of variances: . 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 , which are iid and integrable. It requires only . The weak law gives convergence in probability, and with it follows directly from Chebyshev: .
∎Point 2 is the lesson’s most important statement: typical error is . To gain one decimal digit multiply by 100, without exception; and the only remaining lever if is limited is to reduce . Point 3 warns of something seen later: consistency does not require finite variance, but then there is no rate or reliable standard error.
The same quantity has many representations as an expectation, each with its own . For there are two natural ones: the darts’ hit or miss, , and the mean value, , with independent uniform on .
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 samples, darts give and mean value : both intervals contain , but the second is 2.5 times narrower. Exact per-sample variances, and , explain the difference: at equal accuracy, darts need times more samples ( versus for standard error ). 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 on , hit or miss uses , with because : their variances are , equal only if is 0 or almost everywhere. Darts are hit or miss for with , whose mean value has , versus . Throwing away information about how much is worth and keeping yes or no costs variance.
Buffon’s needles are even worse. With they cross with probability , and the natural estimate is , a ratio. Its standard error follows from the delta method: if , then , which with gives per needle, versus for darts.
Error, intervals and sample size
Typical error depends on , which you do not know (if you knew you would probably know ). Estimate it using the same samples:
Proof
The central limit theorem for iid with finite variance gives in distribution. By the strong law applied to and (integrable because ), and almost surely, so and, by continuity of the square root, . Slutsky’s lemma allows to be replaced with : . Finally, lies in the interval if and only if the preceding quotient has absolute value , and since the normal distribution function is continuous at , that probability tends to .
∎This is Monte Carlo error and its confidence interval: estimated standard error and the 95% interval . Three practical consequences:
- How many samples. For half-width at level to be requires . Since is unknown, make a short pilot run, estimate and compute ; or simulate in batches until half-width drops below . For relative error , : the determining quantity is coefficient of variation .
- What 95% means. It is a property of the procedure: if you repeat the experiment many times, 95% of intervals contain . 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 coverage is not exactly . If , the Berry–Esseen bound limits normal approximation error: , with (Shevtsova, 2011). A very skewed integrand (with large ) 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 (, lognormal) and an indicator of an event with probability .
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 with and already with . With the highly skewed lognormal it remains , and : even 1000 samples are insufficient. The indicator is extreme: with coverage is , because 90.4% of experiments have no hits, , and the interval is the point , which does not contain . It remains poor with (; 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 samples: generate them in batches of to (for vectorization) and accumulate only what is needed for mean and variance. The temptation is to accumulate and and use . This is exactly the catastrophic cancellation from the rounding-errors lesson: subtracting two enormous, nearly equal numbers.
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 : with , and its relative rounding error already amounts to about units, much more than the centered sum of squares (). The solution is to accumulate the triple with 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 . For , decompose each deviation: in batch . Squaring and summing over , the cross term vanishes because , leaving . Likewise for . Since and , the sum is .
∎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 .
Dimension: the rate does not depend on d, but σ does
In the Monte Carlo estimator, the dimension of appears nowhere: error is whether is a number or a million-component vector. Compare this with the product rule of lesson 11, whose error with evaluations is for a 1D rule of order . Trapezoidal quadrature () has slope on a log–log scale: steeper than Monte Carlo’s if , equal at and flatter thereafter.
The rate not depending on does not make dimension free: constant does depend on , potentially in any way. Two extreme examples with on , and uniform on :
- Product. For , coordinate independence gives and , and the coefficient of variation is which grows exponentially with whenever is nonconstant (by Jensen, ).
- Mean. For , : variance decreases with and the problem gets easier as dimension grows.
Real integrands lie between the two. This is what Monte Carlo in high dimensions means: the 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 .
The grid benefits from this integrand being separable and analytic, its ideal case. The cell compares all three methods with a budget of about evaluations, using the same 1D rules as lesson 11, and adds an integrand that is neither: the unit-ball indicator, whose integral in is .
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 trapezoidal quadrature with points has error and Monte Carlo : in low dimensions Monte Carlo cannot compete. At the grid fits only 10 points per axis and trapezoidal error is , worse than Monte Carlo (, with estimated standard error ). At trapezoidal quadrature with 3 points per axis is at ; Gauss, which uses its 3 nodes very effectively on an analytic integrand, still wins ( versus ), as seen in lesson 11. At and no grid with 2 points per axis fits the budget (), the 1-point grid is useless (error and ), and Monte Carlo gives and , consistent with its estimated standard errors. Notice the last column too: goes from at to at , the product case’s exponential growth.
The ball shows the other side. Its goes from at to at and at , because relative volume plummets ( and ). With samples in none falls inside: Monte Carlo returns . Dimension has not changed the rate; it has turned the problem into one of rare events.
When Monte Carlo fails
Everything above rests on and 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 for , sampled by inversion as . Its moments are if and infinite if . For mean is finite and variance infinite: the strong law holds and , but the classical CLT does not. (The boundary case still admits a CLT with normalization ; the serious problem is .)
What happens instead is described by the generalized CLT: for , converges to a stable law, so mean error is of order instead of . With , : to gain one digit multiply by 1000, not 100. And estimated standard error is misleading: 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 , , is asymptotically if and only if the law of is in the normal domain of attraction; with it is not, and interval coverage does not tend to 95% however large grows. This section studies heavy tails and Monte Carlo failures, where the mean converges very slowly and the calculated interval misleads.
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 nominal 95% coverage remains , and for , and : it does not improve with , as Giné, Götze and Mason predict. With (finite variance but infinite third moment) it reaches and , and with , . The trajectory shows the mechanism: after samples the mean was with estimated standard error , so its interval, , excluded the true mean 3; a sample of arrives (5.2% of the sum of ) and the mean jumps to , almost nine of those standard errors at once.
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 is to 1, the worse; for there is not even a mean. How to detect it in practice:
- Think before simulating. Does 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 ; 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 with the indicator, with and . Absolute error seems small, but what matters is relative error,
which depends only on the expected number of events . For 10% about 100 events are needed, that is, : simulations for . And with of order 1 the estimator is almost always 0 or several times : the probability of seeing no event is .
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 indicators: it directly draws count from its binomial law, a legitimate and useful trick when only the number of samples falling in matters. With observed relative error is (theoretical ) and 37.0% of experiments see no event (theoretical ). With relative error is , both for with samples and for with : all that counts is .
If you see no events, do not say “”. You can give a bound: if were greater than , the probability of seeing nothing would be , and for that to be requires . This is the rule of three: with 0 events in attempts, at 95%.
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 was a fixed-dimensional vector. In a stochastic simulation is an entire trajectory of a random system, potentially of random length, and is what you measure on it. Monte Carlo is unchanged: simulate independent trajectories and average.
Random walks
The simplest example is a simple random walk: a bet winning 1 with probability and losing 1 with probability , repeated until winning or losing . This is gambler’s ruin and has an exact solution: if is the probability of reaching before 0 from , first-step analysis gives with , , whose solution with is , and starting at 0 means starting at . The vectorized simulation advances all surviving walks together.
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 (), the probability of winning 10 before losing 10 falls to ; Monte Carlo gives . Duration has no such handy formula, but Monte Carlo gives it just as easily: 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:
- the system state (customers waiting, server idle or busy, stock level);
- the clock ;
- the future event list, a priority queue (a binary heap) of (time, event) pairs, ordered by time;
- one routine per event type updating state and scheduling events it causes;
- 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 , exponential services at rate , one server and FIFO order. Customer count is a birth–death process that, if utilization is less than 1, has a stationary geometric distribution, . From this follow mean queue length and, by Little’s law (, Little 1961), mean queue wait,
If there is no stationary regime: the queue grows without bound.
The first discrete-event lab is a generic engine of about twenty lines over heapq and, with it, the queue with servers. Wait intervals are computed with batch means, justified in the next section.
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 events (one arrival and one departure per customer) over about simulated time units. For the simulated mean wait, discarding the first 5000 customers, is , 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 matches . The last line is Little’s law from within: area under queue length divided by total time is exactly times mean wait, and with nominal rate agrees to three digits.
The same engine serves any system by changing only routines. Two examples with known theoretical results: the queue, whose waiting probability is Erlang’s C formula, and base-stock inventory: demand arrives as a Poisson process at rate , each unit sold triggers a replenishment order taking fixed lead time , and demand is backordered if stock is unavailable. Inventory position (stock plus orders in transit minus backorders) is always , so in stationarity available stock is , with demand during a lead time, and demand is served immediately with probability .
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 versus Erlang C’s , and mean wait versus : a difference of half-widths, noise. (Without the interval, versus would look like a 9% simulator error.) In inventory, with units of mean lead-time demand and , mean stock is versus theoretical and 69.9% of demands are served immediately, versus . 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, , 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 as a function of (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 and autocorrelations ,
if autocorrelations are summable. Factor (the integrated autocorrelation time) converts correlated observations into equivalent independent observations; it is the same factor seen in the Markov-chain CLT and MCMC effective sample size. Naive standard error ignores and is times too small.
Batch means estimate without computing autocorrelations: split the series (after warm-up) into contiguous batches of length . If , batch means are nearly independent and nearly normal, each with variance , and the interval
has correct coverage. Use few batches (between 10 and 30) so each is long; with , .
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 and the queue initially empty, customer 10’s mean wait is , customer 100’s , and customer 300’s , against stationary value 9; around customer 1000 the curve is indistinguishable from 9 within the noise of 2000 replicas (). Averaging the first 1000 customers gives : bias , 9%, which no number of replicas fixes because it is not noise. The closer is to 1, the longer the transient.
The second part measures correlation’s damage with . Waits have autocorrelation at lag 1, at lag 10 and still at lag 50. Mean naive standard error is ; batch-means error ; and actual error, measured as dispersion of 200 independent replica means, . The naive one is wrong by a factor of 9.5, that is, : 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 or 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 to 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 units of roundoff instead of .
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 . 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.
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 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, : combined mean error is , while the standard error you would report believing you had samples would be ; the actual error is that of samples, . With spawn, the four estimates differ and the combined one has error .
In libraries
| Tool | What it does | When |
|---|---|---|
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) | independent streams derived from a root seed | parallel processes, threads or GPUs |
np.random.Generator(np.random.Philox(key=k)) | counter-based generator; key identifies stream | massive parallelism without coordination, reproducibility by key |
rng.binomial(N, p), rng.poisson(lam) | simulate a count without simulating each trial | rare events, Monte Carlo histograms |
scipy.stats.<dist>.rvs(size, random_state=rng) | samples from any SciPy distribution | distributions without a NumPy sampler |
scipy.stats.qmc, scipy.integrate.qmc_quad | low-discrepancy sequences and randomized quasi-Monte Carlo quadrature with error estimation | smooth integrals in moderate dimension (simulation module) |
heapq | binary heap on a list | custom simulator event list |
| SimPy | process-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 with the same ; 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 for regular integrands, recovering estimable error with the randomized version. When you cannot sample 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
rng = np.random.default_rng(42), generates samples and returns its mean. You combine all 8 means and standard error as if you had samples. What have you obtained?Step 1 of 5. Why is ?
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 with the sample standard deviation ( in the denominator), and the 95% interval with . 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 ) 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)Summary
- Estimator is unbiased, has variance and converges almost surely even if . Different representations of the same quantity have different : hit-or-miss always loses to mean value.
- Interval is asymptotic (CLT and Slutsky); with skewed integrands or small-probability indicators, coverage at moderate can be far below 95%. Error requires samples.
- In streaming, summarize each batch with and merge with Chan–Golub–LeVeque; formula is destroyed by cancellation.
- Rate does not depend on and beats the grid () once ; but depends on , and can grow exponentially or turn the problem into rare events.
- With infinite variance (Pareto with ) the mean converges slowly in jumps and the interval misleads regardless of . For rare events relative error is : samples are needed for 10%, and zero events only give bound .
- 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 times too small.
- At scale: vectorized batches, pairwise sums and an independent stream per worker using
SeedSequence.spawnor 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.