TExcelTAD
Home › Calculus in Depth › Approximate Integration

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 [a,b][a, b] into nn subintervals of width h=Δx=b−anh = \Delta x = \frac{b - a}{n}, with points xi=a+ihx_i = a + ih and midpoints xˉi\bar{x}_i.

MidpointMn=h [f(xˉ1)+f(xˉ2)+⋯+f(xˉn)]TrapezoidTn=h2 [f(x0)+2f(x1)+2f(x2)+⋯+2f(xn−1)+f(xn)]SimpsonSn=h3 [f(x0)+4f(x1)+2f(x2)+4f(x3)+⋯+4f(xn−1)+f(xn)](n even)\begin{aligned} &\text{Midpoint} && M_n = h\,[f(\bar{x}_1) + f(\bar{x}_2) + \cdots + f(\bar{x}_n)] \\ &\text{Trapezoid} && T_n = \frac{h}{2}\,[f(x_0) + 2f(x_1) + 2f(x_2) + \cdots + 2f(x_{n-1}) + f(x_n)] \\ &\text{Simpson} && S_n = \frac{h}{3}\,[f(x_0) + 4f(x_1) + 2f(x_2) + 4f(x_3) + \cdots + 4f(x_{n-1}) + f(x_n)] && (n \text{ even}) \end{aligned}

The trapezoid rule replaces ff 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 h/3h/3) are the exact integral of that parabola over the pair of subintervals.

Error bounds

Let E=∫abf(x) dx−(approximation)E = \int_a^b f(x)\,dx - (\text{approximation}).

Error bounds. If ∣f′′(x)∣≤K\lvert f''(x) \rvert \le K on [a,b][a, b], then

∣ET∣≤K(b−a)312n2\lvert E_T \rvert \le \frac{K(b-a)^3}{12n^2} and ∣EM∣≤K(b−a)324n2\lvert E_M \rvert \le \frac{K(b-a)^3}{24n^2}.

If ∣f(4)(x)∣≤K4\lvert f^{(4)}(x) \rvert \le K_4 on [a,b][a, b], then

∣ES∣≤K4(b−a)5180n4\lvert E_S \rvert \le \frac{K_4(b-a)^5}{180n^4}.

Where they come from (sketch). On one subinterval of width hh, Taylor expansion around the midpoint shows that the chord misses the true area by −h3f′′(ξ)12-\frac{h^3 f''(\xi)}{12} and the midpoint rectangle by +h3f′′(η)24+\frac{h^3 f''(\eta)}{24}, for some points ξ,η\xi, \eta in the subinterval. Summing nn such errors, each at most Kh312\frac{Kh^3}{12}, gives nKh312=K(b−a)h212=K(b−a)312n2\frac{nKh^3}{12} = \frac{K(b - a)h^2}{12} = \frac{K(b - a)^3}{12n^2}. Two consequences:

  • The leading errors of MM and TT have opposite signs and ET≈−2EME_T \approx -2E_M. So for concave-up ff, Mn<∫<TnM_n < \int < T_n.
  • Cancelling them gives 2Mn+Tn3\frac{2M_n + T_n}{3}, which is exactly Simpson's rule S2nS_{2n}. Its error comes from the next Taylor term, the fourth derivative, and falls like 1/n41/n^4.

Doubling nn divides the trapezoid and midpoint errors by about 4 and Simpson's error by about 16.

Checking the bounds numerically

Take ∫13ln⁡x dx=[xln⁡x−x]13=3ln⁡3−2\int_1^3 \ln x\,dx = \Big[x \ln x - x\Big]_1^3 = 3 \ln 3 - 2. Here f′′(x)=−1/x2f''(x) = -1/x^2, so K=1K = 1 on [1,3][1, 3], and f(4)(x)=−6/x4f^{(4)}(x) = -6/x^4, so K4=6K_4 = 6.

python · try it yourself
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 MM and TT) because ∣f′′∣=1/x2\lvert f'' \rvert = 1/x^2 reaches K=1K = 1 only at the left end. Notice also the sign pattern: ln⁡x\ln x is concave down, so the trapezoid underestimates (ET>0E_T > 0) and the midpoint overestimates.

How large must n be?

To guarantee 6 decimal places (∣E∣<5⋅10−7\lvert E \rvert < 5 \cdot 10^{-7}), solve each bound for nn:

python · try it yourself
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

python · try it yourself
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 nn in the error bounds. (At very large nn, Simpson's error stalls near 10−1510^{-15}, 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 ET≈C/n2E_T \approx C/n^2, combining TnT_n and T2nT_{2n} as 4T2n−Tn3\frac{4T_{2n} - T_n}{3} cancels the C/n2C/n^2 term (it equals S2nS_{2n}); repeating the trick gives ever higher orders.
  • Monte Carlo. In many dimensions grid rules need ndn^d points; random sampling's 1/N1/\sqrt{N} error does not depend on dd (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 1/N1/\sqrt{N}.
  • Data integration. Sensor logs, audio and finance data come as samples; scipy.integrate.trapezoid and simpson integrate them directly. The error bounds explain why smoother data or finer sampling help, and by how much.

Exercises

Exercise 1: By hand

Approximate ∫02x3 dx\int_0^2 x^3\,dx with T2T_2, M2M_2 and S2S_2. Compare with the exact value 4.

Answer

T2=5T_2 = 5, M2=3.5M_2 = 3.5, S2=4S_2 = 4 (exact).

Solution
h=1:T2=12[0+2⋅1+8]=5M2=1⋅[0.53+1.53]=0.125+3.375=3.5h=1:S2=13[0+4⋅1+8]=4\begin{aligned} h = 1: \quad & T_2 = \frac{1}{2}[0 + 2 \cdot 1 + 8] = 5 \\ & M_2 = 1 \cdot [0.5^3 + 1.5^3] = 0.125 + 3.375 = 3.5 \\ h = 1: \quad & S_2 = \frac{1}{3}[0 + 4 \cdot 1 + 8] = 4 \end{aligned}

Simpson is exact for cubics: their fourth derivative is 0, so K4=0K_4 = 0 in the bound. Note also S2=2M1+T13S_2 = \frac{2M_1 + T_1}{3} with M1=2⋅1=2M_1 = 2 \cdot 1 = 2, T1=1⋅(0+8)=8T_1 = 1 \cdot (0 + 8) = 8: 4+83=4\frac{4 + 8}{3} = 4.

Exercise 2: Choose n

How large must nn be for the trapezoid rule to approximate ∫01ex2 dx\int_0^1 e^{x^2}\,dx with error below 10−410^{-4}?

Answer

n≥117n \ge 117 (using K=6eK = 6e).

Solution

f′′(x)=(2+4x2)ex2f''(x) = (2 + 4x^2)e^{x^2} is increasing on [0,1][0, 1], so K=f′′(1)=6e≈16.31K = f''(1) = 6e \approx 16.31. Solve 6e12n2<10−4\frac{6e}{12n^2} < 10^{-4}: n2>e2⋅104≈13 591n^2 > \frac{e}{2} \cdot 10^4 \approx 13\,591, so n≥117n \ge 117. The computer confirms the arithmetic:

python · try it yourself
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

n=6n = 6, h=2h = 2: 23[0+4⋅6+2⋅11+4⋅15+2⋅17+4⋅18+18]=23(230)≈153.33\frac{2}{3}[0 + 4 \cdot 6 + 2 \cdot 11 + 4 \cdot 15 + 2 \cdot 17 + 4 \cdot 18 + 18] = \frac{2}{3}(230) \approx 153.33.

python · try it yourself
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 MnM_n, TnT_n overestimates the integral?

Answer

TnT_n overestimates, MnM_n 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 nn divides the Simpson error by roughly…

  1. 2
  2. 4
  3. 8
  4. 16

Which derivative controls the trapezoid rule's error bound?

  1. f′f'
  2. f′′′f'''
  3. f′′f''
  4. f(4)f^{(4)}

How is Simpson's rule related to the midpoint and trapezoid rules?

  1. S2n=2Mn+Tn3S_{2n} = \frac{2M_n + T_n}{3}
  2. S2n=Mn+Tn2S_{2n} = \frac{M_n + T_n}{2}
  3. S2n=Mn⋅TnS_{2n} = M_n \cdot T_n
  4. They are unrelated