Adaptive Runge–Kutta methods and local error control

Environment

Python 3.14.6, NumPy 2.5.4, SciPy 1.18.1, Matplotlib 3.11.2.

This article is a rewrite of a post from around 2013–2016, with calculations performed in the environment described above.

Overview

Adaptive Runge–Kutta methods solve ordinary differential equations by estimating error at each step and adjusting the time step. We implement the Bogacki–Shampine pair of third- and second-order formulas, then examine error scaling, accepted and rejected steps, and the relation between tolerance and cost. Comparisons with exact solutions also distinguish local and global errors.

Setup

Run the code in Jupyter Notebook from top to bottom.

Imports and plotting setup
import platform
import sys
from pathlib import Path
from pprint import pprint

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import scipy
from IPython.display import Math, SVG, display
from matplotlib.ticker import FuncFormatter, NullFormatter
from scipy.integrate import solve_ivp
from scipy.special import erf

print('Kernel: wa-src(3.14.6)')
print('Python:', platform.python_version())
print('Executable:', sys.executable)
print('NumPy:', np.__version__)
print('SciPy:', scipy.__version__)
print('Matplotlib:', matplotlib.__version__)
assert sys.version_info[:3] == (3, 14, 6)

# Support running from the repository root or the notebook directory.
base = Path('rec/computing/107')
fig_dir = (base if base.is_dir() else Path.cwd()) / '107_nb_files'
fig_dir.mkdir(parents=True, exist_ok=True)
plt.rcParams.update({'font.size': 10, 'svg.fonttype': 'none',
                     'svg.hashsalt': 'rk107', 'axes.grid': True})


def sig(value):
    return f'{float(value):#.3g}'


np.set_printoptions(formatter={'float_kind': sig})


def save_figure(fig, name):
    # Use three significant digits for ticks, and save and display the same figure.
    for ax in fig.axes:
        for axis in (ax.xaxis, ax.yaxis):
            axis.set_major_formatter(FuncFormatter(lambda x, pos: sig(x)))
            axis.set_minor_formatter(NullFormatter())
        ax.grid(True, alpha=0.250)
    path = fig_dir / name
    fig.savefig(path, format='svg', bbox_inches='tight',
                metadata={'Date': None})
    plt.close(fig)
    display(SVG(filename=str(path)))
Kernel: wa-src(3.14.6)
Python: 3.14.6
Executable: /Users/hiroshi/private/wa_src/.venv/bin/python
NumPy: 2.5.4
SciPy: 1.18.1
Matplotlib: 3.11.2

1. One-step error and error over the full interval

Consider the initial-value problem

$$ \frac{d\mathbf{y}}{dt}=\mathbf{f}(t,\mathbf{y}), \qquad \mathbf{y}(t_0)=\mathbf{y}_0 $$

Let $h_n=t_{n+1}-t_n$, and write $\mathbf{\Phi}_{h_n}(t_n,\mathbf{v})$ for the exact one-step map from starting value $\mathbf{v}$. Local error treats the numerical starting value as exact. We use the definition without division by $h_n$.

$$ \mathbf{d}_{n+1}=\mathbf{\Phi}_{h_n}(t_n,\mathbf{y}_n)-\mathbf{y}_{n+1}, \qquad \mathbf{E}_n=\mathbf{y}(t_n)-\mathbf{y}_n. $$

$\mathbf{E}_n$ is the global error accumulated from the initial time. Adding and subtracting the same term relates the two errors.

$$ \begin{aligned} \mathbf{E}_{n+1} &=\mathbf{\Phi}_{h_n}(t_n,\mathbf{y}(t_n))-\mathbf{y}_{n+1}\\ &=\left[\mathbf{\Phi}_{h_n}(t_n,\mathbf{y}(t_n)) -\mathbf{\Phi}_{h_n}(t_n,\mathbf{y}_n)\right]+\mathbf{d}_{n+1}. \end{aligned} $$

The bracketed term propagates earlier error to the next time. With sufficient smoothness and stability, a method of order $p$ has local error $O(h^{p+1})$ and fixed-interval global error $O(h^p)$. Keeping local error small does not guarantee that global error stays within the same tolerance.

2. Embedded Runge–Kutta methods

An explicit Runge–Kutta method computes slopes $\mathbf{k}_i$ in sequence.

$$ \mathbf{k}_i=\mathbf{f}\left(t_n+c_i h, \mathbf{y}_n+h\sum_{j\lt i}a_{ij}\mathbf{k}_j\right),\qquad \mathbf{y}_{n+1}^{(p)}=\mathbf{y}_n+h\sum_i b_i\mathbf{k}_i. $$

Applying different weights $\widehat b_i$ to the same slopes gives a lower-order approximation. Their difference is used to estimate error.

The Bogacki–Shampine 3(2) pair

This pair is also used by SciPy’s RK23. We omit the next-step subscript $n+1$ below.

$$ \begin{aligned} \mathbf{k}_1&=\mathbf{f}(t_n,\mathbf{y}_n),\\ \mathbf{k}_2&=\mathbf{f}\left(t_n+\frac{h}{2},\mathbf{y}_n+\frac{h}{2}\mathbf{k}_1\right),\\ \mathbf{k}_3&=\mathbf{f}\left(t_n+\frac{3h}{4},\mathbf{y}_n+\frac{3h}{4}\mathbf{k}_2\right),\\ \mathbf{y}^{(3)}&=\mathbf{y}_n+h\left(\frac{2}{9}\mathbf{k}_1+\frac{1}{3}\mathbf{k}_2+\frac{4}{9}\mathbf{k}_3\right),\\ \mathbf{k}_4&=\mathbf{f}(t_n+h,\mathbf{y}^{(3)}),\\ \mathbf{y}^{(2)}&=\mathbf{y}_n+h\left(\frac{7}{24}\mathbf{k}_1+\frac{1}{4}\mathbf{k}_2+\frac{1}{3}\mathbf{k}_3+\frac{1}{8}\mathbf{k}_4\right). \end{aligned} $$

The coefficient differences are $2/9-7/24=-5/72$, $1/3-1/4=1/12$, and $4/9-1/3=1/9$. The estimate is therefore

$$ \boxed{\mathbf{e}=\mathbf{y}^{(3)}-\mathbf{y}^{(2)} =h\left(-\frac{5}{72}\mathbf{k}_1+\frac{1}{12}\mathbf{k}_2 +\frac{1}{9}\mathbf{k}_3-\frac{1}{8}\mathbf{k}_4\right)} $$

Let $\mathbf{Y}$ be the exact value after one step. Then

$$ \mathbf{e}=(\mathbf{Y}-\mathbf{y}^{(2)})-(\mathbf{Y}-\mathbf{y}^{(3)}) =O(h^3)-O(h^4)=O(h^3). $$

This difference primarily estimates the local error of the second-order formula. We accept the third-order value, but use the $h^3$ scaling to update the step size.

def bs23_step(fun, t, y, h, k1=None):
    # Reusing k1 requires only three additional function evaluations.
    if k1 is None:
        k1 = fun(t, y)
    k2 = fun(t + h / 2, y + h * k1 / 2)
    k3 = fun(t + 3 * h / 4, y + 3 * h * k2 / 4)
    y3 = y + h * (2 * k1 / 9 + k2 / 3 + 4 * k3 / 9)
    k4 = fun(t + h, y3)
    # Compute the estimate from coefficient differences rather than subtracting nearby y3 and y2.
    error = h * (-5 * k1 / 72 + k2 / 12 + k3 / 9 - k4 / 8)
    return y3, error, k4

Checking orders with $y^{\prime}=-y$

Take one step from $y(0)=1$. Substituting the slopes gives

$$ \begin{aligned} k_1&=-1,\qquad k_2=-\left(1-\frac h2\right)=-1+\frac h2,\\ k_3&=-\left(1+\frac{3h}{4}\left(-1+\frac h2\right)\right) =-1+\frac{3h}{4}-\frac{3h^2}{8},\\ y^{(3)}&=1+h\left[-\frac29+\frac13\left(-1+\frac h2\right) +\frac49\left(-1+\frac{3h}{4}-\frac{3h^2}{8}\right)\right]\\ &=1-h+\frac{h^2}{2}-\frac{h^3}{6},\\ k_4&=-1+h-\frac{h^2}{2}+\frac{h^3}{6},\\ y^{(2)}&=1+h\left[-\frac7{24}+\frac14\left(-1+\frac h2\right) +\frac13\left(-1+\frac{3h}{4}-\frac{3h^2}{8}\right) +\frac18\left(-1+h-\frac{h^2}{2}+\frac{h^3}{6}\right)\right]\\ &=1-h+\frac{h^2}{2}-\frac{3h^3}{16}+\frac{h^4}{48}. \end{aligned} $$

Subtract the two approximations and compare with the expansion of the exact solution $e^{-h}$.

$$ \begin{aligned} e&=\left(-\frac16+\frac3{16}\right)h^3-\frac{h^4}{48} =\frac{h^3(1-h)}{48},\\ e^{-h}-y^{(3)} &=\left(1-h+\frac{h^2}{2}-\frac{h^3}{6}+\frac{h^4}{24}+O(h^5)\right) -\left(1-h+\frac{h^2}{2}-\frac{h^3}{6}\right)\\ &=\frac{h^4}{24}+O(h^5). \end{aligned} $$

On a log–log plot, the estimate approaches slope three and the third-order solution’s local error approaches slope four. At $h=1$, however, the estimate is zero while the true error is not. This is a small-step approximation, not a rigorous error bound.

hs = 2.00 ** (-np.arange(3, 10))
estimates, defects = [], []
for h in hs:
    y3, e, _ = bs23_step(lambda t, y: -y, 0, np.array([1.00]), h)
    estimates.append(abs(e[0]))
    defects.append(abs(np.exp(-h) - y3[0]))
estimates, defects = np.array(estimates), np.array(defects)
pprint({'estimate order': sig(np.log2(estimates[-2] / estimates[-1])),
        'local error order of the third-order solution': sig(np.log2(defects[-2] / defects[-1]))})
display(Math(r'e=\frac{h^3(1-h)}{48},\qquad d^{(3)}=\frac{h^4}{24}+O(h^5)'))

fig, ax = plt.subplots(figsize=(7, 4), layout='constrained')
ax.loglog(hs, estimates, 'o-', label='Embedded estimate')
ax.loglog(hs, defects, 's-', label='True local error, order 3')
ax.loglog(hs, hs**3 / 48, '--', label=r'$h^3/48$')
ax.loglog(hs, hs**4 / 24, ':', label=r'$h^4/24$')
ax.set(xlabel='Step size h', ylabel='Absolute error')
ax.legend()
save_figure(fig, '01_local_order.svg')
{'estimate order': '3.00',
 'local error order of the third-order solution': '4.00'}

$$ \displaystyle e=\frac{h^3(1-h)}{48},\qquad d^{(3)}=\frac{h^4}{24}+O(h^5) $$

3. Tolerances and step size updates

Build the error scale for component $i$ from absolute and relative tolerances.

$$ s_i=\mathrm{atol}_i+\mathrm{rtol}\max(|y_{n,i}|,|y_i^{(3)}|), \qquad r_i=\frac{|e_i|}{s_i},\qquad R=\max_i r_i. $$

Accept the step when $R\leq1$. If $R\gt 1$, retry without advancing time or state. Near $y_i=0$, atol controls the scale. Use component-specific atol values when components have different units or magnitudes.

If the scales and error coefficients stay nearly constant on the next trial, write $R\simeq Ch^{q+1}$. Targeting a value of one gives

$$ \frac{R_{\mathrm{new}}}{R}\simeq \left(\frac{h_{\mathrm{new}}}{h}\right)^{q+1},\qquad \frac1R\simeq\left(\frac{h_{\mathrm{new}}}{h}\right)^{q+1},\qquad \frac{h_{\mathrm{new}}}{h}\simeq R^{-1/(q+1)}. $$

For the 3(2) pair, $q=2$. Add a safety factor of $0.900$ and limits on the step size change.

$$ \boxed{h_{\mathrm{new}}=h\,\min\left(5,\max\left(0.200,0.900R^{-1/3}\right)\right)} $$

If $R=0$, use a factor of five. On an accepted step immediately following a rejection, cap the factor at one. Examining rejection counts and step sizes as well as the solution curve reveals where retries concentrate.

The implementation below handles forward integration, real one-dimensional state arrays, and positive tolerances. After an accepted step, $\mathbf{k}_4$ equals the next $\mathbf{k}_1$ and is reused. This is the first-same-as-last, or FSAL, property. With $N$ trials, the function evaluation count is $1+3N$.

def adaptive_bs23(fun, span, y0, rtol=1.00e-5, atol=1.00e-8,
                  h0=0.500, max_step=1.00, max_trials=100000):
    t, end = map(float, span)
    y = np.asarray(y0, dtype=float).copy()
    if y.ndim != 1 or y.size == 0 or not np.all(np.isfinite(y)):
        raise ValueError('y0 must be a finite one-dimensional real array')
    atol = np.broadcast_to(np.asarray(atol, dtype=float), y.shape)
    values = np.r_[t, end, rtol, h0, max_step, atol]
    if (not np.all(np.isfinite(values)) or end <= t or rtol <= 0
            or h0 <= 0 or max_step <= 0 or np.any(atol <= 0)):
        raise ValueError('A finite interval and positive tolerances and step size are required')
    ts, ys, trials = [t], [y.copy()], []
    h, nfev, rejected = min(h0, max_step), 1, False
    k1 = fun(t, y)
    for _ in range(max_trials):
        if t >= end:
            break
        # Do not pass the endpoint; stop if rounding prevents time from advancing.
        next_t = min(t + min(h, max_step), end)
        h = next_t - t
        if h <= 0:
            raise RuntimeError('Step size is too small to advance time')
        candidate, error, k4 = bs23_step(fun, t, y, h, k1)
        nfev += 3
        scale = atol + rtol * np.maximum(abs(y), abs(candidate))
        ratio = float(np.max(abs(error) / scale))
        if not np.isfinite(ratio) or not np.all(np.isfinite(candidate)):
            raise FloatingPointError('The solution or error estimate is not finite')
        accepted = ratio <= 1
        trials.append((t, h, ratio, accepted))
        factor = 5 if ratio == 0 else np.clip(0.900 * ratio**(-1 / 3), 0.200, 5)
        if accepted:
            if rejected:
                factor = min(1, factor)
            t, y, k1 = next_t, candidate, k4
            ts.append(t)
            ys.append(y.copy())
            rejected = False
        else:
            # Keep t, y, and k1 on rejection.
            rejected = True
        h *= factor
    if t < end:
        raise RuntimeError('Maximum trial count reached')
    return {'t': np.array(ts), 'y': np.array(ys),
            'trials': np.array(trials), 'nfev': nfev}

4. Step sizes where the solution changes rapidly

The following decay equation has an increased decay rate near $t=3$.

$$ y^{\prime}=-a(t)y,\qquad a(t)=1+20e^{-25(t-3)^2},\qquad y(0)=1. $$

Separation of variables gives $\log y(t)=-\int_0^t a(s)\,ds=-A(t)$. Set $u=5(s-3)$ and $ds=du/5$, and use $\mathrm{erf}(x)=2\int_0^x e^{-u^2}\,du/\sqrt\pi$.

$$ \begin{aligned} A(t)&=t+20\int_0^t e^{-25(s-3)^2}\,ds\\ &=t+4\int_{-15}^{5(t-3)}e^{-u^2}\,du\\ &=t+2\sqrt\pi\left[\mathrm{erf}(5(t-3))-\mathrm{erf}(-15)\right],\\ y(t)&=e^{-A(t)}. \end{aligned} $$

Integrate over $0\leq t\leq6$, starting with a step of $0.500$, and record rejected trials too.

def integral_rate(t):
    return t + 2 * np.sqrt(np.pi) * (erf(5 * (t - 3)) - erf(-15))


def exact(t):
    return np.exp(-integral_rate(t))


def rhs(t, y):
    return -(1 + 20 * np.exp(-25 * (t - 3)**2)) * y


run = adaptive_bs23(rhs, (0, 6), [1.00])
t, y = run['t'], run['y'][:, 0]
trial = run['trials']
accepted = trial[:, 3].astype(bool)
global_error = abs(y - exact(t))
pprint({'accepted': len(t) - 1, 'rejected': int((~accepted).sum()),
        'function evaluations': run['nfev'], 'maximum absolute error at nodes': sig(global_error.max())})

grid = np.linspace(0, 6, 1201)
fig, axes = plt.subplots(2, 1, figsize=(8, 6), layout='constrained')
axes[0].semilogy(grid, exact(grid), label='Exact')
axes[0].semilogy(t, y, '.', label='Accepted nodes')
axes[0].set(ylabel='y(t)')
axes[0].legend()
axes[1].semilogy(t[:-1], np.diff(t), '.-', label='Accepted h')
axes[1].semilogy(trial[~accepted, 0], trial[~accepted, 1], 'x',
                 color='tab:red', label='Rejected h')
axes[1].set(xlabel='t', ylabel='Step size h')
axes[1].legend()
save_figure(fig, '02_adaptive_steps.svg')
{'accepted': 143,
 'function evaluations': 472,
 'maximum absolute error at nodes': '6.15e-06',
 'rejected': 14}

Steps shrink where the decay rate rises. Later, when the solution becomes sufficiently small, absolute tolerance dominates and steps grow again. Step size is not determined by slope magnitude alone.

In this example, we can also compute the exact one-step result starting from the numerical value $y_n$.

$$ \Phi_h(t_n,y_n)=y_n e^{-[A(t_n+h)-A(t_n)]},\qquad d_{n+1}=y_n e^{-[A(t_{n+1})-A(t_n)]}-y_{n+1}. $$

The upper panel below shows the acceptance measure $R$. The lower panel compares the true local error of accepted third-order steps with global error. Zero values are omitted because a logarithmic axis cannot display them.

local_error = abs(y[:-1] * np.exp(-np.diff(integral_rate(t))) - y[1:])
fig, axes = plt.subplots(2, 1, figsize=(8, 6), layout='constrained')
for mask, label, marker in [(accepted, 'Accepted', '.'), (~accepted, 'Rejected', 'x')]:
    positive = mask & (trial[:, 2] > 0)
    axes[0].semilogy(np.flatnonzero(positive), trial[positive, 2], marker, label=label)
axes[0].axhline(1, color='black', linestyle='--', label='Acceptance limit')
axes[0].set(xlabel='Trial index', ylabel='Normalized estimate R')
axes[0].legend()
for errors, label in [(local_error, 'True local error'), (global_error[1:], 'Global error')]:
    positive = errors > 0
    axes[1].semilogy(t[1:][positive], errors[positive], label=label)
axes[1].set(xlabel='t', ylabel='Absolute error')
axes[1].legend()
save_figure(fig, '03_error_control.svg')

5. Tolerance and computational cost

Solve the same problem with decreasing rtol, setting atol = rtol / 1000. Compare the maximum absolute error at accepted nodes in each run; it is not an upper bound over the whole interval. Function evaluation counts include rejected trials.

rtols = np.logspace(-3, -7, 5)
errors, costs, rows = [], [], []
for tol in rtols:
    result = adaptive_bs23(rhs, (0, 6), [1.00], rtol=tol, atol=tol / 1000)
    error = np.max(abs(result['y'][:, 0] - exact(result['t'])))
    errors.append(error)
    costs.append(result['nfev'])
    rows.append({'rtol': sig(tol), 'maximum error': sig(error), 'function evaluations': result['nfev']})
pprint(rows, sort_dicts=False)

fig, axes = plt.subplots(1, 2, figsize=(10, 4), layout='constrained')
axes[0].loglog(rtols, errors, 'o-')
axes[0].set(xlabel='rtol', ylabel='Max nodal absolute error')
axes[1].loglog(rtols, costs, 's-')
axes[1].set(xlabel='rtol', ylabel='Function evaluations')
save_figure(fig, '04_tolerance_cost.svg')
[{'rtol': '0.00100', 'maximum error': '0.00135', 'function evaluations': 127},
 {'rtol': '0.000100', 'maximum error': '7.33e-05', 'function evaluations': 247},
 {'rtol': '1.00e-05', 'maximum error': '6.15e-06', 'function evaluations': 472},
 {'rtol': '1.00e-06', 'maximum error': '5.72e-07', 'function evaluations': 949},
 {'rtol': '1.00e-07',
  'maximum error': '5.52e-08',
  'function evaluations': 1990}]

Tighter tolerances reduce error and increase function evaluations in this example. This trend need not continue when rounding error or stability limits dominate.

6. Component-specific absolute tolerances for small components

Use a decaying first component and a small-amplitude oscillating second component.

$$ \mathbf{y}^{\prime}=\begin{bmatrix}-y_1\\-10^{-5}\sin(10t)\end{bmatrix},\qquad \mathbf{y}(0)=\begin{bmatrix}1\\10^{-6}\end{bmatrix},\qquad \mathbf{y}(t)=\begin{bmatrix}e^{-t}\\10^{-6}\cos(10t)\end{bmatrix}. $$

Fix rtol at $1.00\times10^{-3}$. A shared atol of $1.00\times10^{-6}$ gives the small component a tolerance comparable to its initial magnitude. Change only its tolerance to $1.00\times10^{-12}$. To compare the components, divide each error by the magnitude of its initial value. This differs from relative error divided by $y_i(t)$.

initial = np.array([1.00, 1.00e-6])


def two_components(t, y):
    return np.array([-y[0], -1.00e-5 * np.sin(10 * t)])


cases = {'Shared atol': 1.00e-6,
         'Component atol': np.array([1.00e-6, 1.00e-12])}
fig, axes = plt.subplots(1, 2, figsize=(10, 4), layout='constrained')
for label, atol in cases.items():
    result = adaptive_bs23(two_components, (0, 6), initial, rtol=1.00e-3, atol=atol)
    reference = np.column_stack((np.exp(-result['t']), np.cos(10 * result['t'])))
    relative_to_initial = abs(result['y'] / initial - reference)
    pprint({'setting': label, 'function evaluations': result['nfev'],
            'maximum error scaled by initial values': [sig(v) for v in relative_to_initial.max(axis=0)]})
    for i, ax in enumerate(axes):
        positive = relative_to_initial[:, i] > 0
        ax.semilogy(result['t'][positive], relative_to_initial[positive, i], label=label)
        ax.set(xlabel='t', ylabel=f'Absolute error / initial[{i}]', title=f'Component {i + 1}')
        ax.legend()
save_figure(fig, '05_component_atol.svg')
{'function evaluations': 52,
 'maximum error scaled by initial values': ['0.00135', '0.347'],
 'setting': 'Shared atol'}
{'function evaluations': 916,
 'maximum error scaled by initial values': ['6.28e-07', '0.000200'],
 'setting': 'Component atol'}

Component-specific tolerances restrict steps to follow the small component’s oscillation, increasing the evaluation count. Choose atol from the absolute accuracy needed for each component, not simply by choosing an arbitrarily small number.

7. Using SciPy’s RK23 and RK45

solve_ivp adjusts steps from the specified tolerances. t_eval specifies output times, not internal step sizes. Omit it here and use sol.t to recover accepted internal steps.

For $m$ components, SciPy uses the root mean square of the scaled errors, $R_{\mathrm{RMS}}=\sqrt{\sum_i r_i^2/m}$. For multiple components, this can produce different acceptance decisions from the maximum norm used here. Initial step selection and growth limits also differ, so the nodes need not match exactly.

RK45 uses the Dormand–Prince 5(4) pair. The fourth-order formula has local error $O(h^5)$, giving the update exponent $-1/5$, while the accepted value uses the fifth-order formula. This differs from $-1/3$ for the 3(2) pair.

fig, axes = plt.subplots(1, 2, figsize=(10, 4), layout='constrained')
solutions = {}
for method in ('RK23', 'RK45'):
    sol = solve_ivp(rhs, (0, 6), [1.00], method=method,
                    rtol=1.00e-5, atol=1.00e-8, max_step=1.00)
    if not sol.success:
        raise RuntimeError(sol.message)
    solutions[method] = sol
    error = abs(sol.y[0] - exact(sol.t))
    pprint({'method': method, 'accepted': len(sol.t) - 1, 'function evaluations': sol.nfev,
            'maximum absolute error at nodes': sig(error.max())})
    positive = error > 0
    axes[0].semilogy(sol.t[positive], error[positive], label=method)
    axes[1].semilogy(sol.t[:-1], np.diff(sol.t), '.-', label=method)
axes[0].set(xlabel='t', ylabel='Absolute error at nodes')
axes[1].set(xlabel='t', ylabel='Accepted step size')
for ax in axes:
    ax.legend()
save_figure(fig, '06_scipy_comparison.svg')
{'accepted': 144,
 'function evaluations': 467,
 'maximum absolute error at nodes': '5.89e-06',
 'method': 'RK23'}
{'accepted': 35,
 'function evaluations': 260,
 'maximum absolute error at nodes': '1.17e-06',
 'method': 'RK45'}

Higher order is not always better, but RK45 needs fewer evaluations for this smooth problem. For stiff problems, explicit-method stability restricts steps as well as error control. Radau or BDF may then be appropriate. Split the integration interval at known discontinuities. Tighter tolerances alone do not resolve these issues.

Conclusion

We derived local error estimation and step size control for embedded Runge–Kutta methods, then checked accuracy and cost in Python.

The 3(2) pair uses the difference from the second-order solution as an $O(h^3)$ estimate and accepts the third-order solution. Errors are scaled to each component’s magnitude, and rejected trials restart from the same point. Since the local acceptance condition does not bound global error, also check the required accuracy by repeating the calculation with different tolerances.