---
title: "Numerical methods lab: roots, quadrature and an adaptive integrator"
heading: Three robust routines, each checked against an exact answer
eyebrow: "A13 · Lesson 51 · Numerical methods lab"
xp: 60
---

::: hook
Library routines like `brentq`, `quad` and `solve_ivp` are built from the ideas in this course: a fast method guarded by a safe one, an error estimate from two answers, and a step that adapts. In this lab you'll write a small version of each: a Newton solver that falls back to bisection, an adaptive Simpson integrator, and an RK4 integrator that adapts its step by step doubling. Each test compares against an exact answer, and each counts the work, so you can see the adaptivity pay off.
:::

::: predict
## Your adaptive RK4 integrator solves $\dot y = -50(y - \cos t)$ from y(0) = 0. Where will it take its smallest steps?

- [x] At the start, during the fast initial transient
- [ ] Evenly everywhere
- [ ] At the end
- [ ] Where $\cos t$ is largest

::: reveal
At the start. The solution has a fast part $e^{-50t}$ that dies within about 0.1, then follows the slow $\cos t$ forcing. The error estimate is large while the fast part is alive, so the steps start small and grow once it's gone, by a factor of about 10 here.
:::
:::

::: nameit
## What you'll write

1. `safe_newton(f, df, a, b, tol)`: keep a bracket [a, b] with a sign change. Try a Newton step from the current point; if it lands outside the bracket, bisect instead. After each step shrink the bracket using the sign of f. Stop when the step is below tol. Return `(root, steps)`.
2. `adaptive_simpson(f, a, b, tol)`: the recursive method of lesson 19. Accept a piece when $\lvert S_2 - S_1\rvert \le 15\,\text{tol}$ and return $S_2 + (S_2 - S_1)/15$; otherwise split it, giving each half tol/2. Count function evaluations (reuse the ones you already have). Return `(value, evaluations)`.
3. `rk4_adaptive(f, t0, y0, t1, tol)`: from each point take one RK4 step of size h and two of h/2; the error estimate is $\lvert y_{h/2} - y_h\rvert/15$. Accept the two-step answer if the estimate is at most tol; either way set the next h to $0.9h(\text{tol}/\text{err})^{1/5}$, between h/5 and 5h. Don't step past t1. Return the lists of times and values.

## The exact answers

- $x^3 - 2x - 5 = 0$ has its root at 2.0945514815423265.
- $\int_0^1\sqrt x\,dx = \frac23$ and $\int_0^\pi\sin x\,dx = 2$.
- $\dot y = -k(y - \cos t)$, y(0) = 0, has $y = \frac{k^2\cos t + k\sin t}{1 + k^2} - \frac{k^2}{1 + k^2}e^{-kt}$.
:::

::: example
## Why must the safeguarded solver check the Newton step against the bracket?

::: solution
1. **Plain Newton on $\arctan x$.** From x = 2 it jumps to
   $$2 - \arctan 2 \times (1 + 4) = -3.54$$
   then to 13.95, and diverges.
2. **With a bracket.** With [−10, 10] the first jump lands inside, but each later wild step falls outside the shrinking bracket and is replaced by bisection.
3. **Back to Newton.** That goes on until the iterate is close enough for Newton to take over.

**Answer:** an unchecked Newton step can leave the region of the root and diverge, as on $\arctan x$ from 2; checking against the bracket replaces each such step with bisection.
:::
:::

::: example
## How many function evaluations does one step-doubling RK4 step cost?

::: solution
1. **Count the evaluations.** The full step uses 4 evaluations and the two half steps 8.
2. **Share one.** The full step and the first half step both start with $f(t, y)$, so 11 in all.
3. **Compare.** That's almost three times one RK4 step, the price of the error estimate. Embedded pairs (RK45) get theirs for 6 or 7.

**Answer:** 11 evaluations.
:::
:::

::: check
kind: python

## Step 1. Write `safe_newton(f, df, a, b, tol)` returning `(root, steps)`.

```python starter
import math

def safe_newton(f, df, a, b, tol):
    x = (a + b) / 2
    steps = 0
    # keep f(a) and f(b) of opposite signs; take Newton steps that stay inside, else bisect
    return x, steps

print(safe_newton(lambda x: x**3 - 2*x - 5, lambda x: 3*x**2 - 2, 2, 3, 1e-12))
```

```python solution
import math

def safe_newton(f, df, a, b, tol):
    fa = f(a)
    x = (a + b) / 2
    steps = 0
    while True:
        steps += 1
        fx = f(x)
        if fx == 0:
            return x, steps
        if (fx > 0) == (fa > 0):
            a, fa = x, fx
        else:
            b = x
        d = df(x)
        new = x - fx / d if d != 0 else None
        if new is None or not (a < new < b):
            new = (a + b) / 2
        if abs(new - x) < tol or steps > 200:
            return new, steps
        x = new

print(safe_newton(lambda x: x**3 - 2*x - 5, lambda x: 3*x**2 - 2, 2, 3, 1e-12))
```

```python tests
import math
r, n = safe_newton(lambda x: x**3 - 2*x - 5, lambda x: 3*x**2 - 2, 2, 3, 1e-12)
assert abs(r - 2.0945514815423265) < 1e-11, f"The root of x³ − 2x − 5 is 2.0945514815; got {r}."
assert n <= 10, f"Newton should finish in a handful of steps here; it took {n}."
r, n = safe_newton(math.atan, lambda x: 1 / (1 + x * x), -10, 10, 1e-12)
assert abs(r) < 1e-11, f"arctan's root is 0; got {r}. Plain Newton diverges from a far start; the bracket should save it."
r, n = safe_newton(lambda x: math.atan(x - 0.3), lambda x: 1 / (1 + (x - 0.3) ** 2), -10, 10, 1e-12)
assert abs(r - 0.3) < 1e-11 and n < 60, f"Expected 0.3 in under 60 steps; got {r} after {n}."
```

::: right
Right. On a polynomial it's pure Newton; on arctan from a wide bracket, bisection steps carry it in until Newton can finish.
:::
:::

::: check
kind: python

## Step 2. Write `adaptive_simpson(f, a, b, tol)` returning `(value, evaluations)`.

```python starter
import math

def adaptive_simpson(f, a, b, tol):
    evaluations = 0
    # compute S on [a, b], then recurse: accept when |S2 - S1| <= 15 tol
    return 0.0, evaluations

print(adaptive_simpson(math.sqrt, 0, 1, 1e-10))
```

```python solution
import math

def adaptive_simpson(f, a, b, tol):
    count = [0]
    def F(x):
        count[0] += 1
        return f(x)
    def simpson(a, fa, m, fm, b, fb):
        return (b - a) / 6 * (fa + 4 * fm + fb)
    def rec(a, fa, b, fb, m, fm, whole, tol, depth):
        lm, rm = (a + m) / 2, (m + b) / 2
        flm, frm = F(lm), F(rm)
        left = simpson(a, fa, lm, flm, m, fm)
        right = simpson(m, fm, rm, frm, b, fb)
        if abs(left + right - whole) <= 15 * tol or depth > 50:
            return left + right + (left + right - whole) / 15
        return rec(a, fa, m, fm, lm, flm, left, tol / 2, depth + 1) + rec(m, fm, b, fb, rm, frm, right, tol / 2, depth + 1)
    fa, fb, m = F(a), F(b), (a + b) / 2
    fm = F(m)
    value = rec(a, fa, b, fb, m, fm, simpson(a, fa, m, fm, b, fb), tol, 0)
    return value, count[0]

print(adaptive_simpson(math.sqrt, 0, 1, 1e-10))
```

```python tests
import math
v, n = adaptive_simpson(math.sin, 0, math.pi, 1e-10)
assert abs(v - 2) < 1e-9, f"∫ sin from 0 to π is 2; got {v}."
v, n = adaptive_simpson(math.sqrt, 0, 1, 1e-10)
assert abs(v - 2 / 3) < 1e-9, f"∫ √x from 0 to 1 is 2/3; got {v}."
assert n < 3000, f"Adaptive Simpson should need well under 3000 evaluations for √x at 1e-10; it used {n}. Are you reusing function values?"
v2, n2 = adaptive_simpson(math.sqrt, 0.5, 1, 1e-10)
assert n2 < n / 3, "On [0.5, 1], where √x is smooth, it should need far fewer evaluations than on [0, 1]."
```

::: right
Right. The square root at 0 is where the evaluations go; on [0.5, 1] the same tolerance takes only a few dozen.
:::
:::

::: check
kind: python

## Step 3. Write `rk4_adaptive(f, t0, y0, t1, tol)` returning lists `ts` and `ys` of accepted points (starting with t0, y0).

```python starter
import math

def rk4_step(f, t, y, h):
    k1 = f(t, y)
    k2 = f(t + h / 2, y + h / 2 * k1)
    k3 = f(t + h / 2, y + h / 2 * k2)
    k4 = f(t + h, y + h * k3)
    return y + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)

def rk4_adaptive(f, t0, y0, t1, tol):
    ts, ys = [t0], [y0]
    h = (t1 - t0) / 100
    # step doubling: compare one step of h with two of h/2
    return ts, ys

k = 50
ts, ys = rk4_adaptive(lambda t, y: -k * (y - math.cos(t)), 0, 0.0, 2, 1e-8)
print(len(ts), ys[-1])
```

```python solution
import math

def rk4_step(f, t, y, h):
    k1 = f(t, y)
    k2 = f(t + h / 2, y + h / 2 * k1)
    k3 = f(t + h / 2, y + h / 2 * k2)
    k4 = f(t + h, y + h * k3)
    return y + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)

def rk4_adaptive(f, t0, y0, t1, tol):
    ts, ys = [t0], [y0]
    t, y = t0, y0
    h = (t1 - t0) / 100
    while t < t1 - 1e-15:
        h = min(h, t1 - t)
        full = rk4_step(f, t, y, h)
        half = rk4_step(f, t + h / 2, rk4_step(f, t, y, h / 2), h / 2)
        err = abs(half - full) / 15
        if err <= tol:
            t, y = t + h, half + (half - full) / 15
            ts.append(t)
            ys.append(y)
        factor = 5.0 if err == 0 else min(5.0, max(0.2, 0.9 * (tol / err) ** 0.2))
        h *= factor
    return ts, ys

k = 50
ts, ys = rk4_adaptive(lambda t, y: -k * (y - math.cos(t)), 0, 0.0, 2, 1e-8)
print(len(ts), ys[-1])
```

```python tests
import math
k = 50
exact = lambda t: (k * k * math.cos(t) + k * math.sin(t)) / (1 + k * k) - k * k / (1 + k * k) * math.exp(-k * t)
ts, ys = rk4_adaptive(lambda t, y: -k * (y - math.cos(t)), 0, 0.0, 2, 1e-8)
assert abs(ts[-1] - 2) < 1e-12, f"The last point should be exactly t1 = 2; got {ts[-1]}."
err = max(abs(y - exact(t)) for t, y in zip(ts, ys))
assert err < 1e-6, f"With tol = 1e-8 the solution should be within 1e-6 everywhere; the worst error is {err:.2e}."
steps = [b - a for a, b in zip(ts, ts[1:])]
assert max(steps[-5:]) > 5 * min(steps[:5]), "Steps near the end should be much larger than during the initial transient."
ts2, ys2 = rk4_adaptive(lambda t, y: -y, 0, 1.0, 5, 1e-10)
assert abs(ys2[-1] - math.exp(-5)) < 1e-8, f"For y' = −y, y(5) should be e^−5; got {ys2[-1]}."
```

::: right
Right. The steps start small during the $e^{-50t}$ transient and grow by an order of magnitude once it has died, with the error everywhere well inside the target.
:::
:::

::: check
given: a = 0.5403 | 0.3679 | 0.1653; d = 0.0006 | -0.0021; let b = a + d
answer: (b - a)/15
tolerance: 0.5%

## Step doubling with RK4 gives {a} from one step and {b} from two half steps. What's the estimated error of the two-step answer?

::: right
Right. $\frac{y_{h/2} - y_h}{2^4 - 1}$ = {answer}.
:::

::: misses
- [b - a] Divide by 15: most of the difference is the full step's error.
- [any] Not yet. $\frac{y_{h/2} - y_h}{15}$.
:::
:::

::: check
given: k = 5 | 20 | 50
answer: k^2/(1 + k^2)
tolerance: 0.01%

## For $\dot y = -\given{k}(y - \cos t)$, y(0) = 0, what's the amplitude of the decaying term $e^{-kt}$ in the exact solution (its coefficient's size)?

::: right
Right. $\frac{k^2}{1 + k^2}$ = {answer}.
:::

::: misses
- [1] Close, but the exact coefficient is $\frac{k^2}{1 + k^2}$.
- [any] Not yet. Choose C so that y(0) = 0: $C = -\frac{k^2}{1 + k^2}$.
:::
:::

::: explain
## In the adaptive RK4 integrator, why can the step grow so much after the initial transient, when the forcing is still changing?

::: model
The step is chosen to keep each step's local error near the tolerance, and that error depends on how fast the solution's higher derivatives are. During the transient the solution contains $e^{-50t}$, whose fifth derivative is $50^5$ times as large, so the steps must be tiny. Once that term has decayed, the solution follows $\cos t$, whose derivatives are all of size about 1, so a much larger step gives the same error. The forcing still changes, but slowly, and the step only has to resolve that slow change. The equation is mildly stiff, though: with k = 50 an explicit method's stability also limits the step to a few hundredths, and the controller finds that limit too, by rejecting steps where the error estimate grows.
:::
:::

::: practice

::: check
given: a = 0.7071 | 0.9048; d = 0.0003 | -0.0015; let b = a + d
answer: (b - a)/15
tolerance: 0.5%

## RK4 step-doubling error estimate from {a} and {b}?

::: misses
- [any] $(y_{h/2} - y_h)/15$.
:::
:::

::: check
given: k = 2 | 5 | 10 | 50 | 100 | 1000
answer: k^2/(1 + k^2)
tolerance: 0.01%

## Size of the $e^{-kt}$ coefficient for k = {k}?

::: misses
- [any] $\frac{k^2}{1 + k^2}$.
:::
:::

::: check
given: h = 0.01 | 0.2; e = 0.00000005 | 0.000000001; t = 0.00000001
answer: h*0.9*(t/e)^(1/5)
tolerance: 0.5%

## Next step from h = {h}, error {e}, tolerance {t}?

::: misses
- [any] $0.9h(\text{tol}/\text{err})^{1/5}$.
:::
:::
:::
