Direction Fields and Euler's Method
Most differential equations have no formula for their solutions, but you can still see them and compute them. A direction field draws the equation's slopes, Euler's method follows them in small steps, and an error analysis tells you how far to trust the result. This lesson proves that Euler's method is first-order accurate and shows the instability that breaks naive game physics.
The survey course covers the method briefly in Numerical Solutions: Euler and RK4.
Direction fields
The equation tells you the slope of the solution through every point, without solving anything. Draw a short segment with slope at each point of a grid: that is the direction field (slope field). A solution curve is a curve that is tangent to the field everywhere, so you can sketch solutions by "following the arrows".
Curves where the slope is constant, , are isoclines; they help sketch by hand. For , the isoclines are the lines , and the isocline , the line , is itself a solution (its slope is 1 everywhere). All other solutions approach it.
import numpy as np
import matplotlib.pyplot as plt
f = lambda t, y: t - y
T, Y = np.meshgrid(np.linspace(0, 4, 17), np.linspace(-2, 3, 17))
S = f(T, Y)
L = np.sqrt(1 + S**2)
plt.figure(figsize=(6, 4))
plt.quiver(T, Y, 1 / L, S / L, angles="xy", color="0.6", width=0.003)
ts = np.linspace(0, 4, 200)
for y0 in [-2, -1, 0, 1, 2, 3]:
plt.plot(ts, ts - 1 + (y0 + 1) * np.exp(-ts), label=f"y(0) = {y0}")
plt.title("y′ = t − y: direction field and solutions"); plt.xlabel("t"); plt.ylabel("y")
plt.ylim(-2, 3); plt.legend(fontsize=7); plt.grid(alpha=0.3)
print("plotted the direction field of y' = t - y with six solution curves")plotted the direction field of y' = t - y with six solution curves
The exact solutions come from Linear Equations; here they only confirm that the curves follow the field.
Autonomous equations have a field that is the same on every vertical line, so a one-dimensional phase line suffices: mark the zeros of (equilibria) and an arrow up where , down where . An equilibrium is stable when arrows on both sides point toward it.
Euler's method
Start at , walk along the tangent line for a step , recompute the slope, repeat:
It is the linear approximation applied over and over.
import math
f = lambda t, y: t - y
exact = lambda t: t - 1 + 2 * math.exp(-t) # y(0) = 1
def euler(f, t0, y0, h, n):
t, y = t0, y0
for _ in range(n):
y += h * f(t, y)
t += h
return y
prev = None
for h in [0.5, 0.25, 0.125, 0.0625]:
err = abs(euler(f, 0, 1, h, round(2 / h)) - exact(2))
ratio = f" ratio {prev / err:.2f}" if prev else ""
print(f"h = {h:<6} error at t=2: {err:.5f}{ratio}")
prev = errh = 0.5 error at t=2: 0.14567
h = 0.25 error at t=2: 0.07044 ratio 2.07
h = 0.125 error at t=2: 0.03454 ratio 2.04
h = 0.0625 error at t=2: 0.01709 ratio 2.02
Halving roughly halves the error: Euler's method is first order.
Why the error is
Local error. By Taylor's theorem, . One Euler step from the exact value therefore misses by at most , where .
Propagation. If , an error at step becomes at most after the next step, plus the new local error:
Unrolling this recurrence (a geometric sum) and using gives
steps, each contributing , add up to . Methods with a higher-order Taylor match, such as Runge–Kutta 4 (), are what scipy.integrate.solve_ivp uses (SciPy ODEs).
Stability: when small steps are not small enough
On the decay equation () the true solution shrinks, but Euler gives , so . That shrinks only if , that is . Beyond that, the numbers oscillate and explode even though the error bound above still technically holds: its constant is astronomically large. Equations with a large (stiff equations: stiff springs, fast chemistry) force tiny steps or an implicit method.
lam = 10.0
for h in [0.05, 0.15, 0.25]:
y, path = 1.0, []
for _ in range(6):
y = (1 - h * lam) * y
path.append(f"{y:8.3f}")
print(f"h = {h:4}: factor {1 - h * lam:5.2f} |", " ".join(path))h = 0.05: factor 0.50 | 0.500 0.250 0.125 0.062 0.031 0.016
h = 0.15: factor -0.50 | -0.500 0.250 -0.125 0.062 -0.031 0.016
h = 0.25: factor -1.50 | -1.500 2.250 -3.375 5.062 -7.594 11.391
In software
- Explicit Euler in game loops.
vel += acc·dt; pos += vel·dtwritten in the "wrong" order (position first, with the old velocity) is explicit Euler, and on a spring it adds energy every frame until the simulation explodes. Swapping the two lines gives semi-implicit (symplectic) Euler, which keeps the energy bounded at the same cost. That one-line difference is why engines use it (Integrators, Physics Integration in Game Loops). - Fixed time steps keep below the stability limit regardless of frame rate (Fixed Timestep).
- Learning rates. Gradient descent on a quadratic loss with curvature is exactly the decay example above: it diverges when the learning rate exceeds . That is the textbook explanation of "loss exploded, lower the learning rate".
Exercises
Exercise 1: Two steps by hand
Use Euler's method with on , to estimate . The exact solution is ; what is the error?
Answer
; exact , error .
Solution
Exercise 2: Phase line
Draw the phase line of . Which equilibria are stable? What happens to the solution with ?
Answer
Equilibria (stable) and (unstable). From the solution increases without bound (in fact it blows up in finite time).
Solution
for and (arrows up), for (arrows down). Arrows point toward from both sides and away from . Above 2, grows faster than linearly, like , which blows up in finite time.
Exercise 3: Stability limit
Euler's method is used on . What is the largest stable step size?
Answer
Solution
shrinks iff , i.e. .
Exercise 4: Euler computes e
Apply Euler's method to , on with steps. Show the result is and that the error is close to .
Answer
, , ; errors , , , close to , , .
Solution
Each step multiplies by with , so . Expanding gives .
import math
for n in [10, 100, 1000]:
y = 1.0
for _ in range(n):
y += (1 / n) * y
print(f"n={n:4d} y={y:.6f} error={math.e - y:.4g} e/(2n)={math.e / (2 * n):.4g}")n= 10 y=2.593742 error=0.1245 e/(2n)=0.1359
n= 100 y=2.704814 error=0.01347 e/(2n)=0.01359
n=1000 y=2.716924 error=0.001358 e/(2n)=0.001359
Test yourself
Euler's method gives an error of 0.08 at with . Roughly what error do you expect with ?
- 0.005
- 0.02
- 0.04
- 0.0003
In a direction field for , what is drawn at the point ?
- The value of the solution
- A segment with slope
- The curvature of the solution
- The isocline
Why does explicit Euler on blow up for ?
- Rounding errors
- The local error is
- Each step multiplies by , whose absolute value exceeds 1
- The equation has no solution