Approximate Integration
Most definite integrals met in practice have no elementary antiderivative, or come from measured data with no formula at all. Then we approximate. This lesson develops the midpoint, trapezoid and Simpson rules, states their error bounds and explains where the bounds come from, checks them numerically, and shows how the same ideas run inside SciPy, physics engines and renderers. The survey lesson is Numerical Integration.
Three rules
Split into subintervals of width , with points and midpoints .
The trapezoid rule replaces on each piece by its chord, which is the average of the left and right Riemann sums. Simpson's rule fits a parabola through each consecutive triple of points and integrates it exactly; the weights 1, 4, 1 (times ) are the exact integral of that parabola over the pair of subintervals.
Error bounds
Let .
Error bounds. If on , then
and .
If on , then
.
Where they come from (sketch). On one subinterval of width , Taylor expansion around the midpoint shows that the chord misses the true area by and the midpoint rectangle by , for some points in the subinterval. Summing such errors, each at most , gives . Two consequences:
- The leading errors of and have opposite signs and . So for concave-up , .
- Cancelling them gives , which is exactly Simpson's rule . Its error comes from the next Taylor term, the fourth derivative, and falls like .
Doubling divides the trapezoid and midpoint errors by about 4 and Simpson's error by about 16.
Checking the bounds numerically
Take . Here , so on , and , so .
import numpy as np
f = np.log
a, b = 1.0, 3.0
exact = 3 * np.log(3) - 2
K, K4 = 1.0, 6.0
def rules(n):
x = np.linspace(a, b, n + 1); h = (b - a) / n
M = h * float(np.sum(f((x[:-1] + x[1:]) / 2)))
T = h * float(np.sum(f(x)) - (f(a) + f(b)) / 2)
S = h / 3 * float(f(a) + f(b) + 4 * np.sum(f(x[1:-1:2])) + 2 * np.sum(f(x[2:-1:2])))
return M, T, S
print(" n E_M bound_M E_T bound_T E_S bound_S")
for n in (4, 8, 16, 32):
M, T, S = rules(n)
bM = K * (b - a)**3 / (24 * n**2); bT = 2 * bM; bS = K4 * (b - a)**5 / (180 * n**4)
print(f"{n:2} {exact - M:+.2e} {bM:.2e} {exact - T:+.2e} {bT:.2e} {exact - S:+.2e} {bS:.2e}") n E_M bound_M E_T bound_T E_S bound_S
4 -6.81e-03 2.08e-02 +1.37e-02 4.17e-02 +5.15e-04 4.17e-03
8 -1.73e-03 5.21e-03 +3.46e-03 1.04e-02 +3.85e-05 2.60e-04
16 -4.33e-04 1.30e-03 +8.67e-04 2.60e-03 +2.55e-06 1.63e-05
32 -1.08e-04 3.26e-04 +2.17e-04 6.51e-04 +1.62e-07 1.02e-06
Every actual error is inside its bound. The bounds are pessimistic here (by a factor of about 3 for and ) because reaches only at the left end. Notice also the sign pattern: is concave down, so the trapezoid underestimates () and the midpoint overestimates.
How large must n be?
To guarantee 6 decimal places (), solve each bound for :
import math
a, b, K, K4, tol = 1.0, 3.0, 1.0, 6.0, 5e-7
n_T = math.ceil(math.sqrt(K * (b - a)**3 / (12 * tol)))
n_M = math.ceil(math.sqrt(K * (b - a)**3 / (24 * tol)))
n_S = math.ceil((K4 * (b - a)**5 / (180 * tol)) ** 0.25)
n_S += n_S % 2 # Simpson needs an even n
print(f"trapezoid needs n >= {n_T}")
print(f"midpoint needs n >= {n_M}")
print(f"Simpson needs n >= {n_S}")trapezoid needs n >= 1155
midpoint needs n >= 817
Simpson needs n >= 40
Simpson needs about 30 times fewer function evaluations than the trapezoid rule for this accuracy. For smooth integrands, higher-order rules win dramatically.
The convergence rates on a log-log plot
import numpy as np
import matplotlib.pyplot as plt
f, a, b = np.log, 1.0, 3.0
exact = 3 * np.log(3) - 2
ns = 2 ** np.arange(1, 11)
errs = {"midpoint": [], "trapezoid": [], "Simpson": []}
for n in ns:
x = np.linspace(a, b, n + 1); h = (b - a) / n
errs["midpoint"].append(abs(exact - h * np.sum(f((x[:-1] + x[1:]) / 2))))
errs["trapezoid"].append(abs(exact - h * (np.sum(f(x)) - (f(a) + f(b)) / 2)))
errs["Simpson"].append(abs(exact - h / 3 * (f(a) + f(b) + 4 * np.sum(f(x[1:-1:2])) + 2 * np.sum(f(x[2:-1:2])))))
plt.figure(figsize=(6, 4))
for name, e in errs.items():
plt.loglog(ns, e, "o-", label=name)
slope = np.polyfit(np.log(ns[2:7]), np.log(e[2:7]), 1)[0]
print(f"{name:9}: fitted slope {slope:.2f}")
plt.xlabel("n"); plt.ylabel("|error|"); plt.legend(); plt.grid(alpha=0.3, which="both")midpoint : fitted slope -2.00
trapezoid: fitted slope -2.00
Simpson : fitted slope -3.97
The slopes −2, −2, −4 are the exponents of in the error bounds. (At very large , Simpson's error stalls near , where rounding error takes over.)
Beyond Simpson
- Adaptive quadrature. SciPy's
quad(QUADPACK) uses Gauss–Kronrod rules, which choose both the points and the weights to integrate polynomials of the highest possible degree, and it subdivides only where the error estimate is large. It reports that estimate as its second return value. - Romberg / Richardson extrapolation. Because , combining and as cancels the term (it equals ); repeating the trick gives ever higher orders.
- Monte Carlo. In many dimensions grid rules need points; random sampling's error does not depend on (Average Value).
In software
- Physics engines. Buoyancy integrates water pressure over a hull's submerged surface, impulses integrate a contact force over a short time, and soft-body and FEM codes integrate stresses over each element. All use fixed quadrature rules (often Gauss points), because their cost is predictable each frame.
- Rendering. A pixel's colour is an integral of light over the pixel area, the lens and incoming directions. Real-time renderers use fixed sample patterns (a quadrature rule); path tracers use Monte Carlo with stratified or low-discrepancy samples to push the error below .
- Data integration. Sensor logs, audio and finance data come as samples;
scipy.integrate.trapezoidandsimpsonintegrate them directly. The error bounds explain why smoother data or finer sampling help, and by how much.
Exercises
Exercise 1: By hand
Approximate with , and . Compare with the exact value 4.
Answer
, , (exact).
Solution
Simpson is exact for cubics: their fourth derivative is 0, so in the bound. Note also with , : .
Exercise 2: Choose n
How large must be for the trapezoid rule to approximate with error below ?
Answer
(using ).
Solution
is increasing on , so . Solve : , so . The computer confirms the arithmetic:
import math
K = 6 * math.e
n = math.ceil(math.sqrt(K / (12 * 1e-4)))
print("n >=", n)n >= 117
Exercise 3: Data
A car's speed (m/s) is recorded every 2 s: 0, 6, 11, 15, 17, 18, 18. Estimate the distance with Simpson's rule.
Answer
About 153.3 m.
Solution
, : .
from scipy.integrate import simpson
print(round(float(simpson([0, 6, 11, 15, 17, 18, 18], dx=2)), 2))153.33
Exercise 4: Midpoint versus trapezoid
For a concave-up function, which of , overestimates the integral?
Answer
overestimates, underestimates.
Solution
A concave-up graph lies below its chords (so trapezoids are too big) and above its tangent lines; the midpoint rectangle has the same area as the trapezoid under the tangent at the midpoint, so it is too small.
Test yourself
Doubling divides the Simpson error by roughly…
- 2
- 4
- 8
- 16
Which derivative controls the trapezoid rule's error bound?
How is Simpson's rule related to the midpoint and trapezoid rules?
- They are unrelated