Numerical integration: from Newton-Cotes to Gauss
Review classical quadrature and advance to Richardson extrapolation, Gaussian quadrature as an eigenvalue problem, adaptive integration and exponential trapezoid convergence for periodic functions, ending with the curse of dimensionality.
After this lesson you can
- Derive and empirically verify composite trapezoid and Simpson errors.
- Apply Richardson extrapolation and Romberg integration.
- Compute Gauss–Legendre and Gauss–Hermite nodes and weights with Golub–Welsch.
- Implement adaptive quadrature with local error estimation.
- Explain exponential periodic trapezoid convergence and the curse of dimensionality.
Before you start
Motivation: integrals without antiderivatives
The fundamental theorem of calculus turns an integral into a difference of antiderivatives, but almost no integral arising in a real model has an elementary antiderivative:
- Expectations under a normal distribution. In a Bayesian model with logistic or probit likelihood, prediction and evidence require computing with , namely , for like or . This is needed for each data point and optimizer iteration.
- Expected payoff. An option price is the discounted expectation of its payoff under the pricing measure. A European call has the Black–Scholes formula; for almost any other payoff or model, numerical integration is needed.
- Energy of a system. Energy of a finite-element structure, action of a trajectory or mass of a charge distribution are integrals of products of shape functions evaluated element by element millions of times.
A quadrature rule replaces an integral with a weighted sum of integrand values,
with nodes and weights independent of , and a weight function (almost always ). Cost is measured in evaluations of , because evaluating is expensive in real problems. The lesson’s question is how much accuracy each evaluation buys and what it depends on.
This lesson quickly reviews familiar rules (trapezoid and Simpson) to reach professional depth: why errors have their form (Euler–Maclaurin), how to cancel them (Richardson and Romberg), where to place nodes for double the degree (Gauss, computed as an eigenvalue problem), why the humble trapezoid is unbeatable on periodic functions, how scipy.integrate.quad works internally, and why none of these rules survives high dimension.
Interpolatory rules: Newton–Cotes
The most direct idea is to integrate a polynomial resembling . If is the interpolating polynomial of at distinct nodes, with Lagrange basis , then
Trapezoid integrates the piecewise linear interpolant and Simpson the piecewise quadratic over pairs of subintervals. Their errors follow from the interpolation error formula.
Proof
(1) On subinterval , linear interpolation error is . Factor does not change sign on the subinterval, so the mean value theorem for integrals with constant-sign weight gives with
Summing the subintervals, , where is the mean of . Since is continuous and the mean lies between minimum and maximum, the intermediate value theorem gives with , and .
(2) The argument is the same with a subtlety: Simpson’s nodal polynomial on , , changes sign and integrates to zero. Thus Simpson, interpolating degree 2, integrates cubics exactly (degree of exactness 3, one above the guarantee). Let be the cubic interpolating at the three nodes and also at the center. Simpson is exact on and matches at nodes, so Simpson error on the pair is . Hermite error is , whose polynomial factor has constant sign, and the mean value theorem gives . Sum the pairs and apply intermediate value again to obtain the result, since .
∎Thus trapezoid is order 2 and Simpson order 4: doubling points divides error by 4 and 16. On a log-log plot of error against evaluations they are straight lines of slope and . The ladder below shows them alongside two upcoming rules (Gauss–Legendre and Clenshaw–Curtis), on five integrands of different difficulty.
Three things visible in the figure, explained one by one. First, theoretical order appears only if has the derivatives required by the theorem: with a corner, Simpson and Gauss fall to trapezoid’s order 2, oscillating according to where the corner falls between nodes. Second, on analytic functions Gaussian rules are curves falling faster than any power rather than straight lines. Third, on a periodic integrand trapezoid, the simplest rule, beats all others.
Euler–Maclaurin: the exact error form
The previous theorem gives order; the Euler–Maclaurin formula gives the full trapezoid error expansion and, with it, everything that follows.
Two readings. First: error depends only on derivatives at endpoints, and contains only even powers of . The latter makes the next section’s Richardson extrapolation work. Second: if all odd derivatives match at and , all terms vanish and error is smaller than any power of . This is exactly what happens for a periodic function integrated over one complete period, explaining the figure’s surprise.
The cell checks order with the standard tool, empirical order verification: the ratio between consecutive errors when doubling should approach .
import numpy as np
def trapecio(f, a, b, n):
"""Trapecio compuesto con n subintervalos (n + 1 evaluaciones)."""
x = np.linspace(a, b, n + 1)
y = f(x)
h = (b - a) / n
return h * (y.sum() - 0.5 * (y[0] + y[-1]))
def simpson(f, a, b, n):
"""Simpson compuesto; n debe ser par."""
assert n % 2 == 0, "Simpson necesita un número par de subintervalos"
x = np.linspace(a, b, n + 1)
y = f(x)
h = (b - a) / n
return h / 3 * (y[0] + y[-1] + 4 * y[1:-1:2].sum() + 2 * y[2:-1:2].sum())
I = np.e - 1
print(" n error trapecio cociente h²/12·(f'(1)-f'(0)) error Simpson cociente")
eT_prev = eS_prev = None
for n in [2, 4, 8, 16, 32, 64, 128]:
eT = trapecio(np.exp, 0, 1, n) - I
eS = simpson(np.exp, 0, 1, n) - I
em = (1 / n) ** 2 / 12 * (np.e - 1) # término principal de Euler-Maclaurin
rT = f"{eT_prev / eT:8.3f}" if eT_prev else " " * 8
rS = f"{eS_prev / eS:8.3f}" if eS_prev else " " * 8
print(f"{n:4d} {eT:13.6e} {rT} {em:13.6e} {eS:13.6e} {rS}")
eT_prev, eS_prev = eT, eS
# con una esquina el orden se pierde: f(x) = |x - x0|, x0 irracional
x0 = np.sqrt(5) - 2
g = lambda x: np.abs(x - x0)
Ig = (x0**2 + (1 - x0)**2) / 2
print(f"\nesquina en x0 = {x0:.4f}:")
for n in [16, 32, 64, 128, 256]:
print(f" n = {n:3d} trapecio {abs(trapecio(g, 0, 1, n) - Ig):.2e} Simpson {abs(simpson(g, 0, 1, n) - Ig):.2e}")Trapezoid ratios approach and Simpson ratios , and Euler–Maclaurin’s leading term predicts trapezoid error to five digits already at ( measured versus ). With the corner, by contrast, errors decrease irregularly and Simpson is not systematically better than trapezoid (at it is worse: versus ). From to both gain just over two digits, corresponding to order 2 (multiplying by 16 divides error by ), not order 4 (which would divide by ).
Why not increase degree
If Simpson (3 points) beats trapezoid (2), why not use Newton–Cotes with 11 equally spaced points? Two reasons. First is the Runge phenomenon: a high-degree interpolant at equally spaced nodes can diverge even if is analytic, and its integral with it. Second is worse in practice: negative weights appear with 9 points and do not disappear with 11 or more (the 10-point rule is the last with all positive). With 11 points, , so rounding or measurement error of size in can cause error instead of , and the factor grows exponentially with point count. Practical lesson: compose low-degree rules (increase , not degree) or choose better nodes, as Gauss does.
Richardson extrapolation and Romberg
Euler–Maclaurin says with coefficients independent of . With steps and :
Multiply the second by 4, subtract the first and divide by 3: the term vanishes,
This is Richardson extrapolation: knowing the error form, combine two approximations to cancel its leading term. Something beautiful happens here: is term by term Simpson’s rule with step . Simpson is extrapolated trapezoid. The same trick gives a free error estimator: , because the difference of two approximations is three times the better one’s error.
Nothing prevents repetition. If , each new column eliminates the next even power:
This is the Romberg method (Werner Romberg, 1955). Its practical advantage is reuse: trapezoid with subintervals only needs evaluating at the new midpoints, . Row costs evaluations total.
import numpy as np
def romberg_tabla(f, a, b, niveles):
"""Tabla de Romberg R[k, j]: la fila k usa 2^k subintervalos; la columna j elimina h², ..., h^(2j)."""
R = np.zeros((niveles, niveles))
h = b - a
R[0, 0] = h / 2 * (f(a) + f(b))
evals = 2
for k in range(1, niveles):
h /= 2
nuevos = a + h * np.arange(1, 2**k, 2) # solo los puntos medios nuevos
R[k, 0] = R[k - 1, 0] / 2 + h * f(nuevos).sum()
evals += len(nuevos)
for j in range(1, k + 1):
R[k, j] = R[k, j - 1] + (R[k, j - 1] - R[k - 1, j - 1]) / (4**j - 1)
return R, evals
I = np.e - 1
R, ev = romberg_tabla(np.exp, 0.0, 1.0, 6)
print(f"errores de la tabla de Romberg para ∫₀¹ eˣ dx ({ev} evaluaciones):")
with np.printoptions(linewidth=110, formatter={"float": lambda v: f"{v:9.1e}"}):
print(np.where(np.tril(np.ones_like(R)) > 0, np.abs(R - I), np.nan))
# sin desarrollo en potencias pares de h, Richardson no sirve
Rs, ev = romberg_tabla(np.sqrt, 0.0, 1.0, 10)
print(f"\n√x en [0, 1] con {ev} evaluaciones:")
print(f" trapecio (columna 0): {abs(Rs[-1, 0] - 2/3):.2e} diagonal de Romberg: {abs(Rs[-1, -1] - 2/3):.2e}")
print(" cocientes de errores sucesivos del trapecio:", np.round(np.abs(Rs[:-1, 0] - 2/3) / np.abs(Rs[1:, 0] - 2/3), 3)[-4:])With , column 0 falls by factor 4 per row and each new column accelerates decline: at 33 evaluations the diagonal reaches machine precision, where trapezoid would need on the order of points. With the result is very different: derivative explodes at 0, the Euler–Maclaurin expansion does not exist (error contains , as ratios reveal) and extrapolation, canceling absent powers, improves only by factor 3 with 513 evaluations. Richardson is only as good as the assumed error form.
Gaussian quadrature
Newton–Cotes rules fix nodes and choose weights: free parameters, degree (sometimes by symmetry). If nodes are also free there are parameters, and one might expect enough to integrate exactly the monomials . Before theory, find them yourself.
What you just saw is the central theorem. The bar measures whether , and the rule gains one degree for each (starting at ) to which is orthogonal. With nodes, has degree and can be orthogonal to at most : then is, up to a constant, itself, and nodes are its zeros.
For the definition to make sense the zeros of must be real, simple and in . A classic argument: if changed sign at only points of , product would have constant sign and its integral with weight would be nonzero, contradicting orthogonality of to every polynomial of degree .
Proof
(1) You will prove it step by step in the final guided exercise.
(2) has degree , so the rule is exact on it: , because . The integral is positive because is not identically zero. The sum follows by applying exactness to .
(3) Interpolate and at nodes with the degree- Hermite polynomial ; the rule is exact on it and , so . Hermite error is , with ; polynomial factor has constant sign, and the mean value theorem with weight concludes.
(4) For any of degree , because the rule is exact on . And , , because weights are positive. Take as the best approximant.
∎Point 4 is the deep reason Gauss is so good for analytic functions: is the best degree- polynomial approximation error, which in the prior lesson you saw decrease geometrically for analytic functions, like the Chebyshev series. If is analytic in the Bernstein ellipse with parameter , Gauss error is . The proof uses positive weights essentially: high-degree Newton–Cotes fails precisely there.
Golub–Welsch: nodes and weights as an eigenvalue problem
How are zeros of and weights computed? Neither root formulas nor a Vandermonde system (ill-conditioned). Monic orthogonal polynomials satisfy a three-term recurrence,
with . For Legendre, and ; for Hermite with weight (probabilists’ version), and .
Proof
Let be orthonormal polynomials. The recurrence becomes , because . With , all equations together are
At a zero of the last term vanishes: , and because . Thus the distinct zeros are the eigenvalues.
For weights, the rule is exact on (, degree ): . With and , this is , so is invertible and . The diagonal gives . Since , its first component squared is .
∎The calculation is entirely a symmetric matrix eigenvalue problem, tridiagonal, the most stable case. Golub and Welsch solved it in with tridiagonal QR, calculating only each eigenvector’s first component; eigh on the dense matrix as in the cell costs , irrelevant for .
import numpy as np
def golub_welsch(alfa, beta, mu0):
"""Regla gaussiana de n puntos a partir de la recurrencia p_{k+1} = (x - alfa_k) p_k - beta_k p_{k-1}.
alfa: n coeficientes; beta: los n - 1 coeficientes beta_1 ... beta_{n-1}; mu0 = ∫ w."""
J = np.diag(alfa) + np.diag(np.sqrt(beta), 1) + np.diag(np.sqrt(beta), -1)
x, V = np.linalg.eigh(J) # simétrica tridiagonal: autovalores reales y ordenados
w = mu0 * V[0, :] ** 2 # primera componente de cada autovector unitario
return x, w
def gauss_legendre(n):
k = np.arange(1, n)
return golub_welsch(np.zeros(n), k**2 / (4.0 * k**2 - 1), 2.0)
def gauss_hermite_prob(n):
"""Peso exp(-x²/2) en R (Hermite de los probabilistas, He_k): beta_k = k, mu0 = √(2π)."""
return golub_welsch(np.zeros(n), np.arange(1, n, dtype=float), np.sqrt(2 * np.pi))
for n in [5, 20, 100]:
x, w = gauss_legendre(n)
xr, wr = np.polynomial.legendre.leggauss(n)
print(f"n = {n:3d}: |x - leggauss| = {np.max(np.abs(x - xr)):.1e} "
f"|w - leggauss| = {np.max(np.abs(w - wr)):.1e} peso mínimo = {w.min():.2e}")
x, w = gauss_hermite_prob(10)
xr, wr = np.polynomial.hermite_e.hermegauss(10)
print(f"Hermite, n = 10: |x - hermegauss| = {np.max(np.abs(x - xr)):.1e} |w - hermegauss| = {np.max(np.abs(w - wr)):.1e}")
# grado de exactitud de la regla de 5 puntos: exacta hasta x^9, no con x^10 ni con ω²
x, w = gauss_legendre(5)
for k in [8, 9, 10]:
exacto = 2 / (k + 1) if k % 2 == 0 else 0.0
print(f"x^{k}: error {abs(w @ x**k - exacto):.1e}")
omega2 = lambda t: np.prod([(t - xi) ** 2 for xi in x], axis=0)
xx, ww = gauss_legendre(10) # 10 puntos: exacta hasta grado 19 ≥ 10
print(f"∫ ω² = {ww @ omega2(xx):.6e} la regla de 5 puntos da {w @ omega2(x):.1e}")Differences from leggauss and hermegauss are order , all weights positive (minimum with is ), the 5-point rule integrates exactly and fails on , and gives exactly 0 for versus . That matches the closed formula for Legendre, , which at gives , and is the theorem point 3 error-term constant.
Gauss–Hermite for Gaussian expectations
A normal distribution is exactly the Hermite weight. If , the substitution turns the density into :
with Gauss–Hermite nodes and weights for weight (from np.polynomial.hermite.hermgauss). This is Gauss–Hermite for Gaussian expectations: with evaluations it is exact for polynomial of degree , and converges quickly for smooth . With the probabilists’ version (hermegauss, weight ) the substitution is and factor . Mixing conventions is the commonest mistake: missing or extra changes variance.
Three real use cases with exact references:
import numpy as np
from scipy.integrate import quad
def esperanza_gh(f, mu, sigma, n):
"""E[f(X)], X ~ N(mu, sigma²), con Gauss-Hermite de n puntos (peso e^{-t²}, x = mu + √2 sigma t)."""
t, w = np.polynomial.hermite.hermgauss(n)
return w @ f(mu + np.sqrt(2) * sigma * t) / np.sqrt(np.pi)
def densidad(x, mu, sigma):
return np.exp(-0.5 * ((x - mu) / sigma) ** 2) / (np.sqrt(2 * np.pi) * sigma)
softplus = lambda x: np.logaddexp(0.0, x) # log(1 + e^x) sin desbordamiento
mu, sigma = 0.5, 2.0
ref = quad(lambda x: softplus(x) * densidad(x, mu, sigma), -np.inf, np.inf, epsabs=1e-14, epsrel=1e-13, limit=200)[0]
print(f"E[softplus(X)], X ~ N({mu}, {sigma}²) = {ref:.12f} (referencia con quad)")
for n in [3, 5, 10, 20, 40]:
print(f" Gauss-Hermite n = {n:2d}: error {abs(esperanza_gh(softplus, mu, sigma, n) - ref):.1e}")
t, w = np.polynomial.hermite.hermgauss(20)
mal = w @ softplus(mu + sigma * t) / np.sqrt(np.pi) # olvidando el √2
print(f" sin el √2 (n = 20): {mal:.6f}, error {abs(mal - ref):.2e}")
rng = np.random.default_rng(0)
for N in [10**3, 10**5]:
est = np.array([softplus(mu + sigma * rng.standard_normal(N)).mean() for _ in range(20)])
print(f" Monte Carlo, N = {N:6d}: error cuadrático medio en 20 repeticiones {np.sqrt(np.mean((est - ref)**2)):.1e}")At 10 nodes error is already , and at 20, ; Monte Carlo with samples remains at , because its error decreases as (see the Monte Carlo lesson). Softplus is not polynomial and has complex singularities (logarithm branch points where ) at , so convergence is quick but not instant. Forgetting causes error : an expectation under variance instead of .
import numpy as np
from scipy.integrate import quad
from scipy.special import ndtr as Phi # función de distribución normal estándar
# call europea: E[e^{-rT} (S_T - K)^+] con S_T = S0 exp((r - vol²/2) T + vol √T Z)
S0, K, r, vol, T = 100.0, 110.0, 0.03, 0.25, 1.0
d1 = (np.log(S0 / K) + (r + vol**2 / 2) * T) / (vol * np.sqrt(T))
C = S0 * Phi(d1) - K * np.exp(-r * T) * Phi(d1 - vol * np.sqrt(T)) # Black-Scholes
pago = lambda z: np.exp(-r * T) * np.maximum(S0 * np.exp((r - vol**2 / 2) * T + vol * np.sqrt(T) * z) - K, 0.0)
print(f"call europea, Black-Scholes = {C:.10f}")
for n in [10, 20, 40, 80, 160]:
print(f" Gauss-Hermite n = {n:3d}: error {abs(esperanza_gh(pago, 0.0, 1.0, n) - C):.1e}")
z_star = (np.log(K / S0) - (r - vol**2 / 2) * T) / (vol * np.sqrt(T)) # donde el pago deja de ser 0
val, err, info = quad(lambda z: pago(z) * densidad(z, 0, 1), z_star, np.inf, full_output=1)[:3]
print(f" quad partiendo en z* = {z_star:.4f}: error {abs(val - C):.1e} con {info['neval']} evaluaciones")
# probit con intercepto aleatorio: P(y = 1 | x) = E_b[Φ(x β + b)], b ~ N(0, τ²), que vale Φ(x β / √(1 + τ²))
rng = np.random.default_rng(1)
n_obs, beta, tau = 200, 1.3, 0.8
x = rng.normal(size=n_obs)
y = (rng.random(n_obs) < Phi(x * beta / np.sqrt(1 + tau**2))).astype(float)
loglik = lambda p: np.sum(y * np.log(p) + (1 - y) * np.log1p(-p))
exacta = loglik(Phi(x * beta / np.sqrt(1 + tau**2)))
print(f"\nprobit con efecto aleatorio, log-verosimilitud exacta = {exacta:.10f}")
for n in [2, 4, 8, 16]:
t, w = np.polynomial.hermite.hermgauss(n)
p = (w * Phi(x[:, None] * beta + np.sqrt(2) * tau * t[None, :])).sum(axis=1) / np.sqrt(np.pi)
print(f" Gauss-Hermite n = {n:2d} ({n * n_obs:5d} evaluaciones de Φ): error {abs(loglik(p) - exacta):.1e}")
for M in [100, 10000]:
b = tau * rng.standard_normal(M)
p = Phi(x[:, None] * beta + b[None, :]).mean(axis=1)
print(f" Monte Carlo M = {M:5d} ({M * n_obs:7d} evaluaciones de Φ): error {abs(loglik(p) - exacta):.1e}")The other two examples teach the opposite. In probit, is entire and convergence spectacular: 16 nodes per datum give log likelihood error , while Monte Carlo with samples per datum (two million evaluations) remains at . Thus adaptive Gauss–Hermite (centered and scaled at integrand mode, like the Laplace approximation) is standard for mixed models with low-dimensional random effects. In the call, by contrast, payoff has a corner at , and Gauss–Hermite crawls: multiplying nodes by 16 (10 to 160) only takes error from to , and along the way it is nonmonotonic ( at 40 nodes, at 80), because it depends on where the corner lies between nodes. As in the ladder, with a corner no high-order rule keeps its order. The remedy is usual: split the interval at the corner, and quad from gives price error in 135 evaluations.
Clenshaw–Curtis versus Gauss
Another natural node choice is to interpolate at Chebyshev points (extrema of ), , , and integrate the interpolant exactly. This is the Clenshaw–Curtis rule (1960). With points it has degree , half Gauss with the same points. But it has three practical advantages: weights are computed by FFT in because interpolation there uses a cosine transform (see Chebyshev nodes and FFT); nodes are nested (those for are a subset of those for , so doubling reuses all evaluations as in Romberg); and weights are all positive (the cell checks through ), so theorem point 4 for Gauss also holds with instead of .
That bound suggests Gauss should need half as many points. Trefethen (2008) showed that in practice this factor-2 advantage rarely appears: Clenshaw–Curtis gives almost Gauss accuracy for most integrands, and Gauss only wins clearly for functions analytic in a large region around , like . His explanation interprets each rule as a rational approximation of : Gauss is a Padé approximant at and Clenshaw–Curtis has half the order there, but is equally accurate near , what matters except for functions with very distant singularities.
import numpy as np
def clenshaw_curtis(n):
"""n + 1 nodos x_k = cos(kπ/n) y sus pesos (fórmula explícita de Trefethen, clencurt.m)."""
theta = np.pi * np.arange(n + 1) / n
x = np.cos(theta)
w = np.zeros(n + 1)
v = np.ones(n - 1)
ii = slice(1, n)
if n % 2 == 0:
w[0] = w[n] = 1.0 / (n**2 - 1)
for k in range(1, n // 2):
v -= 2 * np.cos(2 * k * theta[ii]) / (4 * k**2 - 1)
v -= np.cos(n * theta[ii]) / (n**2 - 1)
else:
w[0] = w[n] = 1.0 / n**2
for k in range(1, (n - 1) // 2 + 1):
v -= 2 * np.cos(2 * k * theta[ii]) / (4 * k**2 - 1)
w[ii] = 2 * v / n
return x, w
print("peso mínimo de Clenshaw-Curtis para n = 2 ... 256:", f"{min(clenshaw_curtis(n)[1].min() for n in range(2, 257)):.2e}")
x0 = np.sqrt(5) - 2
banco = {
"e^x": (np.exp, np.e - 1 / np.e),
"1/(1+25x²)": (lambda t: 1 / (1 + 25 * t * t), 0.4 * np.arctan(5)),
"|x - x0|": (lambda t: np.abs(t - x0), 1 + x0**2),
"√(1+x)": (lambda t: np.sqrt(1 + t), 4 * np.sqrt(2) / 3),
}
Ns = [9, 17, 33, 65]
print("\nerror relativo con N evaluaciones en [-1, 1] (G = Gauss-Legendre, CC = Clenshaw-Curtis)")
print(" " * 13 + "".join(f"{'N = ' + str(N):>21s}" for N in Ns))
for nombre, (f, Iex) in banco.items():
fila = ""
for N in Ns:
xg, wg = gauss_legendre(N)
xc, wc = clenshaw_curtis(N - 1)
fila += f" G {abs(wg @ f(xg) - Iex) / Iex:7.1e} CC {abs(wc @ f(xc) - Iex) / Iex:7.1e}"
print(f"{nombre:13s}{fila}")The table confirms Trefethen with our numbers. With entire , Gauss is already at with 9 points and Clenshaw–Curtis at : the factor 2 really appears here. With , whose poles at are close to the interval, both rules converge at the same geometric speed and Clenshaw–Curtis is only factor 2 to 5 behind in error, not point count. With the corner and square root, both converge algebraically with errors of the same order (on the corner, oscillations sometimes favor one, sometimes the other). That is why spectral libraries like Chebfun integrate with Clenshaw–Curtis, and why choosing between them is rarely critical: the critical thing is ‘s smoothness.
The trapezoidal rule for periodic functions
Return to the ladder with the periodic integrand: trapezoid beats Gauss. Euler–Maclaurin already foreshadowed it (all terms vanish), but the clean explanation is Fourier, connecting to sampling and aliasing from the previous lesson.
If is -periodic, trapezoid with subintervals on is simply the mean of equally spaced samples, because and the two half weights add:
Proof
The rule applied to is , a geometric sum equal to if divides and otherwise: DFT orthogonality. Absolute convergence permits interchanging the rule and Fourier sums, and since , the first formula follows.
For the bound, . If , shift the integration segment to with : by periodicity vertical sides cancel, by Cauchy’s theorem the integral is unchanged, and there, so ; for shift upward. Letting , , and then .
∎This is the trapezoidal rule for periodic functions: trapezoid with points integrates exactly every trigonometric polynomial of degree , and its only error is Fourier coefficients sampling confuses with the constant (frequencies , aliasing). If is analytic in a strip of width , error falls as , faster for a wider strip.
In the figure’s example poles are at , so each point adds correct digits: with and only with . For the ladder integrand, , poles satisfy , at distance from the axis, and with . The cell verifies it alongside , which is entire and converges faster than any exponential: its error is , with the modified Bessel function.
import numpy as np
from scipy.special import iv # Bessel modificada I_k
def trapecio_periodico(f, N):
t = 2 * np.pi * np.arange(N) / N
return 2 * np.pi / N * f(t).sum()
f = lambda t: 1 / (2 + np.cos(t))
Iex = 2 * np.pi / np.sqrt(3)
rho = 2 - np.sqrt(3)
print("1/(2 + cos θ) en [0, 2π]")
print(" N trapecio predicción (4π/√3)·ρ^N/(1-ρ^N) Gauss-Legendre")
for N in [4, 8, 12, 16, 20, 24]:
eT = abs(trapecio_periodico(f, N) - Iex)
xg, wg = gauss_legendre(N)
eG = abs(np.pi * (wg @ f(np.pi * (xg + 1))) - Iex)
print(f"{N:3d} {eT:9.2e} {4 * np.pi / np.sqrt(3) * rho**N / (1 - rho**N):9.2e} {eG:9.2e}")
g = lambda t: np.exp(np.cos(t))
Ig = 2 * np.pi * iv(0, 1)
print("\ne^{cos θ} en [0, 2π]: integral 2π I_0(1) =", Ig)
for N in [4, 8, 10, 12, 16]:
xg, wg = gauss_legendre(N)
print(f" N = {N:2d}: error {abs(trapecio_periodico(g, N) - Ig):.2e}"
f" predicción 4π I_N(1) = {4 * np.pi * iv(N, 1):.2e}"
f" Gauss-Legendre {abs(np.pi * (wg @ g(np.pi * (xg + 1))) - Ig):.2e}")With prediction matches measured error to three printed digits and trapezoid reaches with 24 points; Gauss–Legendre with 24 remains at , five orders worse. With , 16 points suffice to reach rounding (), while Gauss–Legendre at those 16 points remains at . In the last row prediction () is already below summation rounding, what is measured. Trapezoid wins because equally spaced nodes are optimal for periodic functions, while Gauss and Clenshaw–Curtis cluster nodes at interval endpoints which, for a periodic function, are not special. Trefethen and Weideman (2014) extend the idea to the real line (rapidly decaying integrands) and substitutions converting an interval into a periodic or doubly exponential function, like Takahasi and Mori’s (1974) tanh–sinh rule.
Adaptive quadrature
So far every rule distributes nodes in advance. But the motivating integrand may be flat almost everywhere with a narrow peak or point singularity. A uniform rule wastes almost all evaluations where unnecessary.
Adaptive quadrature estimates error in each panel by comparing two rules and subdivides only where the estimate is large. For Simpson, Richardson provides the estimate: if is Simpson on panel and the sum of Simpson on its halves, then if is nearly constant on the panel,
because error is that of . Two strategies follow. Local (recursive) accepts a panel if its estimate falls below a tolerance distributed among panels. Global, used by QUADPACK and here, keeps all panels in a priority queue and splits the largest estimated error at each step until the sum of estimates falls below tolerance. Global is more robust: a difficult panel does not exhaust its tolerance share before others are examined.
import heapq
import numpy as np
from scipy.integrate import quad
def simpson_adaptativo(f, a, b, tol=1e-8, max_evals=20000):
"""Divide siempre el panel con mayor error estimado hasta que la suma de estimaciones baja de tol.
Devuelve (integral, error estimado, evaluaciones, paneles)."""
n_evals = 0
def F(x):
nonlocal n_evals
n_evals += 1
return f(x)
def panel(a, b, fa, fm, fb):
m = (a + b) / 2
flm, frm = F((a + m) / 2), F((m + b) / 2)
S1 = (b - a) / 6 * (fa + 4 * fm + fb) # Simpson con h
S2 = (m - a) / 6 * (fa + 4 * flm + fm) + (b - m) / 6 * (fm + 4 * frm + fb) # con h/2
err = abs(S2 - S1) / 15
return (-err, a, b, fa, flm, fm, frm, fb, S2 + (S2 - S1) / 15) # heapq es de mínimos: -err
fa, fm, fb = F(a), F((a + b) / 2), F(b)
cola = [panel(a, b, fa, fm, fb)]
while -sum(p[0] for p in cola) > tol and n_evals < max_evals:
_, a_, b_, fa_, flm, fm_, frm, fb_, _ = heapq.heappop(cola) # el de mayor error
m = (a_ + b_) / 2
heapq.heappush(cola, panel(a_, m, fa_, flm, fm_)) # reutiliza las 5 evaluaciones
heapq.heappush(cola, panel(m, b_, fm_, frm, fb_))
return sum(p[8] for p in cola), -sum(p[0] for p in cola), n_evals, len(cola)
s = 0.3 * np.sqrt(2)
dificil = lambda x: 1 / np.sqrt(np.abs(x - s)) + 6 * np.exp(-((x - 0.8) / 0.01) ** 2)
I_dificil = 2 * (np.sqrt(s) + np.sqrt(1 - s)) + 6 * 0.01 * np.sqrt(np.pi)
print("1/√|x - s| más un pico de anchura 0.01 en [0, 1]:")
for tol in [1e-2, 1e-4, 1e-6]:
Q, est, ev, npan = simpson_adaptativo(dificil, 0.0, 1.0, tol)
print(f" tol {tol:.0e}: error real {abs(Q - I_dificil):.1e} estimado {est:.1e} {ev:4d} evaluaciones, {npan} paneles")
for n in [2**10, 2**14, 2**18]:
print(f" Simpson uniforme con {n + 1:6d} evaluaciones: error {abs(simpson(dificil, 0, 1, n) - I_dificil):.1e}")
Q, est, info = quad(dificil, 0, 1, full_output=1)[:3]
print(f" quad sin pistas: error real {abs(Q - I_dificil):.1e}, {info['neval']} evaluaciones")
Q, est, info = quad(dificil, 0, 1, points=[s, 0.8], full_output=1)[:3]
print(f" quad con points=[s, 0.8]: error real {abs(Q - I_dificil):.1e}, {info['neval']} evaluaciones")Numbers tell three stories. Savings: at tolerance adaptive achieves actual error with 201 evaluations; uniform Simpson with 262 145 evaluations remains at , even worse than with 16 385 (). Near the singularity Simpson error decreases on average as and erratically, depending how close the nearest node falls to : no reasonable number of uniform points fixes it. Silent failure: at tolerance the algorithm stops after 17 evaluations with estimated error , but actual error is . None of those 17 evaluations hit the peak, and to an algorithm seeing only values an unsampled peak does not exist. Optimistic estimator: at actual error () exceeds tolerance, because near the singularity Simpson error does not fall as and factor is no longer valid. quad without hints suffers the same: exhausts 50 subintervals (2079 evaluations) and remains at error ; with points=[s, 0.8] it knows where to split and reaches with 903.
Gauss–Kronrod and QUADPACK
scipy.integrate.quad wraps QUADPACK (Piessens, de Doncker-Kapenga, Überhuber and Kahaner, 1983). For a finite interval it uses QAGS: global adaptive subdivision with a 21-point Gauss–Kronrod rule on each panel, plus Wynn’s epsilon-algorithm extrapolation, accelerating convergence of the approximation sequence when endpoints have singularities.
Kronrod’s idea (mid-1960s) solves a Gauss problem: nodes are not nested, so comparing with to estimate error costs evaluations without reuse. Kronrod adds new nodes to the Gauss nodes, chosen so the -point rule has the highest possible degree (at least ). Pair , costs 21 evaluations and gives a highly accurate rule () plus an error estimate (). QUADPACK does not use that difference directly: it corrects it with empirical formula , with , absolute deviation of from its panel mean (computed using the Kronrod rule itself), because measures error and greatly overestimates error.
Singularities and infinite intervals
Two situations where helping the algorithm with a change of variables is useful:
- Integrable endpoint singularity, like with smooth . With , and the integral becomes , without singularity. Alternatively tell
quadthe weight is withweight='alg', and it uses a rule exactly integrating that weight. - Infinite interval, as in an expectation. Eyeball truncation, , adds error absent from all estimates. Better transform: QUADPACK (QAGI routine) uses , mapping to , and
quaddoes it automatically if passednp.inf. For a normal distribution Gauss–Hermite is the natural transformation.
import numpy as np, warnings
from scipy.integrate import quad, IntegrationWarning
from scipy.special import fresnel
exacta = np.sqrt(2 * np.pi) * fresnel(np.sqrt(2 / np.pi))[1] # ∫₀¹ cos(x)/√x dx
for nombre, args, kw in [
("cos(x)/√x directo ", (lambda x: np.cos(x) / np.sqrt(x), 0, 1), {}),
("cambio x = t², 2cos(t²) ", (lambda t: 2 * np.cos(t * t), 0, 1), {}),
("weight='alg', wvar=(-½, 0)", (np.cos, 0, 1), {"weight": "alg", "wvar": (-0.5, 0)}),
]:
val, err, info = quad(*args, full_output=1, **kw)[:3]
print(f"{nombre}: error real {abs(val - exacta):.1e}, estimado {err:.1e}, {info['neval']:3d} evaluaciones")
val, err, info = quad(lambda x: 1 / (1 + x * x), 0, np.inf, full_output=1)[:3]
print(f"\n∫₀^∞ dx/(1+x²) con np.inf: error real {abs(val - np.pi / 2):.1e}, {info['neval']} evaluaciones")
val, err = quad(lambda x: 1 / (1 + x * x), 0, 100)
print(f"truncada a [0, 100]: error real {abs(val - np.pi / 2):.1e}, estimado {err:.1e}")
val, err = quad(lambda x: np.exp(-(x - 300) ** 2), 0, np.inf)
print(f"∫₀^∞ e^(-(x-300)²) (vale √π = 1.77): quad devuelve {val} ± {err}")
# los avisos importan: una oscilación rápida
exacta_osc = (1 - np.exp(-10) * (np.cos(2000) - 200 * np.sin(2000))) / (1 + 200**2) # ∫₀¹⁰ cos(200x) e^(-x) dx
with warnings.catch_warnings(record=True) as avisos:
warnings.simplefilter("always", IntegrationWarning)
val, err = quad(lambda x: np.cos(200 * x) * np.exp(-x), 0, 10)
print(f"\noscilante por defecto: {val:.3e} ± {err:.1e} (exacta {exacta_osc:.3e})")
print(" aviso:", str(avisos[0].message).splitlines()[0] if avisos else "ninguno")
val, err = quad(lambda x: np.exp(-x), 0, 10, weight="cos", wvar=200)
print(f"con weight='cos': {val:.6e} ± {err:.1e}, error real {abs(val - exacta_osc):.1e}")Singularity does not break quad: QAGS does not evaluate endpoints (all Gauss–Kronrod nodes are interior) and its extrapolation absorbs it, but costs 231 evaluations; substitution needs 21 (one Kronrod rule), and algebraic weight 40. Infinite interval with np.inf costs 45 evaluations with zero error, while truncating at 100 leaves error that quad’s estimate () cannot see: it is the error of another integral. The last two cases show why not to trust results blindly. A peak far from the origin on returns 0 with estimated error 0, without warning: after transformation, the peak occupies a tiny strip of between QAGI’s 15 rule nodes and nobody sees it. The oscillatory integral returns instead of , this time with an IntegrationWarning saying the integral is probably divergent. With the proper oscillatory weight (weight='cos', using Clenshaw–Curtis rules with Chebyshev moments), actual error is below .
The curse of dimensionality
Everything so far is one-dimensional. The obvious way to integrate on is a product rule: take an -point rule per axis and all combinations,
using evaluations. If the 1D rule has error for integrands with bounded derivatives of order , the product rule keeps that error in , but in cost terms it is
This is the curse of dimensionality in quadrature: effective order is divided by dimension. Trapezoid () in has error : gaining a digit requires multiplying evaluations by . Monte Carlo, with error , has rate in any dimension (its constant may depend on ). Beyond some , it always wins.
The interactive model deliberately favors the grid because integrand is a product, but already shows explosion. The cell computes the same numbers.
import numpy as np
x0 = np.sqrt(5) - 2
media_esquina = 1 + (x0**2 + (1 - x0)**2) / 2
g_exp = lambda x: np.exp(x) / (np.e - 1)
g_esq = lambda x: (1 + np.abs(x - x0)) / media_esquina
Eg2 = {"analítica": (np.e + 1) / (2 * (np.e - 1)),
"con esquina": (1 + x0**2 + (1 - x0)**2 + (x0**3 + (1 - x0)**3) / 3) / media_esquina**2}
def Q_trap(g, n): # trapecio 1D con n puntos en [0, 1]
x = np.linspace(0, 1, n)
y = g(x)
return (y.sum() - 0.5 * (y[0] + y[-1])) / (n - 1)
def Q_gauss(g, n): # Gauss-Legendre 1D con n puntos en [0, 1]
t, w = np.polynomial.legendre.leggauss(n)
return 0.5 * w @ g((t + 1) / 2)
def N_producto(Q, g, d, eps, nmin, nmax):
for n in range(nmin, nmax):
if abs(Q(g, n) ** d - 1) <= eps: # integrando separable: la regla producto da Q_n^d
return float(n) ** d
return np.nan
eps = 1e-3
for nombre, g in [("analítica", g_exp), ("con esquina", g_esq)]:
print(f"g {nombre}: evaluaciones para error relativo {eps:g}")
print(" d trapecio Gauss Monte Carlo")
for d in [1, 2, 3, 4, 5, 6, 8, 10]:
nt = N_producto(Q_trap, g, d, eps, 2, 3000)
ng = N_producto(Q_gauss, g, d, eps, 1, 300)
nmc = (Eg2[nombre] ** d - 1) / eps**2 # σ²/ε²
print(f" {d:2d} {nt:10.1e} {ng:10.1e} {nmc:10.1e}")With cornered and , product trapezoid rises from 13 evaluations in to in (Monte Carlo: ) and in (Monte Carlo: ); product Gauss, also order 2 with a corner, crosses at ( versus ). At product rules need over evaluations and Monte Carlo . With analytic , product Gauss holds much longer ( evaluations in , versus for Monte Carlo) because 3 points per axis suffice, but even infinite smoothness does not escape: with points per axis the grid has at least points, over at , and at fits no computer.
In practice, the reasonable frontier for product rules is around to , depending on smoothness and target accuracy. Beyond that two options exist. Smolyak sparse grids combine 1D rules of different levels so point count grows like rather than , at the cost of bounded mixed derivatives; they work through several dozen dimensions. And Monte Carlo, in lesson 18, whose rate is independent of and which, with low-discrepancy sequences (quasi-Monte Carlo), improves to nearly for sufficiently regular integrands.
In the libraries
| Function | What it does | When |
|---|---|---|
scipy.integrate.quad(f, a, b) | QUADPACK: adaptive 21-point Gauss–Kronrod with extrapolation (QAGS); np.inf activates QAGI; points= marks interior singularities; weight= for algebraic, logarithmic, oscillatory or Cauchy weights | default for evaluable anywhere |
scipy.integrate.quad_vec(f, a, b) | adaptive for vector-output : one subdivision tree for all components | integrate many functions sharing difficult regions |
scipy.integrate.trapezoid(y, x), np.trapezoid(y, x) | trapezoid on sampled data | measured data; periodic integrands over one period |
scipy.integrate.simpson(y, x=x) | Simpson on sampled data | smooth equally spaced data |
scipy.integrate.romb(y, dx) | Romberg on equally spaced samples | smooth data with points |
np.polynomial.legendre.leggauss(n), hermite.hermgauss(n), hermite_e.hermegauss(n), laguerre.laggauss(n) | Gaussian nodes and weights | repeated integrals with same weight, in loops or vectorized |
scipy.integrate.nquad, dblquad, tplquad | nested quad | with reasonable integrands |
import numpy as np
import scipy
import scipy.integrate as si
print("NumPy", np.__version__, " SciPy", scipy.__version__)
print("¿existe np.trapz?", hasattr(np, "trapz"), " ¿existe scipy.integrate.romberg?", hasattr(si, "romberg"))
x = np.linspace(0, 1, 33) # 2^5 + 1 muestras de e^x
y = np.exp(x)
I = np.e - 1
print(f"np.trapezoid: {abs(np.trapezoid(y, x) - I):.1e} simpson: {abs(si.simpson(y, x=x) - I):.1e} romb: {abs(si.romb(y, dx=x[1] - x[0]) - I):.1e}")
t, w = np.polynomial.legendre.leggauss(8)
print(f"leggauss(8) en [0, 1]: {abs(0.5 * w @ np.exp((t + 1) / 2) - I):.1e}")
val, err, info = si.quad(np.exp, 0, 1, full_output=1)[:3]
print(f"quad: error real {abs(val - I):.1e}, estimado {err:.1e}, {info['neval']} evaluaciones")
# quad_vec: E[X^k] para k = 0..5 con X ~ N(0, 1), un solo árbol de subdivisión
k = np.arange(6)
res, err = si.quad_vec(lambda x: x**k * np.exp(-x * x / 2) / np.sqrt(2 * np.pi), -np.inf, np.inf)
print("quad_vec, momentos de N(0, 1):", np.round(res, 10))This cell’s output shows the silliest pitfall: np.trapz no longer exists in this browser’s NumPy version. It was deprecated in NumPy 2.0 in favor of np.trapezoid, and scipy.integrate.romberg (the function-taking version) was deprecated in SciPy 1.12 and removed in 1.15; romb, taking samples, remains.
Common mistakes
Exercises
quad without options do, and what is advisable?Step 1 of 5. What is the first step?
romberg(f, a, b, tol=1e-10, max_niveles=20), building the Romberg table row by row and stopping once tol (with ). Return (valor, R, evals): value , table as a (k+1)×(k+1) array with zeros above the diagonal, and total number of points where f was evaluated. f accepts arrays. Each new row may evaluate f only at new midpoints: row costs evaluations total.import numpy as np
def romberg(f, a, b, tol=1e-10, max_niveles=20):
"""Devuelve (valor, R, evals)."""
R = np.zeros((max_niveles, max_niveles))
R[0, 0] = (b - a) / 2 * (f(a) + f(b))
evals = 2
# tu código: para k = 1, 2, ...: trapecio con 2^k subintervalos reutilizando R[k-1, 0],
# columnas de Richardson y criterio de parada
return R[0, 0], R[:1, :1], evalsSummary
- Composite trapezoid and Simpson have errors and . Euler–Maclaurin gives trapezoid’s full expansion in even powers of , with coefficients depending only on endpoint derivatives.
- Richardson combines and to cancel (obtaining Simpson); Romberg repeats in cascade while reusing evaluations. It works only if the error expansion exists.
- The -point Gaussian rule has degree , the maximum, positive weights and converges for every continuous with error . Nodes and weights are eigenvalues and first eigenvector components of the Jacobi matrix (Golub–Welsch). Gauss–Hermite with computes Gaussian expectations with a few nodes.
- Clenshaw–Curtis, with half the degree, is often as accurate as Gauss and has nested nodes and FFT weights.
- Trapezoid with points over a period only incurs aliasing error , falling as if is analytic in a strip of width .
- Adaptive routines (adaptive Simpson, Gauss–Kronrod in QUADPACK) estimate error per panel and subdivide where needed, but see only what they sample: read warnings, mark singularities and transform infinite intervals.
- A product rule with points has error ; Monte Carlo, in any dimension. Beyond to , the grid ceases to be viable.
Connections. Gauss–Hermite reappears in approximate inference alongside the Laplace approximation whenever a nonconjugate likelihood requires integrating against a normal distribution. Option pricing beyond the Black–Scholes formula integrates cornered payoffs like this lesson’s, and transform methods use the same quadratures. Finite elements integrate each element with Gaussian rules, and sparse grids are the deterministic response to dimensionality’s curse.
Further reading. Davis and Rabinowitz, Methods of Numerical Integration, is the encyclopedic reference. The two cited Trefethen papers (Gauss versus Clenshaw–Curtis, 2008, and exponentially convergent trapezoid with Weideman, 2014) are short and readable. Golub and Welsch (1969) fits in a few pages, and the QUADPACK book documents routines beneath quad.