---
title: Numerical integration and its error
heading: When there's no formula, add up slices, and know how wrong you are
eyebrow: A6 · Lesson 11 · Numerical integration
xp: 40
---

::: hook
The energy in a recorded waveform, the charge from a measured current, the area under $e^{-x^2}$: none of these have a formula you can write down. You integrate them numerically, by adding up slices. The interesting part is the error. A good method doesn't just get closer as the slices get thinner; it gets closer at a predictable rate, which tells you how many slices you need.
:::

::: predict
## The trapezoid rule's error shrinks in proportion to $h^2$, the slice width squared. You halve $h$. What happens to the error?

- [ ] It halves
- [x] It drops to about a quarter
- [ ] It drops to about a sixteenth
- [ ] It stays the same

::: reveal
About a quarter: $(\tfrac12)^2 = \tfrac14$. That's why the trapezoid rule is called second order. Simpson's rule, which fits parabolas instead of straight lines, has error proportional to $h^4$, so halving $h$ cuts its error about sixteen times.
:::
:::

::: nameit
## Three rules, from crude to good

Split $[a, b]$ into $n$ slices of width $h = (b - a)/n$, with points $x_0 = a, x_1, \ldots, x_n = b$.

- **Rectangles** (left-hand sum): $h\sum_{k=0}^{n-1} f(x_k)$. Error proportional to $h$: first order.
- **Trapezoids**, joining neighboring points with straight lines:

$$\int_a^b f\,dx \approx h\left[\tfrac12 f(x_0) + f(x_1) + \cdots + f(x_{n-1}) + \tfrac12 f(x_n)\right]$$

  Error about $-\frac{(b - a)h^2}{12}f''$: second order.

- **Simpson's rule**, with $n$ even, fits a parabola through each pair of slices:

$$\int_a^b f\,dx \approx \frac h3\left[f(x_0) + 4f(x_1) + 2f(x_2) + 4f(x_3) + \cdots + 4f(x_{n-1}) + f(x_n)\right]$$

  Error proportional to $h^4$: fourth order.

**Checking the order.** Compute with $n$ slices and with $2n$. If the method has order $p$, the error should drop by about $2^p$. Measuring that ratio is how numerical code gets tested, and it's how this course's own circuit simulator was checked.

In NumPy, `np.trapezoid(y, x)` applies the trapezoid rule to sampled data, and SciPy's `scipy.integrate.quad` chooses its own slices adaptively to reach a requested accuracy.
:::

::: example
## Estimate $\int_0^1 e^x\,dx$ with the trapezoid rule and four slices.

::: solution
1. **Sample the function.** $h = 0.25$, and $e^x$ at $0, 0.25, 0.5, 0.75, 1$ is $1, 1.284025, 1.648721, 2.117000, 2.718282$.
2. **Apply the trapezoid rule.** The two end values get half weight:
   $$\begin{aligned} T &= 0.25\Big(\tfrac{1}{2} + 1.284025 \\ &\qquad + 1.648721 + 2.117000 \\ &\qquad + \tfrac{2.718282}{2}\Big) \\ &= 1.727222 \end{aligned}$$
3. **Compare with the exact value.** The exact value is $e - 1 = 1.718282$, so the error is 0.0089. The curve bends upward, so the trapezoids overshoot.

**Answer:** the trapezoid rule gives 1.727222, 0.0089 above the exact $e - 1 = 1.718282$.
:::
:::

::: example
## Do the same with Simpson's rule.

::: solution
1. **Weight the points.** Simpson weights the points $1, 4, 2, 4, 1$ and multiplies by $\frac{h}{3}$:
   $$\begin{aligned} S &= \frac{0.25}{3}\Big(1 + 4 \times 1.284025 \\ &\qquad + 2 \times 1.648721 \\ &\qquad + 4 \times 2.117000 \\ &\qquad + 2.718282\Big) \\ &= 1.718319 \end{aligned}$$
2. **Compare.** The error is 0.000037, about 240 times smaller than the trapezoid rule's, from the same five function values.

**Answer:** Simpson's rule gives 1.718319, off by only 0.000037.
:::
:::

::: check
kind: python

## Write `trapezoid(f, a, b, n)`, the trapezoid rule with `n` slices.

```python starter
import math

def trapezoid(f, a, b, n):
    return 0   # replace this

print(trapezoid(math.sin, 0, math.pi, 100))   # should be close to 2
```

```python solution
import math

def trapezoid(f, a, b, n):
    h = (b - a) / n
    total = 0.5 * (f(a) + f(b))
    for k in range(1, n):
        total += f(a + k * h)
    return h * total

print(trapezoid(math.sin, 0, math.pi, 100))
```

```python tests
import math
assert abs(trapezoid(lambda x: 3.0, 0, 2, 4) - 6) < 1e-12, "A constant 3 over a width of 2 has area 6; check the end weights of ½."
assert abs(trapezoid(lambda x: x, 0, 1, 1) - 0.5) < 1e-12, "With one slice, the trapezoid for f(x) = x on [0, 1] is ½."
r = trapezoid(math.sin, 0, math.pi, 100)
assert abs(r - 2) < 2e-4, f"The area under sin from 0 to π is 2; you got {r}."
assert abs(r - 2) > 1e-7, "That's too exact for the trapezoid rule with 100 slices: is it really trapezoids?"
```

::: right
Right. With 100 slices the result is within about 0.0002 of 2, as the error formula predicts.
:::
:::

::: check
kind: python

## Write `simpson(f, a, b, n)` (with `n` even). Then measure its order: set `ratio` to the error with 10 slices divided by the error with 20 slices, for $\int_0^\pi \sin x\,dx = 2$.

```python starter
import math

def simpson(f, a, b, n):
    return 0   # replace this

e10 = abs(simpson(math.sin, 0, math.pi, 10) - 2)
e20 = abs(simpson(math.sin, 0, math.pi, 20) - 2)
ratio = 0
print(e10, e20, ratio)
```

```python solution
import math

def simpson(f, a, b, n):
    h = (b - a) / n
    total = f(a) + f(b)
    for k in range(1, n):
        total += (4 if k % 2 else 2) * f(a + k * h)
    return h / 3 * total

e10 = abs(simpson(math.sin, 0, math.pi, 10) - 2)
e20 = abs(simpson(math.sin, 0, math.pi, 20) - 2)
ratio = e10 / e20
print(e10, e20, ratio)
```

```python tests
import math
assert abs(simpson(lambda x: x**2, 0, 3, 2) - 9) < 1e-12, "Simpson's rule is exact for parabolas: ∫₀³ x² dx = 9 with just 2 slices. Check the weights 1, 4, 2, 4, ..., 4, 1."
assert abs(simpson(math.sin, 0, math.pi, 10) - 2) < 2e-4, "simpson(sin, 0, π, 10) should be within about 0.0001 of 2."
assert abs(ratio - e10 / e20) < 1e-9, "ratio should be e10 / e20."
assert 14 < ratio < 18, f"For a fourth-order method, doubling the slices should cut the error about 16 times; your ratio is {ratio:.2f}."
```

::: right
Right. A ratio near 16: Simpson's rule is fourth order.
:::
:::

::: check
kind: python
given: tau = 1..9 int

## The arrays `t` (ms) and `p` (W) are samples of a decaying power, $p = e^{-2t/\tau}$ with $\tau$ = {tau} ms. Integrate them with the trapezoid rule over the samples to set `E`, the energy in mJ.

```python starter
import numpy as np

t = np.linspace(0, 10 * tau, 401)
p = np.exp(-2 * t / tau)
E = 0   # replace this
print(E, tau / 2)
```

```python solution
import numpy as np

t = np.linspace(0, 10 * tau, 401)
p = np.exp(-2 * t / tau)
h = t[1] - t[0]
E = h * (p.sum() - 0.5 * (p[0] + p[-1]))
print(E, tau / 2)
```

```python tests
import numpy as np
h = t[1] - t[0]
want = h * (p.sum() - 0.5 * (p[0] + p[-1]))
assert abs(E - want) < 1e-9 * tau, "E should be the trapezoid rule applied to the samples: h times (sum minus half the two ends)."
assert abs(E - tau / 2) < 0.01 * tau, "The energy should come out close to τ/2 mJ."
```

::: right
Right. With samples you can only integrate what you measured, so the sample spacing sets the accuracy.
:::
:::

::: check
kind: choice

## A method's error drops by a factor of 4 each time you halve the slice width. What is its order?

- [ ] 1
- [x] 2
- [ ] 4
- [ ] 16

::: right
Right. $2^p = 4$ gives $p = 2$: second order, like the trapezoid rule.
:::

::: misses
- [1] First order would halve the error.
- [3] Fourth order would cut it 16 times.
- [4] The order is the power of h: $2^p = 4$.
:::
:::

::: check
given: b = 2 | 3 | 4
answer: (b/2)*((b/2)^2 + b^2/2)
tolerance: 0.5%

## Estimate $\int_0^{\given{b}} x^2\,dx$ with the trapezoid rule and two slices.

::: right
Right. With $h = \given{b}/2$ the rule gives $h\left(\tfrac12 f(0) + f(h) + \tfrac12 f(\given{b})\right)$ = {answer}, a little above the exact $\given{b}^3/3$, because a curve that bends upward sits below its chords.
:::

::: misses
- [b^3/3] That's the exact integral. The trapezoid rule with two slices overestimates it.
- [(b/2)*((b/2)^2 + b^2)] The end points get half weight: $\tfrac12 f(0) + f(h) + \tfrac12 f(b)$.
- [any] Not yet. Use $h\left(\tfrac12 f(0) + f(h) + \tfrac12 f(b)\right)$ with $h = \given{b}/2$.
:::
:::

::: check
given: tol = 1e-4 | 1e-6 | 1e-8
answer: ceil(sqrt(exp(1)/(12*tol)))
tolerance: 0.1

## The trapezoid rule's error on $[a, b]$ is at most $\frac{(b - a)h^2}{12}\max|f''|$. How many slices guarantee an error below {tol} for $\int_0^1 e^x\,dx$?

::: right
Right. On $[0, 1]$ the largest $|f''| = e^x$ is $e$, so you need $h^2 \le 12 \times \given{tol}/e$, and $n = 1/h$ rounded up: {answer} slices.
:::

::: misses
- [ceil(sqrt(1/(12*tol)))] That takes the largest $|f''|$ as 1. On $[0, 1]$, $e^x$ reaches $e$.
- [ceil(exp(1)/(12*tol))] That solves for $h$ instead of $h^2$. Take a square root.
- [any] Not yet. Solve $\frac{h^2}{12}e \le$ {tol} for $h$, then $n = 1/h$, rounded up.
:::
:::

::: explain
## Why is measuring how fast the error shrinks a good way to test numerical code?

::: model
Each method has a known order: the trapezoid rule's error should fall about four times when the slice width halves, Simpson's about sixteen times. If a program shows exactly that ratio, it's very likely implemented correctly, because most bugs, like a wrong weight at the ends, break the pattern even when the answer looks roughly right. It also tells you how many slices you need for a given accuracy.
:::
:::

::: practice

::: check
kind: python
given: b = 0.5 | 1 | 1.5 | 2 | 2.5 | 3

## Use your trapezoid rule (or write it again) to estimate $\int_0^{\given{b}} e^{-x^2}dx$ with 1000 slices; set `area`.

```python starter
import math

area = 0
print(area)
```

```python solution
import math

def trapezoid(f, a, b, n):
    h = (b - a) / n
    return h * (0.5 * (f(a) + f(b)) + sum(f(a + k * h) for k in range(1, n)))

area = trapezoid(lambda x: math.exp(-x * x), 0, b, 1000)
print(area)
```

```python tests
import math
assert abs(area - math.sqrt(math.pi) / 2 * math.erf(b)) < 1e-5, f"The area should be about {math.sqrt(math.pi) / 2 * math.erf(b):.6f} (it's (√π/2)·erf(b))."
```
:::

::: check
kind: python

## Measure the trapezoid rule's order: set `ratio` to its error on $\int_0^1 e^x dx$ with 8 slices divided by its error with 16 slices.

```python starter
import math

ratio = 0
print(ratio)
```

```python solution
import math

def trapezoid(f, a, b, n):
    h = (b - a) / n
    return h * (0.5 * (f(a) + f(b)) + sum(f(a + k * h) for k in range(1, n)))

exact = math.e - 1
ratio = abs(trapezoid(math.exp, 0, 1, 8) - exact) / abs(trapezoid(math.exp, 0, 1, 16) - exact)
print(ratio)
```

```python tests
assert 3.8 < ratio < 4.2, f"For the trapezoid rule, the ratio should be close to 4; you got {ratio}."
```
:::
:::
