A06: Differential equations, stability, and optimization
On this page
- A. Prerequisites and observable goals
- B. The central question: how does a local rule determine an evolving system?
- C. Euler’s method is a tangent approximation in time
- D. RK4 samples several slopes, but does not eliminate all error
- E. Stability asks whether numerical error is amplified
- F. Optimization is an iterative computation with its own conditions
- G. Independent practice
- H. Complete solutions: A06
- I. Retention and readiness
A. Prerequisites and observable goals#
Modules 09–17 and 25; A01–A02 vectors and matrices; A05 numerical error.
Convert a differential equation into state form, carry out Euler and RK4 steps, test convergence against a known solution, analyze a simple stability restriction, and distinguish gradient descent from Newton optimization.
Level: Degree core with advanced continuation boundaries.
B. The central question: how does a local rule determine an evolving system?#
An initial-value problem specifies a derivative rule and an initial state . The solution is a function of time satisfying both. It is not obtained by treating the derivative as an ordinary variable and guessing arbitrary constants. Existence and uniqueness require conditions; continuity of and a suitable local Lipschitz condition in the state give a standard local result. A numerical trajectory is an approximation to that model, not proof that the model describes the real world.
A second-order equation becomes a first-order vector system. For the dimensionless oscillator , define . Then
The exact solution is . Verify it by differentiating and checking the initial state. Its energy is constant because . These analytical facts provide independent validation targets for a numerical solver.
C. Euler’s method is a tangent approximation in time#
For step , explicit Euler uses
The increment has the state’s units because derivative units multiplied by time give state units. For , , and , the first values are . The exact value at is . Euler is close over this short interval but not exact. Under appropriate smoothness and stability conditions, the local truncation error is and the accumulated global error over a fixed interval is . Local and global orders are not interchangeable.
D. RK4 samples several slopes, but does not eliminate all error#
Classical fourth-order Runge–Kutta computes
Here each is a derivative, not an already multiplied step increment. Some textbooks define with included; either convention can work, but mixing them multiplies by twice. For sufficiently smooth problems over a fixed interval and appropriate step sizes, global error is . Halving should then reduce the dominant error by approximately , until rounding or another error source dominates. This is an asymptotic diagnostic, not an exact ratio for every step size.
E. Stability asks whether numerical error is amplified#
For with , Euler gives . The exact solution decays, so a basic numerical stability requirement is , or . With and , the multiplier is , so the numerical values alternate and grow even though the exact solution decays. This is not a sign that the physical model suddenly became unstable.
For the undamped oscillator, Euler gives . Its energy satisfies
Therefore it adds energy at every positive step. A smaller step reduces finite-time error but does not make explicit Euler a long-term energy-preserving oscillator integrator. Symplectic methods, implicit methods, adaptive error control, and stiffness are important continuation topics. T05 introduces velocity Verlet for a bounded conservative model rather than pretending that one solver is best for all equations.
F. Optimization is an iterative computation with its own conditions#
To minimize a differentiable objective , gradient descent uses . The negative gradient is a local steepest-descent direction in the Euclidean norm, but a step that is too large can increase the objective. For , the update is , so convergence to zero requires . The resemblance to the Euler stability calculation is meaningful: both are iterative amplification analyses.
For a positive-definite quadratic , the gradient is . A constant step less than gives convergence in exact arithmetic, while a wide eigenvalue spread can make it slow. Feature scaling and preconditioning can change the geometry. For nonconvex objectives, a zero gradient need not indicate a global minimum.
Newton optimization solves for a step and then updates , possibly with a line search or damping. This is not the same notation as scalar root finding, though it applies root finding to the gradient. An indefinite Hessian can yield a non-descent direction. Do not explicitly invert a large Hessian just because the mathematical formula can be written with .
For a box constraint, projected gradient descent replaces the unconstrained trial point by its Euclidean projection onto the box, componentwise clipping. General constraints need more analysis. Lagrange multipliers give necessary conditions under suitable regularity, not automatic global optimality. Module 38 supplies the geometric constrained-optimization foundation. The lab in this module focuses on ODE integration; optimization is exercised analytically here and computationally in T03.
G. Independent practice#
F foundation C standard course work T transfer S optional stretch L runnable lab or project. Attempt the complete set before opening its solutions.
Carry out two explicit Euler steps for , , with . Compare with the exact values at the same times and state the sign of the error.
For , determine the explicit Euler stability interval for positive step sizes. What happens at and ? Distinguish neutral magnitude from accurate decay.
Derive the oscillator energy-growth factor for explicit Euler. Explain why testing only a visually plausible short animation is weak validation of a scientific simulation.
Minimize by constant-step gradient descent. Derive the convergence range for and the iterate after one step from when . Then minimize the same function on and explain the constrained answer.
Implement integrate in ode_lab.py for explicit Euler and RK4 on finite-dimensional state tuples. Validate time bounds, step count, derivative shape, and finite values. Compare with , then compare oscillator trajectories with . Measure a refinement ratio rather than reporting only a final coordinate.
Optional small hints
A06.02: apply . A06.03: expand both squared updated components before canceling cross terms. A06.04: analyze the error .
H. Complete solutions: A06#
Compare the first step where your work differs. A corrected answer is not yet an independent success.
A06.01Show solution
A first-order approximation
The steps are and . Exact values are and . Numerical minus exact errors are approximately and . Over these steps Euler decays too quickly. The comparison evaluates both trajectories at identical times and respects the initial condition.
Back to A06.01A06.02Show solution
The amplification factor controls the diagnosis
gives . At , the factor is , so values alternate without decaying in magnitude; this is a boundary case, not a faithful approximation to exponential decay. At , the factor is , so magnitudes double every step. Both numerical behaviors differ qualitatively from the exact decaying solution. An accuracy target can require a much smaller step than the stability limit.
Back to A06.02A06.03Show solution
A precise conservation check
Expand:
The cross terms cancel, but the terms remain positive. Energy grows geometrically by this factor in exact arithmetic. A short animation can hide the drift through scale, camera movement, or a short time horizon. A scientific check compares with the exact solution, tracks invariants, changes step size, and states units and modeling assumptions. Passing one visual inspection is not validation of a dynamical model.
Back to A06.03A06.04Show solution
Analyze the error recurrence
, so . Convergence requires , hence . With and , . On , the unconstrained minimizer 3 is infeasible. The function decreases throughout the interval because there, so the constrained minimum is at , value 1. A projected method clips trial points to ; it must not report an infeasible point merely because its gradient is zero.
Back to A06.04A06.05Show solution
Reference solver and interpretation
"""A06.05: fixed-step Euler and RK4 for finite-dimensional ODE systems."""
import math
from collections.abc import Callable
def integrate(f: Callable, y0: tuple[float, ...], t0: float, t1: float,
steps: int, method: str = "rk4") -> list[tuple[float, tuple]]:
if type(steps) is not int or steps < 1 or not y0:
raise ValueError("positive integer steps and nonempty state required")
if not all(math.isfinite(x) for x in (t0, t1, *y0)) or t1 <= t0:
raise ValueError("finite data and increasing time required")
if method not in {"euler", "rk4"}:
raise ValueError("unknown integration method")
h = (t1 - t0) / steps
y = tuple(float(x) for x in y0)
out = [(t0, y)]
def derivative(t, state):
d = tuple(f(t, state))
if len(d) != len(y0) or any(not math.isfinite(x) for x in d):
raise ValueError("invalid derivative shape or value")
return d
def add(state, d, factor):
return tuple(a + factor * b for a, b in zip(state, d))
for i in range(steps):
t = t0 + i * h
k1 = derivative(t, y)
if method == "euler":
y = add(y, k1, h)
else:
k2 = derivative(t + h / 2, add(y, k1, h / 2))
k3 = derivative(t + h / 2, add(y, k2, h / 2))
k4 = derivative(t + h, add(y, k3, h))
y = tuple(v + h * (a + 2*b + 2*c + d) / 6
for v, a, b, c, d in zip(y, k1, k2, k3, k4))
if any(not math.isfinite(x) for x in y):
raise ArithmeticError("nonfinite integration state")
out.append((t0 + (i + 1) * h, y))
return out
if __name__ == "__main__":
path = integrate(lambda t, y: (-y[0],), (1.,), 0., 1., 10)
print(path[-1], "exact:", math.exp(-1))The solver represents the state consistently as a tuple and checks that every derivative has the same dimension. Each RK4 stage uses the required intermediate time and state, and the final weighted combination multiplies by exactly once. The tests compare known solutions with explicit tolerances and verify a roughly sixteenfold reduction in the RK4 decay error when the step is halved in a suitable regime. They also reject malformed derivatives and invalid methods. This is a fixed-step teaching solver: it has no adaptive controller, event detection, stiffness handling, or safety-critical assurance. J04 develops a complete command-line validation tool around it; T04 and T05 show how model choice changes the testing obligations.
Back to A06.05I. Retention and readiness#
Retrieve the tangent-line approximation, the chain rule, and eigenvalue growth. Advance when you can distinguish local error, global error, stability, and modeling error, and when a solver’s output comes with an analytical or conservation-based check rather than a claim that the plot looks right.