Foundations to FrontierPart VII: Applied mathematics and computationBezhig

A06: Differential equations, stability, and optimization

5 exercises, each with a complete solution. 1 figure. 1 code listing. 1 note from the engine.

On this page
  1. A. Prerequisites and observable goals
  2. B. The central question: how does a local rule determine an evolving system?
  3. C. Euler’s method is a tangent approximation in time
  4. D. RK4 samples several slopes, but does not eliminate all error
  5. E. Stability asks whether numerical error is amplified
  6. F. Optimization is an iterative computation with its own conditions
  7. G. Independent practice
  8. H. Complete solutions: A06
  9. I. Retention and readiness

A. Prerequisites and observable goals#

Before

Modules 09–17 and 25; A01–A02 vectors and matrices; A05 numerical error.

After

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 y′(t)=f(t,y(t))y'(t)=f(t,y(t)) and an initial state y(t0)=y0y(t_0)=y_0. 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 ff 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 x′′=−xx''=-x, define v=x′v=x'. Then

 d dt(xv)=(v−x),(x(0),v(0))=(1,0).\frac{\dd}{\dd t}\begin{pmatrix}x\\v\end{pmatrix} =\begin{pmatrix}v\\-x\end{pmatrix},\qquad (x(0),v(0))=(1,0).

The exact solution is (cos⁡t,−sin⁡t)(\cos t,-\sin t). Verify it by differentiating and checking the initial state. Its energy E=(x2+v2)/2E=(x^2+v^2)/2 is constant because E′=xx′+vv′=xv+v(−x)=0E'=xx'+vv'=xv+v(-x)=0. These analytical facts provide independent validation targets for a numerical solver.

C. Euler’s method is a tangent approximation in time#

For step h>0h>0, explicit Euler uses

yn+1=yn+hf(tn,yn),tn+1=tn+h.y_{n+1}=y_n+h f(t_n,y_n),\qquad t_{n+1}=t_n+h.

The increment has the state’s units because derivative units multiplied by time give state units. For y′=−yy'=-y, y(0)=1y(0)=1, and h=0.1h=0.1, the first values are 1,0.9,0.811,0.9,0.81. The exact value at t=0.2t=0.2 is e−0.2≈0.818731e^{-0.2}\approx0.818731. Euler is close over this short interval but not exact. Under appropriate smoothness and stability conditions, the local truncation error is O(h2)O(h^2) and the accumulated global error over a fixed interval is O(h)O(h). Local and global orders are not interchangeable.

Euler’s method walks along tangents. For y′=−yy'=-y from y(0)=1y(0)=1, each step follows the slope at its starting point. With h=0.5h=0.5 the value at t=2t=2 is off by 0.0730.073; with h=0.25h=0.25 it is off by 0.0350.035. Halving the step roughly halves the error, the mark of a first-order method.

D. RK4 samples several slopes, but does not eliminate all error#

Classical fourth-order Runge–Kutta computes

k1=f(tn,yn),k2=f(tn+h/2,yn+hk1/2),k3=f(tn+h/2,yn+hk2/2),k4=f(tn+h,yn+hk3),yn+1=yn+h6(k1+2k2+2k3+k4).\begin{align*} k_1&=f(t_n,y_n),\\ k_2&=f(t_n+h/2,y_n+hk_1/2),\\ k_3&=f(t_n+h/2,y_n+hk_2/2),\\ k_4&=f(t_n+h,y_n+hk_3),\\ y_{n+1}&=y_n+\frac h6(k_1+2k_2+2k_3+k_4). \end{align*}

Here each kik_i is a derivative, not an already multiplied step increment. Some textbooks define kik_i with hh included; either convention can work, but mixing them multiplies by hh twice. For sufficiently smooth problems over a fixed interval and appropriate step sizes, global error is O(h4)O(h^4). Halving hh should then reduce the dominant error by approximately 24=162^4=16, 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 y′=−λyy'=-\lambda y with λ>0\lambda>0, Euler gives yn+1=(1−λh)yny_{n+1}=(1-\lambda h)y_n. The exact solution decays, so a basic numerical stability requirement is ∣1−λh∣<1|1-\lambda h|<1, or 0<h<2/λ0<h<2/\lambda. With λ=1000\lambda=1000 and h=0.003h=0.003, the multiplier is −2-2, 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 (xn+1,vn+1)=(xn+hvn,vn−hxn)(x_{n+1},v_{n+1})=(x_n+hv_n,v_n-hx_n). Its energy satisfies

xn+12+vn+12=(1+h2)(xn2+vn2).x_{n+1}^2+v_{n+1}^2=(1+h^2)(x_n^2+v_n^2).

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 F(x)F(x), gradient descent uses xk+1=xk−α∇F(xk)x_{k+1}=x_k-\alpha\nabla F(x_k). 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 F(x)=12λx2F(x)=\frac12\lambda x^2, the update is xk+1=(1−αλ)xkx_{k+1}=(1-\alpha\lambda)x_k, so convergence to zero requires 0<α<2/λ0<\alpha<2/\lambda. The resemblance to the Euler stability calculation is meaningful: both are iterative amplification analyses.

For a positive-definite quadratic F(x)=12xTAx−bTxF(x)=\frac12x^TAx-b^Tx, the gradient is Ax−bAx-b. A constant step less than 2/λmax⁡(A)2/\lambda_{\max}(A) 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 H(xk)pk=−∇F(xk)H(x_k)p_k=-\nabla F(x_k) for a step and then updates xk+1=xk+pkx_{k+1}=x_k+p_k, 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 H−1H^{-1}.

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.

A06.01FSolution

Carry out two explicit Euler steps for y′=−yy'=-y, y(0)=1y(0)=1, with h=0.1h=0.1. Compare with the exact values at the same times and state the sign of the error.

A06.02CSolution

For y′=−1000yy'=-1000y, determine the explicit Euler stability interval for positive step sizes. What happens at h=0.002h=0.002 and h=0.003h=0.003? Distinguish neutral magnitude from accurate decay.

A06.03CSolution

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.

A06.04TSolution

Minimize F(x)=(x−3)2F(x)=(x-3)^2 by constant-step gradient descent. Derive the convergence range for α\alpha and the iterate after one step from x0=0x_0=0 when α=1/4\alpha=1/4. Then minimize the same function on 0≤x≤20\le x\le2 and explain the constrained answer.

A06.05LabSolution

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 y′=−yy'=-y with e−te^{-t}, then compare oscillator trajectories with (cos⁡t,−sin⁡t)(\cos t,-\sin t). Measure a refinement ratio rather than reporting only a final coordinate.

Optional small hints

A06.02: apply ∣1−1000h∣<1|1-1000h|<1. A06.03: expand both squared updated components before canceling cross terms. A06.04: analyze the error ek=xk−3e_k=x_k-3.

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 y1=1+0.1(−1)=0.9y_1=1+0.1(-1)=0.9 and y2=0.9+0.1(−0.9)=0.81y_2=0.9+0.1(-0.9)=0.81. Exact values are e−0.1≈0.904837e^{-0.1}\approx0.904837 and e−0.2≈0.818731e^{-0.2}\approx0.818731. Numerical minus exact errors are approximately −0.004837-0.004837 and −0.008731-0.008731. Over these steps Euler decays too quickly. The comparison evaluates both trajectories at identical times and respects the initial condition.

Back to A06.01
A06.02Show solution

The amplification factor controls the diagnosis

∣1−1000h∣<1|1-1000h|<1 gives 0<h<0.0020<h<0.002. At h=0.002h=0.002, the factor is −1-1, so values alternate without decaying in magnitude; this is a boundary case, not a faithful approximation to exponential decay. At h=0.003h=0.003, the factor is −2-2, 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.02
A06.03Show solution

A precise conservation check

Expand:

(x+hv)2+(v−hx)2=x2+2hxv+h2v2+v2−2hxv+h2x2=(1+h2)(x2+v2).(x+hv)^2+(v-hx)^2=x^2+2hxv+h^2v^2+v^2-2hxv+h^2x^2 =(1+h^2)(x^2+v^2).

The cross terms cancel, but the h2h^2 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.03
A06.04Show solution

Analyze the error recurrence

F′(x)=2(x−3)F'(x)=2(x-3), so ek+1=(1−2α)eke_{k+1}=(1-2\alpha)e_k. Convergence requires ∣1−2α∣<1|1-2\alpha|<1, hence 0<α<10<\alpha<1. With α=1/4\alpha=1/4 and x0=0x_0=0, x1=0−(1/4)(−6)=1.5x_1=0-(1/4)(-6)=1.5. On [0,2][0,2], the unconstrained minimizer 3 is infeasible. The function decreases throughout the interval because F′(x)<0F'(x)<0 there, so the constrained minimum is at x=2x=2, value 1. A projected method clips trial points to [0,2][0,2]; it must not report an infeasible point merely because its gradient is zero.

Back to A06.04
A06.05Show solution

Reference solver and interpretation

code/solutions/ode_lab.pyPython
"""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 hh 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.05

I. 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.