Adaptive Integration
Real integrands are rarely uniformly smooth: they have peaks, kinks, near-singularities and long flat stretches. A fixed grid wastes evaluations where 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 on with (Simpson on the two halves) gives
because Simpson's error scales by when 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.
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 Gauss rule embedded in a 15-point Kronrod rule that reuses the 7 Gauss nodes. The pair costs 15 evaluations and gives a high-order result () plus an error estimate (, 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.
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 ).
- 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 and the two-half version . Estimate the error of and give the corrected value.
Answer
Error about ; corrected .
Solution
, so .
Exercise 2: Why split the tolerance?
Why does each half get tolerance ?
Answer
So that the accepted errors add up to at most .
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 on with quad, with and without points=[1/3], and compare evaluations and errors. Exact value: .
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
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…
- all intervals equally
- only the intervals where the estimated error is too large
- only the endpoints
- nothing
A Gauss-Kronrod pair is useful because…
- it needs no function values
- the Kronrod rule reuses the Gauss nodes, giving an error estimate cheaply
- it is exact for all functions
- it works only on infinite intervals
If you know the integrand has a kink at , you should…
- ignore it
- pass it as a breakpoint, e.g.
points=[c] - use the trapezoid rule
- increase the tolerance