Module contents
Lesson 11 of 26Review 85 min

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 E[f(X)]\E[f(X)] with X∼N(μ,σ2)X \sim \Normal(\mu, \sigma^2), namely ∫f(x) φμ,σ(x) ⁣dx\int f(x)\,\varphi_{\mu,\sigma}(x)\dd x, for ff like log⁡(1+ex)\log(1 + e^x) or Φ(x)\Phi(x). 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,

I(f)=∫abf(x) w(x) ⁣dx  ≈  Qn(f)=∑j=1nwj f(xj),I(f) = \int_a^b f(x)\,w(x)\dd x \;\approx\; Q_n(f) = \sum_{j=1}^{n} w_j\,f(x_j),

with nodes xjx_j and weights wjw_j independent of ff, and a weight function w(x)≥0w(x) \ge 0 (almost always w≡1w \equiv 1). Cost is measured in evaluations of ff, because evaluating ff 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 ff. If pn−1p_{n-1} is the interpolating polynomial of ff at nn distinct nodes, pn−1(x)=∑jf(xj) ℓj(x)p_{n-1}(x) = \sum_j f(x_j)\,\ell_j(x) with Lagrange basis ℓj\ell_j, then

∫abpn−1(x) ⁣dx=∑jwjf(xj),wj=∫abℓj(x) ⁣dx.\int_a^b p_{n-1}(x)\dd x = \sum_j w_j f(x_j), \qquad w_j = \int_a^b \ell_j(x)\dd x .

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 [xi,xi+1][x_i, x_{i+1}], linear interpolation error is f(x)−p1(x)=12f′′(ηx)(x−xi)(x−xi+1)f(x) - p_1(x) = \tfrac12 f''(\eta_x)(x - x_i)(x - x_{i+1}). Factor (x−xi)(x−xi+1)(x - x_i)(x - x_{i+1}) does not change sign on the subinterval, so the mean value theorem for integrals with constant-sign weight gives ξi\xi_i with

∫xixi+1(f−p1)=12f′′(ξi)∫xixi+1(x−xi)(x−xi+1) ⁣dx=−h312f′′(ξi).\int_{x_i}^{x_{i+1}} (f - p_1) = \tfrac12 f''(\xi_i)\int_{x_i}^{x_{i+1}} (x - x_i)(x - x_{i+1})\dd x = -\tfrac{h^3}{12} f''(\xi_i).

Summing the mm subintervals, Th−I=h312∑if′′(ξi)=h3m12 f′′‾T_h - I = \tfrac{h^3}{12}\sum_i f''(\xi_i) = \tfrac{h^3 m}{12}\,\overline{f''}, where f′′‾\overline{f''} is the mean of f′′(ξi)f''(\xi_i). Since f′′f'' is continuous and the mean lies between minimum and maximum, the intermediate value theorem gives ξ\xi with f′′(ξ)=f′′‾f''(\xi) = \overline{f''}, and h3m=(b−a)h2h^3 m = (b - a)h^2.

(2) The argument is the same with a subtlety: Simpson’s nodal polynomial on [x2i,x2i+2][x_{2i}, x_{2i+2}], (x−x2i)(x−x2i+1)(x−x2i+2)(x - x_{2i})(x - x_{2i+1})(x - x_{2i+2}), changes sign and integrates to zero. Thus Simpson, interpolating degree 2, integrates cubics exactly (degree of exactness 3, one above the guarantee). Let HH be the cubic interpolating ff at the three nodes and also f′f' at the center. Simpson is exact on HH and HH matches ff at nodes, so Simpson error on the pair is ∫(f−H)\int (f - H). Hermite error is 124f(4)(ηx)(x−x2i)(x−x2i+1)2(x−x2i+2)\tfrac{1}{24}f^{(4)}(\eta_x)(x - x_{2i})(x - x_{2i+1})^2(x - x_{2i+2}), whose polynomial factor has constant sign, and the mean value theorem gives ∫x2ix2i+2f−S=−h590f(4)(ξi)\int_{x_{2i}}^{x_{2i+2}} f - S = -\tfrac{h^5}{90}f^{(4)}(\xi_i). Sum the m/2m/2 pairs and apply intermediate value again to obtain the result, since m2⋅h590=(b−a)h4180\tfrac{m}{2}\cdot\tfrac{h^5}{90} = \tfrac{(b - a)h^4}{180}.

∎

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 −2-2 and −4-4. The ladder below shows them alongside two upcoming rules (Gauss–Legendre and Clenshaw–Curtis), on five integrands of different difficulty.

InteractiveThe error ladder
  • Trapezoid
  • Simpson
  • Gauss-Legendre
  • Clenshaw-Curtis
error nowapparent orderevals. to 10⁻¹⁰Trapezoid···Simpson···Gauss-Legendre···Clenshaw-Curtis···
∫−11ex  ⁣dx=e−e−1\int_{-1}^{1} e^{x}\,\dd x = e - e^{-1}
Nodes to draw
9
Entire: trapezoid falls with slope −2 and Simpson with −4; Gauss and Clenshaw–Curtis reach machine precision with fewer than 15 points.
Relative error versus evaluations of ff on log-log axes for trapezoid (orange), Simpson (aqua), Gauss–Legendre (blue) and Clenshaw–Curtis (magenta), computed live. Above, integrand and selected rule's nodes at slider budget. In the table, apparent order is measured by doubling evaluations. Start with exe^x: slopes −2-2 and −4-4 are straight and Gaussian rules plummet. Switch to the corner: what remains of high order? Then the periodic function: who wins now? And the endpoint square root: which rules suffer least?

Three things visible in the figure, explained one by one. First, theoretical order appears only if ff 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 hh. The latter makes the next section’s Richardson extrapolation work. Second: if all odd derivatives match at aa and bb, all terms vanish and error is smaller than any power of hh. 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 mm should approach 2p2^p.

[ ]Composite trapezoid and Simpson: order measuredBrowser
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 4.0004.000 and Simpson ratios 16.00016.000, and Euler–Maclaurin’s leading term predicts trapezoid error to five digits already at n=32n = 32 (1.398319×10−41.398319\times 10^{-4} measured versus 1.398341×10−41.398341\times 10^{-4}). With the corner, by contrast, errors decrease irregularly and Simpson is not systematically better than trapezoid (at n=64n = 64 it is worse: 4.90×10−54.90\times 10^{-5} versus 2.36×10−52.36\times 10^{-5}). From n=16n = 16 to n=256n = 256 both gain just over two digits, corresponding to order 2 (multiplying nn by 16 divides error by 256256), not order 4 (which would divide by 65 53665\,536).

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 ff 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, ∑j∣wj∣=3.06 (b−a)\sum_j \abs{w_j} = 3.06\,(b - a), so rounding or measurement error of size δ\delta in f(xj)f(x_j) can cause error 3.06 (b−a) δ3.06\,(b - a)\,\delta instead of (b−a) δ(b - a)\,\delta, and the factor grows exponentially with point count. Practical lesson: compose low-degree rules (increase mm, not degree) or choose better nodes, as Gauss does.

Richardson extrapolation and Romberg

Euler–Maclaurin says Th=I+c1h2+c2h4+⋯T_h = I + c_1 h^2 + c_2 h^4 + \cdots with coefficients ckc_k independent of hh. With steps hh and h/2h/2:

Th=I+c1h2+c2h4+⋯ ,Th/2=I+14c1h2+116c2h4+⋯T_h = I + c_1 h^2 + c_2 h^4 + \cdots, \qquad T_{h/2} = I + \tfrac14 c_1 h^2 + \tfrac1{16} c_2 h^4 + \cdots

Multiply the second by 4, subtract the first and divide by 3: the h2h^2 term vanishes,

4Th/2−Th3=I−14c2h4+⋯\frac{4T_{h/2} - T_h}{3} = I - \tfrac14 c_2 h^4 + \cdots

This is Richardson extrapolation: knowing the error form, combine two approximations to cancel its leading term. Something beautiful happens here: 13(4Th/2−Th)\tfrac13(4T_{h/2} - T_h) is term by term Simpson’s rule with step h/2h/2. Simpson is extrapolated trapezoid. The same trick gives a free error estimator: Th/2−I≈13(Th/2−Th)T_{h/2} - I \approx \tfrac13(T_{h/2} - T_h), because the difference of two approximations is three times the better one’s error.

Nothing prevents repetition. If Rk,0=Th0/2kR_{k,0} = T_{h_0/2^k}, each new column eliminates the next even power:

Rk,j=Rk,j−1+Rk,j−1−Rk−1,j−14j−1,Rk,j−I=O(hk2j+2).R_{k,j} = R_{k,j-1} + \frac{R_{k,j-1} - R_{k-1,j-1}}{4^j - 1}, \qquad R_{k,j} - I = \bigO\big(h_k^{2j+2}\big).

This is the Romberg method (Werner Romberg, 1955). Its practical advantage is reuse: trapezoid with 2k2^k subintervals only needs evaluating ff at the 2k−12^{k-1} new midpoints, Rk,0=12Rk−1,0+hk∑nuevosfR_{k,0} = \tfrac12 R_{k-1,0} + h_k\sum_{\text{nuevos}} f. Row kk costs 2k+12^k + 1 evaluations total.

[ ]Romberg from scratchBrowser
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 exe^x, 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 10710^7 points. With x\sqrt{x} the result is very different: derivative explodes at 0, the Euler–Maclaurin expansion does not exist (error contains h3/2h^{3/2}, as ratios ≈2.82≈23/2\approx 2.82 \approx 2^{3/2} 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: nn free parameters, degree n−1n - 1 (sometimes nn by symmetry). If nodes are also free there are 2n2n parameters, and one might expect enough to integrate exactly the 2n2n monomials 1,x,…,x2n−11, x, \dots, x^{2n-1}. Before theory, find them yourself.

InteractiveBuild your own nodes
  • nodes xjx_j
  • weights wjw_j
  • ω(x)=∏j(x−xj)\omega(x) = \prod_j (x - x_j), scaled
∣cos⁡∠(ω,Pk)∣\abs{\cos\angle(\omega, P_k)} on a log scale: a bar at the floor means ω⊥Pk\omega \perp P_k
3
Degree of exactness3
Guaranteed · maximum possible2 · 5
Minimum weight0.3333
Relative error in ∫−11ex dx\int_{-1}^1 e^x\,dx5.0e−3
Same with nn-node Gauss2.8e−5
Drag the nn nodes (blue) across [−1,1][-1, 1]. Weights (bars) are recalculated so the rule is interpolatory and its actual degree of exactness measured. Violet curve is nodal polynomial ω(x)=∏j(x−xj)\omega(x) = \prod_j (x - x_j). Below, how far ω\omega is from orthogonal to each Legendre polynomial PkP_k: degree is n−1n - 1 plus the number of initial bars touching the floor. Start at Simpson nodes (degree 3, one more than guaranteed: why?). Move the center node and watch degree fall. With symmetry enabled, which degrees do you get? Press ‘Find with Newton’: where do nodes go and what degree do they reach? Raise to n=9n = 9 with equally spaced nodes (press ‘Equally spaced’): what happens to weights? And with n=10n = 10?

What you just saw is the central theorem. The PkP_k bar measures whether ∫ω Pk=0\int \omega\,P_k = 0, and the rule gains one degree for each PkP_k (starting at P0P_0) to which ω\omega is orthogonal. With nn nodes, ω\omega has degree nn and can be orthogonal to at most P0,…,Pn−1P_0, \dots, P_{n-1}: then ω\omega is, up to a constant, PnP_n itself, and nodes are its zeros.

For the definition to make sense the zeros of pnp_n must be real, simple and in (a,b)(a, b). A classic argument: if pnp_n changed sign at only r<nr < n points t1,…,trt_1, \dots, t_r of (a,b)(a, b), product pn(x)∏i(x−ti)p_n(x)\prod_i(x - t_i) would have constant sign and its integral with weight ww would be nonzero, contradicting orthogonality of pnp_n to every polynomial of degree r<nr < n.

Proof

(1) You will prove it step by step in the final guided exercise.

(2) ℓj2\ell_j^2 has degree 2n−2≤2n−12n - 2 \le 2n - 1, so the rule is exact on it: ∫ℓj2 w=∑iwi ℓj(xi)2=wj\int \ell_j^2\,w = \sum_i w_i\,\ell_j(x_i)^2 = w_j, because ℓj(xi)=δij\ell_j(x_i) = \delta_{ij}. The integral is positive because ℓj2≥0\ell_j^2 \ge 0 is not identically zero. The sum follows by applying exactness to f≡1f \equiv 1.

(3) Interpolate ff and f′f' at nodes with the degree-2n−12n - 1 Hermite polynomial HH; the rule is exact on it and H(xj)=f(xj)H(x_j) = f(x_j), so I(f)−Gn(f)=∫(f−H) wI(f) - G_n(f) = \int (f - H)\,w. Hermite error is f(2n)(ηx)(2n)! ω(x)2\frac{f^{(2n)}(\eta_x)}{(2n)!}\,\omega(x)^2, with ω=pn\omega = p_n; polynomial factor ω2\omega^2 has constant sign, and the mean value theorem with weight ω2w≥0\omega^2 w \ge 0 concludes.

(4) For any pp of degree ≤2n−1\le 2n - 1, I(f)−Gn(f)=I(f−p)−Gn(f−p)I(f) - G_n(f) = I(f - p) - G_n(f - p) because the rule is exact on pp. And ∣I(f−p)∣≤μ0∥f−p∥∞\abs{I(f - p)} \le \mu_0\norm{f - p}_\infty,   ∣Gn(f−p)∣≤∑jwj∥f−p∥∞=μ0∥f−p∥∞\;\abs{G_n(f - p)} \le \sum_j w_j\norm{f - p}_\infty = \mu_0\norm{f - p}_\infty, because weights are positive. Take pp as the best approximant.

∎

Point 4 is the deep reason Gauss is so good for analytic functions: E2n−1(f)E_{2n-1}(f) is the best degree-2n−12n - 1 polynomial approximation error, which in the prior lesson you saw decrease geometrically for analytic functions, like the Chebyshev series. If ff is analytic in the Bernstein ellipse with parameter ρ>1\rho > 1, Gauss error is O(ρ−2n)\bigO(\rho^{-2n}). 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 pnp_n and weights computed? Neither root formulas nor a Vandermonde system (ill-conditioned). Monic orthogonal polynomials satisfy a three-term recurrence,

pk+1(x)=(x−αk) pk(x)−βk pk−1(x),p−1=0, p0=1,p_{k+1}(x) = (x - \alpha_k)\,p_k(x) - \beta_k\,p_{k-1}(x), \qquad p_{-1} = 0,\ p_0 = 1,

with βk>0\beta_k > 0. For Legendre, αk=0\alpha_k = 0 and βk=k2/(4k2−1)\beta_k = k^2/(4k^2 - 1); for Hermite with weight e−x2/2e^{-x^2/2} (probabilists’ version), αk=0\alpha_k = 0 and βk=k\beta_k = k.

Proof

Let p^k=pk/∥pk∥\hat p_k = p_k/\norm{p_k} be orthonormal polynomials. The recurrence becomes x p^k=βk+1 p^k+1+αkp^k+βk p^k−1x\,\hat p_k = \sqrt{\beta_{k+1}}\,\hat p_{k+1} + \alpha_k\hat p_k + \sqrt{\beta_k}\,\hat p_{k-1}, because ∥pk+1∥2/∥pk∥2=βk+1\norm{p_{k+1}}^2/\norm{p_k}^2 = \beta_{k+1}. With p^(x)=(p^0(x),…,p^n−1(x))⊤\hat{\vb{p}}(x) = (\hat p_0(x), \dots, \hat p_{n-1}(x))\T, all nn equations together are

x p^(x)=Jn p^(x)+βn p^n(x) en.x\,\hat{\vb{p}}(x) = \mat{J}_n\,\hat{\vb{p}}(x) + \sqrt{\beta_n}\,\hat p_n(x)\,\vb{e}_n .

At a zero xjx_j of pnp_n the last term vanishes: Jnp^(xj)=xjp^(xj)\mat{J}_n\hat{\vb{p}}(x_j) = x_j\hat{\vb{p}}(x_j), and p^(xj)≠0\hat{\vb{p}}(x_j) \ne \vb{0} because p^0=1/μ0\hat p_0 = 1/\sqrt{\mu_0}. Thus the nn distinct zeros are the nn eigenvalues.

For weights, the rule is exact on p^kp^l\hat p_k\hat p_l (k,l<nk, l < n, degree ≤2n−2\le 2n - 2): ∑jwj p^k(xj)p^l(xj)=δkl\sum_j w_j\,\hat p_k(x_j)\hat p_l(x_j) = \delta_{kl}. With Pkj=p^k(xj)\mat{P}_{kj} = \hat p_k(x_j) and W=diag⁡(wj)\mat{W} = \diag(w_j), this is PWP⊤=I\mat{P}\mat{W}\mat{P}\T = \mat{I}, so P\mat{P} is invertible and P⊤P=W−1\mat{P}\T\mat{P} = \mat{W}\inv. The diagonal gives 1/wj=∥p^(xj)∥21/w_j = \norm{\hat{\vb{p}}(x_j)}^2. Since vj=p^(xj)/∥p^(xj)∥\vb{v}_j = \hat{\vb{p}}(x_j)/\norm{\hat{\vb{p}}(x_j)}, its first component squared is p^02 wj=wj/μ0\hat p_0^2\,w_j = w_j/\mu_0.

∎

The calculation is entirely a symmetric matrix eigenvalue problem, tridiagonal, the most stable case. Golub and Welsch solved it in O(n2)\bigO(n^2) with tridiagonal QR, calculating only each eigenvector’s first component; eigh on the dense matrix as in the cell costs O(n3)\bigO(n^3), irrelevant for n≤100n \le 100.

[ ]Gauss–Legendre and Gauss–Hermite by Golub–WelschBrowser
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 10−1510^{-15}, all weights positive (minimum with n=100n = 100 is 7.35×10−47.35\times 10^{-4}), the 5-point rule integrates x9x^9 exactly and fails on x10x^{10}, and gives exactly 0 for ω2\omega^2 versus ∫ω2=2.931812×10−3\int\omega^2 = 2.931812\times 10^{-3}. That matches the closed formula for Legendre, ∫−11pn2=22n+1(n!)4(2n+1) ((2n)!)2\int_{-1}^1 p_n^2 = \frac{2^{2n+1}(n!)^4}{(2n+1)\,((2n)!)^2}, which at n=5n = 5 gives 2.9318×10−32.9318\times 10^{-3}, and is the theorem point 3 error-term constant.

Gauss–Hermite for Gaussian expectations

A normal distribution is exactly the Hermite weight. If X∼N(μ,σ2)X \sim \Normal(\mu, \sigma^2), the substitution x=μ+2 σtx = \mu + \sqrt2\,\sigma t turns the density into e−t2/πe^{-t^2}/\sqrt\pi:

E[f(X)]=∫Rf(x) e−(x−μ)2/(2σ2)2π σ ⁣dx=1π∫Rf(μ+2 σt) e−t2 ⁣dt≈1π∑i=1nwi f(μ+2 σ ti),\E[f(X)] = \int_{\R} f(x)\,\frac{e^{-(x - \mu)^2/(2\sigma^2)}}{\sqrt{2\pi}\,\sigma}\dd x = \frac{1}{\sqrt\pi}\int_{\R} f(\mu + \sqrt2\,\sigma t)\,e^{-t^2}\dd t \approx \frac{1}{\sqrt\pi}\sum_{i=1}^n w_i\,f(\mu + \sqrt2\,\sigma\,t_i),

with Gauss–Hermite nodes and weights (ti,wi)(t_i, w_i) for weight e−t2e^{-t^2} (from np.polynomial.hermite.hermgauss). This is Gauss–Hermite for Gaussian expectations: with nn evaluations it is exact for polynomial ff of degree ≤2n−1\le 2n - 1, and converges quickly for smooth ff. With the probabilists’ version (hermegauss, weight e−t2/2e^{-t^2/2}) the substitution is x=μ+σtx = \mu + \sigma t and factor 1/2π1/\sqrt{2\pi}. Mixing conventions is the commonest mistake: missing or extra 2\sqrt2 changes variance.

Three real use cases with exact references:

[ ]Gaussian expectations: softplusBrowser
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 3.8×10−53.8\times 10^{-5}, and at 20, 4.2×10−74.2\times 10^{-7}; Monte Carlo with 10510^5 samples remains at 4.1×10−34.1\times 10^{-3}, because its error decreases as N−1/2N^{-1/2} (see the Monte Carlo lesson). Softplus is not polynomial and has complex singularities (logarithm branch points where ex=−1e^x = -1) at x=±iπx = \pm i\pi, so convergence is quick but not instant. Forgetting 2\sqrt2 causes error 0.160.16: an expectation under variance σ2/2\sigma^2/2 instead of σ2\sigma^2.

[ ]Gaussian expectations: a call and a random-effects probitBrowser
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, Φ\Phi is entire and convergence spectacular: 16 nodes per datum give log likelihood error 8.8×10−118.8\times 10^{-11}, while Monte Carlo with 10410^4 samples per datum (two million evaluations) remains at 5.0×10−25.0\times 10^{-2}. 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 max⁡(ST−K,0)\max(S_T - K, 0) has a corner at z∗=0.3862z^* = 0.3862, and Gauss–Hermite crawls: multiplying nodes by 16 (10 to 160) only takes error from 3.5×10−13.5\times 10^{-1} to 3.5×10−23.5\times 10^{-2}, and along the way it is nonmonotonic (3.9×10−23.9\times 10^{-2} at 40 nodes, 4.5×10−24.5\times 10^{-2} 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 z∗z^* gives price error 5×10−155\times 10^{-15} in 135 evaluations.

Clenshaw–Curtis versus Gauss

Another natural node choice is to interpolate ff at Chebyshev points (extrema of TnT_n), xk=cos⁡(kπ/n)x_k = \cos(k\pi/n), k=0,…,nk = 0, \dots, n, and integrate the interpolant exactly. This is the Clenshaw–Curtis rule (1960). With n+1n + 1 points it has degree nn, half Gauss with the same points. But it has three practical advantages: weights are computed by FFT in O(nlog⁡n)\bigO(n\log n) because interpolation there uses a cosine transform (see Chebyshev nodes and FFT); nodes are nested (those for nn are a subset of those for 2n2n, so doubling reuses all evaluations as in Romberg); and weights are all positive (the cell checks through n=256n = 256), so theorem point 4 for Gauss also holds with En(f)E_n(f) instead of E2n−1(f)E_{2n-1}(f).

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 [−1,1][-1, 1], like exe^x. His explanation interprets each rule as a rational approximation of log⁡z+1z−1\log\frac{z + 1}{z - 1}: Gauss is a Padé approximant at z=∞z = \infty and Clenshaw–Curtis has half the order there, but is equally accurate near [−1,1][-1, 1], what matters except for functions with very distant singularities.

[ ]Clenshaw–Curtis versus Gauss on an integrand benchmarkBrowser
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 exe^x, Gauss is already at 10−1610^{-16} with 9 points and Clenshaw–Curtis at 8.7×10−128.7\times 10^{-12}: the factor 2 really appears here. With 1/(1+25x2)1/(1 + 25x^2), whose poles at ±i/5\pm i/5 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 ff‘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 ff is 2π2\pi-periodic, trapezoid with NN subintervals on [0,2π][0, 2\pi] is simply the mean of NN equally spaced samples, because f(0)=f(2π)f(0) = f(2\pi) and the two half weights add:

TN(f)=2πN∑m=0N−1f(θm),θm=2πmN.T_N(f) = \frac{2\pi}{N}\sum_{m=0}^{N-1} f(\theta_m), \qquad \theta_m = \frac{2\pi m}{N}.
Proof

The rule applied to eikθe^{ik\theta} is 2πN∑me2πikm/N\frac{2\pi}{N}\sum_m e^{2\pi i km/N}, a geometric sum equal to 2π2\pi if NN divides kk and 00 otherwise: DFT orthogonality. Absolute convergence permits interchanging the rule and Fourier sums, and since I(f)=2πc0I(f) = 2\pi c_0, the first formula follows.

For the bound, ck=12π∫02πf(θ)e−ikθ ⁣dθc_k = \frac1{2\pi}\int_0^{2\pi} f(\theta)e^{-ik\theta}\dd\theta. If k>0k > 0, shift the integration segment to Im⁡θ=−b\operatorname{Im}\theta = -b with 0<b<a0 < b < a: by periodicity vertical sides cancel, by Cauchy’s theorem the integral is unchanged, and ∣e−ikθ∣=e−kb\abs{e^{-ik\theta}} = e^{-kb} there, so ∣ck∣≤Me−bk\abs{c_k} \le M e^{-bk}; for k<0k < 0 shift upward. Letting b→ab \to a, ∣ck∣≤Me−a∣k∣\abs{c_k} \le M e^{-a\abs{k}}, and then ∣TN−I∣≤2π⋅2M∑j≥1e−ajN=4πMeaN−1\abs{T_N - I} \le 2\pi\cdot 2M\sum_{j \ge 1} e^{-ajN} = \frac{4\pi M}{e^{aN} - 1}.

∎

This is the trapezoidal rule for periodic functions: trapezoid with NN points integrates exactly every trigonometric polynomial of degree ≤N−1\le N - 1, and its only error is Fourier coefficients sampling confuses with the constant (frequencies k=jNk = jN, aliasing). If ff is analytic in a strip of width aa, error falls as e−aNe^{-aN}, faster for a wider strip.

InteractiveWhat trapezoid cannot see
|c_k| on a log scale versus frequency k
  • c0c_0: the integral is 2πc02\pi c_0
  • cjNc_{jN}: added to c0c_0 (aliasing), forming the error
  • the rest: the rule integrates them exactly to 0
f(θ)=1−ρ21−2ρcos⁡θ+ρ2=∑kρ∣k∣eikθf(\theta) = \frac{1 - \rho^2}{1 - 2\rho\cos\theta + \rho^2} = \sum_{k} \rho^{\abs{k}} e^{ik\theta}
0.50
8
Measured error ∣TN−2π∣\abs{T_N - 2\pi}4.93e−2
Formula 4πρN/(1−ρN)4\pi\rho^N/(1 - \rho^N)4.93e−2
Digits gained per point, −log⁡10ρ-\log_{10}\rho0.301
Poisson kernel f(θ)=(1−ρ2)/(1−2ρcos⁡θ+ρ2)f(\theta) = (1 - \rho^2)/(1 - 2\rho\cos\theta + \rho^2) has exact Fourier coefficients ck=ρ∣k∣c_k = \rho^{\abs{k}} and integral 2π2\pi. Above, ff and NN trapezoid samples. Below, log⁡10∣ck∣\log_{10}\abs{c_k}: the rule sums c0c_0 (aqua) plus cjNc_{jN} (orange), nothing else. Raise NN and see orange stems recede and fall: measured error matches 4πρN/(1−ρN)4\pi\rho^N/(1 - \rho^N). Move ρ\rho near 1, bringing ff's poles near the real axis: the analyticity strip narrows and many more points are needed.

In the figure’s example poles are at Im⁡θ=±ln⁡(1/ρ)\operatorname{Im}\theta = \pm\ln(1/\rho), so each point adds −log⁡10ρ-\log_{10}\rho correct digits: 0.3010.301 with ρ=1/2\rho = 1/2 and only 0.0220.022 with ρ=0.95\rho = 0.95. For the ladder integrand, 1/(2+cos⁡θ)1/(2 + \cos\theta), poles satisfy cos⁡θ=−2\cos\theta = -2, at distance a=ln⁡(2+3)=1.317a = \ln(2 + \sqrt3) = 1.317 from the axis, and ck=(−ρ)∣k∣/3c_k = (-\rho)^{\abs{k}}/\sqrt3 with ρ=2−3\rho = 2 - \sqrt3. The cell verifies it alongside ecos⁡θe^{\cos\theta}, which is entire and converges faster than any exponential: its error is 4π∑j≥1IjN(1)4\pi\sum_{j\ge1} I_{jN}(1), with IkI_k the modified Bessel function.

[ ]Periodic trapezoid versus GaussBrowser
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 1/(2+cos⁡θ)1/(2 + \cos\theta) prediction matches measured error to three printed digits and trapezoid reaches 1.4×10−131.4\times 10^{-13} with 24 points; Gauss–Legendre with 24 remains at 1.5×10−81.5\times 10^{-8}, five orders worse. With ecos⁡θe^{\cos\theta}, 16 points suffice to reach rounding (1.8×10−151.8\times 10^{-15}), while Gauss–Legendre at those 16 points remains at 1.7×10−111.7\times 10^{-11}. In the last row prediction (9.3×10−189.3\times 10^{-18}) 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 S1S_1 is Simpson on panel [α,β][\alpha, \beta] and S2S_2 the sum of Simpson on its halves, then if f(4)f^{(4)} is nearly constant on the panel,

S2−I≈S2−S115,S_2 - I \approx \frac{S_2 - S_1}{15},

because S2S_2 error is 1/161/16 that of S1S_1. 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.

InteractiveAdaptive subdivision
  • evaluated points
  • final panels (leaves), one per depth level downward
  • already split panels
  • split in current step
f(x)=1∣x−s∣+6 e−((x−0.8)/0.01)2, s=0.32f(x) = \frac{1}{\sqrt{\abs{x - s}}} + 6\,e^{-((x - 0.8)/0.01)^2},\ s = 0.3\sqrt2
1e−5
split 96 of 96
f evaluations389
Panels · maximum depth97 · 33
Estimated error ∑∣S2−S1∣/15\sum \abs{S_2 - S_1}/159.7e−6
Actual error1.3e−6
Uniform Simpson evaluations for the same actual error> 10⁶
Global adaptive Simpson on 1/∣x−s∣+6e−((x−0.8)/0.01)21/\sqrt{\abs{x - s}} + 6e^{-((x - 0.8)/0.01)^2}, with s=0.32s = 0.3\sqrt2: an integrable singularity and a peak of width 0.01. Above, integrand and evaluated points (blue marks). Below, subdivision tree: each row is one depth level and blue bars are current panels. Play animation and see where levels stack. Compare evaluations with uniform Simpson at equal real error. Then loosen tolerance to 10−210^{-2}: what happened to the peak? And at 10−610^{-6}, is tolerance met?
[ ]Global adaptive Simpson from scratchBrowser
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 10−410^{-4} adaptive achieves actual error 8.4×10−58.4\times 10^{-5} with 201 evaluations; uniform Simpson with 262 145 evaluations remains at 2.3×10−32.3\times 10^{-3}, even worse than with 16 385 (1.8×10−31.8\times 10^{-3}). Near the singularity Simpson error decreases on average as h1/2h^{1/2} and erratically, depending how close the nearest node falls to ss: no reasonable number of uniform points fixes it. Silent failure: at tolerance 10−210^{-2} the algorithm stops after 17 evaluations with estimated error 9.8×10−39.8\times 10^{-3}, but actual error is 0.330.33. None of those 17 evaluations hit the peak, and to an algorithm seeing only ff values an unsampled peak does not exist. Optimistic estimator: at 10−610^{-6} actual error (4.3×10−64.3\times 10^{-6}) exceeds tolerance, because near the singularity Simpson error does not fall as h4h^4 and factor 1/151/15 is no longer valid. quad without hints suffers the same: exhausts 50 subintervals (2079 evaluations) and remains at error 1.0×10−61.0\times 10^{-6}; with points=[s, 0.8] it knows where to split and reaches 3.1×10−153.1\times 10^{-15} 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 GnG_n with G2nG_{2n} to estimate error costs 3n3n evaluations without reuse. Kronrod adds n+1n + 1 new nodes to the nn Gauss nodes, chosen so the 2n+12n + 1-point rule has the highest possible degree (at least 3n+13n + 1). Pair G10G_{10}, K21K_{21} costs 21 evaluations and gives a highly accurate rule (K21K_{21}) plus an error estimate (∣K21−G10∣\abs{K_{21} - G_{10}}). QUADPACK does not use that difference directly: it corrects it with empirical formula ε=I~ min⁡(1,(200∣K21−G10∣/I~)3/2)\varepsilon = \tilde I\,\min\big(1, (200\abs{K_{21} - G_{10}}/\tilde I)^{3/2}\big), with I~=∫panel∣f−fˉ∣\tilde I = \int_{\text{panel}} \abs{f - \bar f}, absolute deviation of ff from its panel mean fˉ\bar f (computed using the Kronrod rule itself), because ∣K−G∣\abs{K - G} measures GG error and greatly overestimates KK error.

Singularities and infinite intervals

Two situations where helping the algorithm with a change of variables is useful:

  • Integrable endpoint singularity, like ∫01g(x)/x ⁣dx\int_0^1 g(x)/\sqrt x\dd x with smooth gg. With x=t2x = t^2,  ⁣dx=2t ⁣dt\dd x = 2t\dd t and the integral becomes ∫012g(t2) ⁣dt\int_0^1 2g(t^2)\dd t, without singularity. Alternatively tell quad the weight is x−1/2x^{-1/2} with weight='alg', and it uses a rule exactly integrating that weight.
  • Infinite interval, as in an expectation. Eyeball truncation, ∫0∞≈∫0L\int_0^\infty \approx \int_0^L, adds error absent from all estimates. Better transform: QUADPACK (QAGI routine) uses x=(1−t)/tx = (1 - t)/t, mapping (0,1](0, 1] to [0,∞)[0, \infty), and quad does it automatically if passed np.inf. For a normal distribution Gauss–Hermite is the natural transformation.
[ ]quad under the microscope: singularities, infinities and warningsBrowser
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 1/x1/\sqrt x 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 10−210^{-2} that quad’s estimate (≈5×10−9\approx 5\times 10^{-9}) 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 [0,∞)[0, \infty) returns 0 with estimated error 0, without warning: after transformation, the peak occupies a tiny strip of (0,1](0, 1] between QAGI’s 15 rule nodes and nobody sees it. The oscillatory integral returns −2.9×10−2-2.9\times 10^{-2} instead of 2.5×10−52.5\times 10^{-5}, 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 10−1810^{-18}.

The curse of dimensionality

Everything so far is one-dimensional. The obvious way to integrate on [0,1]d[0, 1]^d is a product rule: take an nn-point rule per axis and all combinations,

Q(f)=∑j1=1n⋯∑jd=1nwj1⋯wjd f(xj1,…,xjd),Q(f) = \sum_{j_1=1}^n \cdots \sum_{j_d=1}^n w_{j_1}\cdots w_{j_d}\,f(x_{j_1}, \dots, x_{j_d}),

using N=ndN = n^d evaluations. If the 1D rule has error O(n−r)\bigO(n^{-r}) for integrands with bounded derivatives of order rr, the product rule keeps that error in nn, but in cost terms it is

error=O(n−r)=O(N−r/d).\text{error} = \bigO(n^{-r}) = \bigO\big(N^{-r/d}\big).

This is the curse of dimensionality in quadrature: effective order is divided by dimension. Trapezoid (r=2r = 2) in d=10d = 10 has error O(N−1/5)\bigO(N^{-1/5}): gaining a digit requires multiplying evaluations by 10510^5. Monte Carlo, with error σ/N\sigma/\sqrt N, has rate N−1/2N^{-1/2} in any dimension (its constant σ\sigma may depend on dd). Beyond some dd, it always wins.

InteractiveThe exploding grid
  • Product trapezoid
  • product Gauss
  • Monte Carlo (σ²/ε²)
Integrand gg per axis
5
10
Target error ε (chart)
Grid evaluations N=ndN = n^d100 k
Error, product trapezoid5.1e−3
Error, product Gauss3.6e−3
Typical Monte Carlo error with those NN1.2e−3
For ε=10−3\varepsilon = 10^{-3} in d=5d = 5: trapezoid 1.89 M, Gauss 759 k, Monte Carlo 155 k evaluations. Monte Carlo wins.
Separable integrand f(x)=g(x1)⋯g(xd)f(\vb{x}) = g(x_1)\cdots g(x_d) on [0,1]d[0, 1]^d with ∫g=1\int g = 1: product rule gives exactly QndQ_n^d and error ∣Qnd−1∣\abs{Q_n^d - 1}; Monte Carlo has root mean square error σd/N\sigma_d/\sqrt N with exact σd2=E[g2]d−1\sigma_d^2 = \E[g^2]^d - 1. Left, first two coordinates' grid; right, evaluations required for target error by dimension through d=12d = 12, for product trapezoid (orange), product Gauss (blue) and Monte Carlo (magenta). With cornered gg, raise dd: at which dimension does trapezoid cross Monte Carlo? And Gauss? Switch to analytic: Gauss crossover recedes, but how many grid points with only 3 per axis at d=20d = 20?

The interactive model deliberately favors the grid because integrand is a product, but already shows explosion. The cell computes the same numbers.

[ ]Product rule versus Monte CarloBrowser
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 gg and ε=10−3\varepsilon = 10^{-3}, product trapezoid rises from 13 evaluations in d=1d = 1 to 1.0×1051.0\times 10^5 in d=4d = 4 (Monte Carlo: 1.2×1051.2\times 10^5) and 1.9×1061.9\times 10^6 in d=5d = 5 (Monte Carlo: 1.5×1051.5\times 10^5); product Gauss, also order 2 with a corner, crosses at d=5d = 5 (7.6×1057.6\times 10^5 versus 1.5×1051.5\times 10^5). At d=10d = 10 product rules need over 101210^{12} evaluations and Monte Carlo 3.3×1053.3\times 10^5. With analytic gg, product Gauss holds much longer (5.9×1045.9\times 10^4 evaluations in d=10d = 10, versus 1.2×1061.2\times 10^6 for Monte Carlo) because 3 points per axis suffice, but even infinite smoothness does not escape: with n≥2n \ge 2 points per axis the grid has at least 2d2^d points, over 10910^9 at d=30d = 30, and at d=100d = 100 fits no computer.

In practice, the reasonable frontier for product rules is around d=4d = 4 to 66, 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 n(log⁡n)d−1n(\log n)^{d-1} rather than ndn^d, at the cost of bounded mixed derivatives; they work through several dozen dimensions. And Monte Carlo, in lesson 18, whose rate is independent of dd and which, with low-discrepancy sequences (quasi-Monte Carlo), improves to nearly N−1N^{-1} for sufficiently regular integrands.

In the libraries

FunctionWhat it doesWhen
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 weightsdefault for ff evaluable anywhere
scipy.integrate.quad_vec(f, a, b)adaptive for vector-output ff: one subdivision tree for all componentsintegrate many functions sharing difficult regions
scipy.integrate.trapezoid(y, x), np.trapezoid(y, x)trapezoid on sampled datameasured data; periodic integrands over one period
scipy.integrate.simpson(y, x=x)Simpson on sampled datasmooth equally spaced data
scipy.integrate.romb(y, dx)Romberg on 2k+12^k + 1 equally spaced samplessmooth data with 2k+12^k + 1 points
np.polynomial.legendre.leggauss(n), hermite.hermgauss(n), hermite_e.hermegauss(n), laguerre.laggauss(n)Gaussian nodes and weightsrepeated integrals with same weight, in loops or vectorized
scipy.integrate.nquad, dblquad, tplquadnested quadd≤3d \le 3 with reasonable integrands
[ ]The same integrals with the libraryBrowser
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

NumericThe leading term
Estimate, using the leading Euler–Maclaurin term, error Th−IT_h - I of composite trapezoid with m=10m = 10 subintervals for ∫01ex ⁣dx\int_0^1 e^x\dd x.
NumericTwo nodes for a fourth moment
You compute E[X4]\E[X^4] with X∼N(0,4)X \sim \Normal(0, 4) using Gauss–Hermite with n=2n = 2 nodes after the correct substitution. What value does the rule return?
NumericThe cost of a digit in dimension 6
A product trapezoid rule in d=6d = 6 has error proportional to N−2/dN^{-2/d}, with NN total evaluations. By what factor must NN be multiplied to divide error by 10?
QuizA suspiciously good trapezoid
With only 16 points, trapezoid computes ∫02πecos⁡θ ⁣dθ\int_0^{2\pi} e^{\cos\theta}\dd\theta with rounding-order error. Why?
QuizA square root in the denominator
You must compute many integrals ∫01g(x)/x ⁣dx\int_0^1 g(x)/\sqrt x\dd x with smooth gg. What does quad without options do, and what is advisable?
QuizMore points, worse rule
Why is the 11-point closed equally spaced Newton–Cotes rule not used instead of composite Simpson?
QuizGauss versus Clenshaw–Curtis
With n+1n + 1 points, Gauss–Legendre has degree 2n+12n + 1 and Clenshaw–Curtis degree nn. What is observed in practice?
QuizAn adaptive method that cannot see
Adaptive Simpson at tolerance 10−210^{-2} ends with estimated error 9.8×10−39.8\times 10^{-3} and actual error 0.330.33 on the integrand with a narrow peak at x=0.8x = 0.8. What happened?
ProofGauss integrates exactly through degree 2n − 1
Prove: Let GnG_n be the interpolatory rule whose nodes are the nn zeros of monic orthogonal polynomial pnp_n for weight w>0w > 0. Then Gn(q)=I(q)G_n(q) = I(q) for every polynomial qq of degree ≤2n−1\le 2n - 1, and Gn(pn2)≠I(pn2)G_n(p_n^2) \ne I(p_n^2).
0
Take polynomial qq of degree at most 2n−12n - 1 and let ω=pn=∏j(x−xj)\omega = p_n = \prod_j (x - x_j).

Step 1 of 5. What is the first step?

CodeRomberg with stopping
Implement romberg(f, a, b, tol=1e-10, max_niveles=20), building the Romberg table row by row and stopping once ∣Rk,k−Rk−1,k−1∣≤\abs{R_{k,k} - R_{k-1,k-1}} \le tol (with k≥1k \ge 1). Return (valor, R, evals): value Rk,kR_{k,k}, 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 kk costs 2k+12^k + 1 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], evals
Shift+Enter to run

Summary

Key idea
A quadrature rule is only as good as what it knows about the integrand: method order holds only if ff has required derivatives; Gauss doubles degree by choosing nodes as zeros of orthogonal polynomials; trapezoid is exponential on periodic functions; adaptation places points where ff is difficult; and no grid survives high dimension.
  • Composite trapezoid and Simpson have errors (b−a)h212f′′(ξ)\frac{(b-a)h^2}{12}f''(\xi) and (b−a)h4180f(4)(ξ)\frac{(b-a)h^4}{180}f^{(4)}(\xi). Euler–Maclaurin gives trapezoid’s full expansion in even powers of hh, with coefficients depending only on endpoint derivatives.
  • Richardson combines ThT_h and Th/2T_{h/2} to cancel h2h^2 (obtaining Simpson); Romberg repeats in cascade while reusing evaluations. It works only if the error expansion exists.
  • The nn-point Gaussian rule has degree 2n−12n - 1, the maximum, positive weights and converges for every continuous ff with error ≤2μ0E2n−1(f)\le 2\mu_0 E_{2n-1}(f). Nodes and weights are eigenvalues and first eigenvector components of the Jacobi matrix (Golub–Welsch). Gauss–Hermite with x=μ+2σtx = \mu + \sqrt2\sigma t 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 NN points over a period only incurs aliasing error 2π∑j≠0cjN2\pi\sum_{j\ne0}c_{jN}, falling as e−aNe^{-aN} if ff is analytic in a strip of width aa.
  • 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 N=ndN = n^d points has error O(N−r/d)\bigO(N^{-r/d}); Monte Carlo, O(N−1/2)\bigO(N^{-1/2}) in any dimension. Beyond d≈4d \approx 4 to 66, 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.