Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions maths/euler_method.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ def explicit_euler(
) -> np.ndarray:
"""Calculate numeric solution at each step to an ODE using Euler's Method

For dy/dx = y with y(0) = 1 on [0, 1], the global error is O(h).
The modified Euler method has error O(h**2), while classical Runge-Kutta
has error O(h**4). Halving the step size therefore reduces the errors by
approximately 1/2, 1/4, and 1/16, respectively.

For reference to Euler's method refer to https://en.wikipedia.org/wiki/Euler_method.

Args:
Expand All @@ -28,6 +33,20 @@ def explicit_euler(
>>> y = explicit_euler(f, y0, 0.0, 0.01, 5)
>>> float(y[-1])
144.77277243257308

Compare the error ratios for halved step sizes:

>>> import math
>>> from maths.euler_modified import euler_modified
>>> from maths.numerical_analysis.runge_kutta import runge_kutta
>>> def error(method, h):
... return abs(float(method(f, 1, 0, h, 1)[-1]) - math.e)
>>> round(error(explicit_euler, 0.05) / error(explicit_euler, 0.1), 2)
0.52
>>> round(error(euler_modified, 0.05) / error(euler_modified, 0.1), 2)
0.26
>>> round(error(runge_kutta, 0.05) / error(runge_kutta, 0.1), 2)
0.07
"""
n = int(np.ceil((x_end - x0) / step_size))
y = np.zeros((n + 1,))
Expand Down
60 changes: 60 additions & 0 deletions work/R23-T047/COMPARE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Euler method comparison

## Interfaces

All three functions take the same positional arguments in the same order:
an ODE callable, initial value `y0`, initial position `x0`, step size, and
endpoint. The parameter names differ in `runge_kutta` (`f` and `h` rather than
`ode_func` and `step_size`), and only `explicit_euler` and `euler_modified`
annotate their arguments and NumPy-array return value. Each returns a NumPy
array containing the initial value and one value per step. Each computes the
number of steps with `ceil((x_end - x0) / h)`, so a non-divisible interval can
end past `x_end`.

The algorithms use one derivative evaluation per step for explicit Euler, two
for modified Euler (predictor-corrector/Heun), and four for classical RK4.

## Error results

For `dy/dx = y`, `y(0) = 1` on `[0, 1]`, the exact endpoint is `e`. The table
shows absolute endpoint error:

| Step size `h` | Explicit Euler | Modified Euler | Classical RK4 |
| ---: | ---: | ---: | ---: |
| 0.1 | 0.124539368359 | 0.004200981851 | 2.084323879e-6 |
| 0.05 | 0.064984123315 | 0.001090774104 | 1.358027100e-7 |
| 0.025 | 0.033217990069 | 0.000277884088 | 8.666190432e-9 |
| Observed order, `h=0.1` to `0.025` | 0.9533 | 1.9591 | 3.9550 |

The measured orders are close to the expected `O(h)`, `O(h**2)`, and `O(h**4)`.
Halving `h` reduces error by roughly `1/2`, `1/4`, and `1/16`, respectively.

## Speed results

The benchmark runs all three solvers on the same 11 shared inputs. It reports
the median of five measurements, each running 1,000 batches of all 11 inputs.
Times are microseconds per solver call:

| Solver | Median time |
| --- | ---: |
| Explicit Euler | 6.03 us |
| Modified Euler | 12.49 us |
| Classical RK4 | 17.72 us |

Measured on macOS arm64 with Python 3.15.0rc3 free-threading build. These short
runs are machine- and load-dependent; they show the relative cost for these
small test inputs, not a general performance guarantee.

## Recommendation for a beginner

Start with explicit Euler: its update is simplest to understand and fastest in
this comparison, while making the first-order accuracy tradeoff clear. Then
compare modified Euler's predictor-corrector improvement and RK4's much higher
accuracy per step when accuracy matters more than a small increase in work.

## Validation

- `uv run pytest work/R23-T047/compare_test.py` — passed (12 tests).
- `uv run pytest maths/euler_method.py maths/euler_modified.py maths/numerical_analysis/runge_kutta.py --doctest-modules` — passed (3 modules).
- `uvx ruff check maths/euler_method.py work/R23-T047/compare_test.py` — passed.
- `uvx ruff format --check maths/euler_method.py work/R23-T047/compare_test.py` — passed.
1 change: 1 addition & 0 deletions work/R23-T047/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Comparison evidence for task R23-T047."""
114 changes: 114 additions & 0 deletions work/R23-T047/compare_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
"""Compare Euler, modified Euler, and classical RK4 on shared inputs."""

import math
import statistics
import sys
from collections.abc import Callable
from pathlib import Path
from time import perf_counter

import numpy as np
import pytest

sys.path.insert(0, str(Path(__file__).resolve().parents[2]))

from maths.euler_method import explicit_euler
from maths.euler_modified import euler_modified
from maths.numerical_analysis.runge_kutta import runge_kutta

type ODE = Callable[[float, float], float]
type InputCase = tuple[float, float, float, float]
type Solver = Callable[[ODE, float, float, float, float], np.ndarray]

SHARED_INPUTS: tuple[InputCase, ...] = (
(1.0, 0.0, 0.1, 1.0),
(1.0, 0.0, 0.05, 1.0),
(1.0, 0.0, 0.025, 1.0),
(2.0, 0.0, 0.1, 0.5),
(-1.0, 0.0, 0.1, 0.5),
(0.5, 0.0, 0.05, 0.5),
(3.0, 0.2, 0.1, 0.7),
(-2.0, 0.1, 0.05, 0.6),
(1.5, -0.2, 0.1, 0.3),
(0.25, 0.25, 0.05, 0.75),
(-0.5, -0.5, 0.05, 0.0),
)

SOLVERS: tuple[tuple[str, Solver], ...] = (
("explicit_euler", explicit_euler),
("euler_modified", euler_modified),
("runge_kutta", runge_kutta),
)


def derivative(_x: float, y: float) -> float:
"""Return the derivative for dy/dx = y."""
return y


@pytest.mark.parametrize(("y0", "x0", "step_size", "x_end"), SHARED_INPUTS)
def test_solvers_on_shared_inputs(
y0: float, x0: float, step_size: float, x_end: float
) -> None:
"""All solvers accept common positional inputs and approximate exp(x)."""
for _, solver in SOLVERS:
values = solver(derivative, y0, x0, step_size, x_end)
expected_steps = math.ceil((x_end - x0) / step_size)
exact_values = [
y0 * math.exp(index * step_size) for index in range(expected_steps + 1)
]

assert isinstance(values, np.ndarray)
assert len(values) == expected_steps + 1
assert values[0] == y0
assert values == pytest.approx(exact_values, rel=0.06, abs=1e-12)


def test_errors_show_expected_convergence_orders() -> None:
"""Halving h reduces global error by factors near 1/2, 1/4, and 1/16."""
for _, solver in SOLVERS:
errors = [
abs(float(solver(derivative, 1.0, 0.0, step_size, 1.0)[-1]) - math.e)
for step_size in (0.1, 0.05, 0.025)
]

assert errors[0] > errors[1] > errors[2]
ratio_1 = errors[1] / errors[0]
ratio_2 = errors[2] / errors[1]

if solver is explicit_euler:
assert 0.45 < ratio_1 < 0.53
assert 0.45 < ratio_2 < 0.53
elif solver is euler_modified:
assert 0.22 < ratio_1 < 0.28
assert 0.22 < ratio_2 < 0.28
else:
assert 0.05 < ratio_1 < 0.08
assert 0.05 < ratio_2 < 0.08


def benchmark_solvers(repeats: int = 5, batches: int = 1000) -> dict[str, float]:
"""Return median microseconds per solve over the same shared input cases."""
timings: dict[str, float] = {}
for name, solver in SOLVERS:
samples = []
for _ in range(repeats):
start = perf_counter()
for _ in range(batches):
for case in SHARED_INPUTS:
solver(derivative, *case)
samples.append(perf_counter() - start)
timings[name] = (
statistics.median(samples) * 1_000_000 / (batches * len(SHARED_INPUTS))
)
return timings


def main() -> None:
"""Print the benchmark medians for the shared inputs."""
for name, microseconds in benchmark_solvers().items():
print(f"{name}: {microseconds:.2f} us/solve")


if __name__ == "__main__":
main()