TExcelTAD
Home › Numerical Methods › Adaptive Integration

Adaptive Integration

Real integrands are rarely uniformly smooth: they have peaks, kinks, near-singularities and long flat stretches. A fixed grid wastes evaluations where ff is easy and starves the hard regions. Adaptive quadrature estimates the error on each subinterval and subdivides only where needed, until a requested tolerance is met. It is what scipy.integrate.quad does.

Error estimates from two rules

Apply two rules of different accuracy to the same interval; their difference estimates the error of the less accurate one. For Simpson's rule, comparing SS on [a,b][a, b] with S2S_2 (Simpson on the two halves) gives

I−S2≈S2−S15,I - S_2 \approx \frac{S_2 - S}{15},

because Simpson's error scales by 116\frac{1}{16} when hh halves.

Recursive adaptive Simpson

If the estimate is below the tolerance, accept the interval (with the correction term added); otherwise split it and give each half half of the tolerance.

python · try it yourself
import numpy as np

def adaptive_simpson(f, a, b, tol, counter):
    def simpson(a, fa, m, fm, b, fb):
        return (b - a) / 6 * (fa + 4 * fm + fb)

    def recurse(a, fa, m, fm, b, fb, whole, tol, depth):
        lm, rm = (a + m) / 2, (m + b) / 2
        flm, frm = f(lm), f(rm); counter[0] += 2
        left = simpson(a, fa, lm, flm, m, fm)
        right = simpson(m, fm, rm, frm, b, fb)
        if depth > 50 or abs(left + right - whole) <= 15 * tol:
            counter[1].append((a, b))
            return left + right + (left + right - whole) / 15
        return (recurse(a, fa, lm, flm, m, fm, left, tol / 2, depth + 1)
                + recurse(m, fm, rm, frm, b, fb, right, tol / 2, depth + 1))

    m = (a + b) / 2
    fa, fm, fb = f(a), f(m), f(b); counter[0] += 3
    return recurse(a, fa, m, fm, b, fb, simpson(a, fa, m, fm, b, fb), tol, 0)

c = 1e-6
f = lambda x: 1 / (c + (x - 0.3) ** 2)              # very sharp peak at 0.3 (width 0.001)
exact = (np.arctan(0.7 / np.sqrt(c)) + np.arctan(0.3 / np.sqrt(c))) / np.sqrt(c)
counter = [0, []]
val = adaptive_simpson(f, 0, 1, 1e-6, counter)
widths = np.array([b - a for a, b in counter[1]])
print(f"adaptive: error {abs(val - exact):.1e} with {counter[0]} evaluations")
print(f"smallest interval {widths.min():.1e}, largest {widths.max():.1e}")
n = counter[0] - 1 - (counter[0] - 1) % 2          # even number of intervals, same budget
x = np.linspace(0, 1, n + 1)
uni = (x[1] - x[0]) / 3 * (f(x[0]) + f(x[-1]) + 4 * f(x[1:-1:2]).sum() + 2 * f(x[2:-1:2]).sum())
print(f"uniform Simpson with the same budget: error {abs(uni - exact):.1e}")
adaptive: error 1.7e-09 with 5009 evaluations
smallest interval 3.8e-06, largest 6.2e-02
uniform Simpson with the same budget: error 9.5e-05

The adaptive method puts tiny intervals near the peak and wide ones elsewhere, and is far more accurate for the same number of evaluations.

Gauss-Kronrod rules

Production codes use Gauss-Kronrod pairs: a G7G_7 Gauss rule embedded in a 15-point Kronrod rule K15K_{15} that reuses the 7 Gauss nodes. The pair costs 15 evaluations and gives a high-order result (K15K_{15}) plus an error estimate (∣K15−G7∣\lvert K_{15} - G_7\rvert, made more conservative by heuristics). QUADPACK's qags, behind scipy.integrate.quad, uses a 21-point Gauss-Kronrod rule globally adaptive: it always splits the subinterval with the largest estimated error, and it extrapolates to handle endpoint singularities.

python · try it yourself
import numpy as np
from scipy.integrate import quad

tests = {
    "peak": (lambda x: 1 / (1e-3 + (x - 0.3) ** 2), 0, 1),
    "log singularity": (lambda x: np.log(x), 0, 1),
    "1/sqrt(x)": (lambda x: 1 / np.sqrt(x), 0, 1),
    "infinite range": (lambda x: np.exp(-x) * np.cos(x), 0, np.inf),
}
exacts = [(np.arctan(0.7 / np.sqrt(1e-3)) + np.arctan(0.3 / np.sqrt(1e-3))) / np.sqrt(1e-3), -1.0, 2.0, 0.5]
for (name, (f, a, b)), ex in zip(tests.items(), exacts):
    val, est, info = quad(f, a, b, full_output=True)[:3]
    print(f"{name:16s}: value {val: .12f}, estimated error {est:.1e}, true error {abs(val - ex):.1e}, evaluations {info['neval']}")
peak            : value  94.597212547208, estimated error 8.1e-07, true error 1.7e-13, evaluations 189
log singularity : value -1.000000000000, estimated error 1.1e-15, true error 1.1e-16, evaluations 231
1/sqrt(x)       : value  2.000000000000, estimated error 5.8e-15, true error 1.6e-15, evaluations 231
infinite range  : value  0.500000000000, estimated error 3.1e-09, true error 0.0e+00, evaluations 195

Helping the integrator

  • Tell it where the trouble is: quad(f, a, b, points=[0.3]) splits at known kinks or peaks.
  • Remove singularities analytically (subtract the singular part or substitute x=t2x = t^2).
  • Use a weight: quad(f, a, b, weight="cos", wvar=w) for oscillatory integrals, weight="alg" for algebraic endpoint singularities.
  • Discontinuous integrands should be split at the discontinuity; the error estimate may otherwise be optimistic.

In software

  • scipy.integrate.quad (1D), dblquad/tplquad/nquad (iterated), quad_vec (vector-valued). For high dimensions, quadrature becomes impractical and Monte Carlo methods take over.
  • Excel has no integration function; numerical integration there is done with trapezoid sums over a column of values.

Exercises

Exercise 1: Error estimate

On an interval, Simpson gives S=0.7854S = 0.7854 and the two-half version S2=0.7849S_2 = 0.7849. Estimate the error of S2S_2 and give the corrected value.

Answer

Error about −3.3×10−5-3.3 \times 10^{-5}; corrected 0.7848670.784867.

Solution

S2−S15=−0.000515≈−3.33×10−5\frac{S_2 - S}{15} = \frac{-0.0005}{15} \approx -3.33 \times 10^{-5}, so I≈0.7849−0.0000333=0.7848667I \approx 0.7849 - 0.0000333 = 0.7848667.

Exercise 2: Why split the tolerance?

Why does each half get tolerance τ2\frac{\tau}{2}?

Answer

So that the accepted errors add up to at most τ\tau.

Solution

The total error is the sum of the errors on the accepted subintervals; halving at each split keeps their sum within the overall tolerance (a conservative strategy).

Exercise 3: Kinks (code)

Integrate ∣x−13∣\lvert x - \frac{1}{3}\rvert on [0,1][0, 1] with quad, with and without points=[1/3], and compare evaluations and errors. Exact value: 518\frac{5}{18}.

Answer

Both are accurate to rounding level, but with the breakpoint quad needs only 42 evaluations (one 21-point rule on each side) instead of 189.

Solution
python · try it yourself
from scipy.integrate import quad
f = lambda x: abs(x - 1 / 3)
for kw in ({}, {"points": [1 / 3]}):
    val, err, info = quad(f, 0, 1, full_output=True, **kw)[:3]

    print(kw, f"error {abs(val - 5 / 18):.1e}, evaluations {info['neval']}")
{} error 5.6e-17, evaluations 189
{'points': [0.3333333333333333]} error 5.6e-17, evaluations 42

Test yourself

Adaptive quadrature refines…

  1. all intervals equally
  2. only the intervals where the estimated error is too large
  3. only the endpoints
  4. nothing

A Gauss-Kronrod pair is useful because…

  1. it needs no function values
  2. the Kronrod rule reuses the Gauss nodes, giving an error estimate cheaply
  3. it is exact for all functions
  4. it works only on infinite intervals

If you know the integrand has a kink at x=cx = c, you should…

  1. ignore it
  2. pass it as a breakpoint, e.g. points=[c]
  3. use the trapezoid rule
  4. increase the tolerance