Numerical integration

Intermediate

Introduction

Most integrals that matter in practice have no neat antiderivative. The area under the bell curve, the length of an ellipse and the energy of a signal are all computed by numbers instead of formulas. The Riemann sums of the last lesson work but need many strips. This lesson shows two better rules, the trapezoid rule and Simpson's rule, and a way to decide how many strips are enough.

How it works

Trapezoid rule. Instead of a flat-topped rectangle, join the curve's heights at the two ends of each strip with a straight line. The strip becomes a trapezoid with area (left height + right height) ÷ 2 × width. Add them all: the two end heights count half, and each middle height counts fully:

(f₀ ÷ 2 + f₁ + f₂ + … + fₙ₋₁ + fₙ ÷ 2) × width

Its error falls about four times when n doubles (second order). That is the same speed as the midpoint rule, and it needs only values at the grid points.

Simpson's rule. Take the strips two at a time and fit a parabola through three heights. The result weights the heights 1, 4, 2, 4, 2, …, 4, 1 and multiplies the total by width ÷ 3. The number of strips n must be even. Its error falls about sixteen times when n doubles (fourth order), and it gives the exact answer for every polynomial up to degree 3.

The example integrates x⁴ from 0 to 1, whose exact value is 0.2. With 16 strips the left rule is still off by about 0.03, the trapezoid by about 0.0013 and Simpson's rule by only about 0.000002. The printed error ratio for the trapezoid rule, close to 4, shows the second-order behaviour.

Choosing n. If the exact answer is unknown, compute the result with n and 2n strips. When the two differ by less than your tolerance, you can stop. A standard loop starts at a small n, doubles it, and compares each result with the previous one. The last line of the example uses 100 midpoint strips for the integral of sin from 0 to π, which is exactly 2, and gets it to six decimals.

Smooth functions suit these rules. A function with a sharp corner or a jump needs the strips split at that point, or the error falls much more slowly.

Example

from math import sin, pi

def f(x):
    return x ** 4

def left(n):
    w = 1 / n
    return sum(f(i * w) for i in range(n)) * w

def trapezoid(n):
    w = 1 / n
    return (f(0) / 2 + sum(f(i * w) for i in range(1, n)) + f(1) / 2) * w

def simpson(n):
    w = 1 / n
    total = f(0) + f(1)
    for i in range(1, n):
        total += (4 if i % 2 == 1 else 2) * f(i * w)
    return total * w / 3

print("area under x**4 from 0 to 1 (exact 0.2)")
for n in [2, 4, 8, 16]:
    print("n =", n, " left:", round(left(n), 6), " trapezoid:", round(trapezoid(n), 6), " simpson:", round(simpson(n), 6))

print("trapezoid error at n = 8 and n = 16:", round(trapezoid(8) - 0.2, 6), round(trapezoid(16) - 0.2, 6))
print("error ratio:", round((trapezoid(8) - 0.2) / (trapezoid(16) - 0.2), 2))

w = pi / 100
# Rounded to 12 places, so the last digit of sin (which can differ between computers) does not show.
total = round(sum(round(sin(w * (i + 0.5)), 12) for i in range(100)) * w, 12)
print("midpoint, 100 strips, integral of sin from 0 to pi (exact 2):", round(total, 6))
Open in compiler

Line by line

  1. left, trapezoid and simpson build the three sums for the same function x⁴ on [0, 1].
  2. trapezoid adds half of each end value and the full middle values. simpson alternates the weights 4 and 2.
  3. The first loop prints the three estimates for 2, 4, 8 and 16 strips; the exact value is 0.2.
  4. The trapezoid errors at n = 8 and n = 16 and their ratio come next; the ratio is about 4.
  5. The last lines integrate sin from 0 to π with the midpoint rule.

Expected result

area under x**4 from 0 to 1 (exact 0.2)
n = 2  left: 0.03125  trapezoid: 0.28125  simpson: 0.208333
n = 4  left: 0.095703  trapezoid: 0.220703  simpson: 0.200521
n = 8  left: 0.1427  trapezoid: 0.2052  simpson: 0.200033
n = 16  left: 0.170052  trapezoid: 0.201302  simpson: 0.200002
trapezoid error at n = 8 and n = 16: 0.0052 0.001302
error ratio: 4.0
midpoint, 100 strips, integral of sin from 0 to pi (exact 2): 2.000082

In the real world

Simulation software integrates equations of motion step by step with rules from this family. Statistics packages integrate probability densities that have no formula. Audio and signal tools integrate energy over time, and engineers integrate sensor readings to get distance from speed. Libraries such as SciPy use the same ideas with automatic step choice.

Common mistakes

  • Using Simpson's rule with an odd number of strips. It needs an even n.
  • Weighting the ends of the trapezoid rule fully. The two end values count half.
  • Trusting one result. Without a second result at a different n there is no error estimate.
  • Using these rules across a jump or a sharp corner without splitting the interval.

Best practices

  • Start with the trapezoid or Simpson rule rather than the left-edge rule.
  • Double n until two answers agree to the accuracy you need.
  • Test the code on a function with a known integral, such as x² or sin.
  • Cap the number of strips so a bad function cannot make the loop run forever.

Summary

The trapezoid rule averages the end heights of each strip and has second-order error. Simpson's rule fits parabolas, has fourth-order error and is exact for cubics. Comparing results for n and 2n estimates the error, and doubling n until it is small enough is a simple and reliable method.

Quick check

1. How much does the trapezoid error fall when the number of strips doubles?
2. Simpson's rule needs the number of strips to be…
3. Simpson's rule gives the exact answer for…
4. In the trapezoid rule the two end heights are counted…
5. How can you estimate the error without knowing the exact answer?

Key takeaways

  • The trapezoid rule is second order: doubling n cuts the error about four times.
  • Simpson's rule is fourth order: doubling n cuts the error about sixteen times, and it is exact for cubics.
  • Comparing results for n and 2n gives a free error estimate.
  • Double n until the answer stops changing by more than the tolerance.

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.