TExcelTAD
Home › Numerical Methods › Trapezoid and Simpson Rules

Trapezoid and Simpson Rules

Most integrals have no closed form: ∫01e−x2dx\int_0^1 e^{-x^2}dx, the arc length of an ellipse, the energy of a measured signal. Numerical integration (quadrature) approximates ∫abf(x) dx\int_a^bf(x)\,dx by a weighted sum of function values. The Newton-Cotes rules integrate an interpolating polynomial on equally spaced points, and their composite versions are the everyday tools.

The basic rules

On one interval of width hh:

Rule Formula Error
midpoint hf(a+h2)hf\left(a + \frac{h}{2}\right) h324f′′\frac{h^3}{24}f''
trapezoid h2(f(a)+f(b))\frac{h}{2}\left(f(a) + f(b)\right) −h312f′′-\frac{h^3}{12}f''
Simpson h6(f(a)+4f(a+b2)+f(b))\frac{h}{6}\left(f(a) + 4f\left(\frac{a + b}{2}\right) + f(b)\right) −h52880f(4)-\frac{h^5}{2880}f^{(4)}

Simpson's rule integrates the quadratic through three points and, by symmetry, is exact even for cubics.

Composite rules

Split [a,b][a, b] into nn subintervals of width h=b−anh = \frac{b - a}{n} and apply a rule on each:

Tn=h(f02+f1+⋯+fn−1+fn2),Sn=h3(f0+4f1+2f2+4f3+⋯+4fn−1+fn)T_n = h\left(\frac{f_0}{2} + f_1 + \cdots + f_{n-1} + \frac{f_n}{2}\right), \qquad S_n = \frac{h}{3}\left(f_0 + 4f_1 + 2f_2 + 4f_3 + \cdots + 4f_{n-1} + f_n\right)

(nn even for Simpson). The composite trapezoid error is O(h2)O(h^2) and Simpson's is O(h4)O(h^4).

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

def trap(f, a, b, n):
    x = np.linspace(a, b, n + 1); y = f(x); h = (b - a) / n
    return h * (y.sum() - (y[0] + y[-1]) / 2)

def simp(f, a, b, n):
    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())

f = lambda x: np.exp(-x**2)
exact = 0.7468241328124270                                     # = sqrt(pi)/2 erf(1)
print("   n   trapezoid error   ratio    Simpson error   ratio")
pt = ps = None
for n in (4, 8, 16, 32, 64):
    et, es = abs(trap(f, 0, 1, n) - exact), abs(simp(f, 0, 1, n) - exact)
    rt = f"{pt / et:6.2f}" if pt else "      "
    rs = f"{ps / es:6.2f}" if ps else "      "
    print(f"{n:4d}   {et:.3e}       {rt}   {es:.3e}      {rs}")
    pt, ps = et, es
x = np.linspace(0, 1, 65)
print("scipy.integrate.simpson agrees:", np.isclose(simpson(f(x), x=x), simp(f, 0, 1, 64)))
   n   trapezoid error   ratio    Simpson error   ratio
   4   3.840e-03                3.125e-05
   8   9.585e-04         4.01   1.988e-06       15.72
  16   2.395e-04         4.00   1.246e-07       15.95
  32   5.988e-05         4.00   7.795e-09       15.99
  64   1.497e-05         4.00   4.872e-10       16.00
scipy.integrate.simpson agrees: True

Error ratios of 4 and 16 confirm second and fourth order.

The Euler-Maclaurin formula and periodic functions

The trapezoid error has an expansion in even powers of hh whose coefficients involve derivatives at the endpoints:

Tn−∫abf dx=h212(f′(b)−f′(a))−h4720(f′′′(b)−f′′′(a))+⋯T_n - \int_a^bf\,dx = \frac{h^2}{12}\left(f'(b) - f'(a)\right) - \frac{h^4}{720}\left(f'''(b) - f'''(a)\right) + \cdots

For a smooth periodic function integrated over a full period, every term vanishes and the trapezoid rule converges exponentially fast:

python · try it yourself
import numpy as np

f = lambda x: np.exp(np.cos(x))                    # periodic with period 2 pi
exact = 2 * np.pi * 1.2660658777520082             # 2 pi I_0(1)
for n in (4, 8, 12, 16, 20):
    x = np.linspace(0, 2 * np.pi, n, endpoint=False)
    T = 2 * np.pi / n * f(x).sum()
    print(f"n = {n:2d}: error {abs(T - exact):.1e}")
n =  4: error 3.4e-02
n =  8: error 1.3e-06
n = 12: error 6.5e-12
n = 16: error 0.0e+00
n = 20: error 8.9e-16

Romberg integration

Since Tn=I+c1h2+c2h4+⋯T_n = I + c_1h^2 + c_2h^4 + \cdots, Richardson extrapolation removes one term at a time: 4T2n−Tn3\frac{4T_{2n} - T_n}{3} is exactly Simpson's rule, and further levels give O(h6)O(h^6), O(h8)O(h^8), and so on. This is Romberg integration.

In software

  • np.trapezoid(y, x) and scipy.integrate.simpson(y, x=x) for sampled data (including unequal spacing); cumulative_trapezoid for running integrals.
  • For functions you can evaluate anywhere, adaptive and Gaussian methods are far more efficient (Gaussian Quadrature, Adaptive Integration).

Exercises

Exercise 1: By hand

Approximate ∫02x2 dx\int_0^2 x^2\,dx by the trapezoid rule with n=2n = 2 and by Simpson's rule with n=2n = 2.

Answer

Trapezoid 33, Simpson 83\frac{8}{3} (exact).

Solution

h=1h = 1: T=1(02+1+42)=3T = 1\left(\frac{0}{2} + 1 + \frac{4}{2}\right) = 3; S=13(0+4⋅1+4)=83S = \frac{1}{3}(0 + 4 \cdot 1 + 4) = \frac{8}{3}.

Exercise 2: Choose nn

How many trapezoid subintervals guarantee error below 10−610^{-6} for ∫01ex dx\int_0^1 e^x\,dx, using ∣E∣≤(b−a)h212max⁡∣f′′∣\lvert E\rvert \le \frac{(b - a)h^2}{12}\max\lvert f''\rvert?

Answer

n=476n = 476.

Solution

e12n2≤10−6\frac{e}{12n^2} \le 10^{-6} gives n≥e12×106≈475.9n \ge \sqrt{\frac{e}{12} \times 10^6} \approx 475.9.

Exercise 3: Romberg (code)

Build a Romberg table for ∫01e−x2dx\int_0^1 e^{-x^2}dx starting from T1T_1 with 5 levels and print the diagonal errors.

Answer

The diagonal errors fall rapidly, to about 3×10−103 \times 10^{-10} at the last level, using only 17 function values.

Solution
python · try it yourself
import numpy as np
f = lambda x: np.exp(-x**2); exact = 0.7468241328124270
R = np.zeros((5, 5))
for i in range(5):
    n = 2**i; x = np.linspace(0, 1, n + 1); y = f(x)
    R[i, 0] = (y.sum() - (y[0] + y[-1]) / 2) / n
    for j in range(1, i + 1):
        R[i, j] = R[i, j - 1] + (R[i, j - 1] - R[i - 1, j - 1]) / (4**j - 1)
print([f"{abs(R[i, i] - exact):.1e}" for i in range(5)])
['6.3e-02', '3.6e-04', '9.6e-06', '1.1e-07', '2.8e-10']

Test yourself

The composite trapezoid rule has error…

  1. O(h)O(h)
  2. O(h2)O(h^2)
  3. O(h4)O(h^4)
  4. O(h6)O(h^6)

Simpson's rule is exact for polynomials up to degree…

  1. 1
  2. 2
  3. 3
  4. 4

For a smooth periodic function over a full period, the trapezoid rule converges…

  1. like h2h^2
  2. exponentially fast
  3. not at all
  4. like hh