TExcelTAD
Home › Calculus in Depth › Direction Fields and Euler's Method

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 y′=f(t,y)y' = f(t, y) tells you the slope of the solution through every point, without solving anything. Draw a short segment with slope f(t,y)f(t, y) 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, f(t,y)=cf(t, y) = c, are isoclines; they help sketch by hand. For y′=t−yy' = t - y, the isoclines are the lines y=t−cy = t - c, and the isocline c=1c = 1, the line y=t−1y = t - 1, is itself a solution (its slope is 1 everywhere). All other solutions approach it.

python · try it yourself
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 y=t−1+(y0+1)e−ty = t - 1 + (y_0 + 1)e^{-t} come from Linear Equations; here they only confirm that the curves follow the field.

Autonomous equations y′=f(y)y' = f(y) have a field that is the same on every vertical line, so a one-dimensional phase line suffices: mark the zeros of ff (equilibria) and an arrow up where f>0f > 0, down where f<0f < 0. An equilibrium is stable when arrows on both sides point toward it.

Euler's method

Start at (t0,y0)(t_0, y_0), walk along the tangent line for a step hh, recompute the slope, repeat:

tn+1=tn+hyn+1=yn+h f(tn,yn)\begin{aligned} t_{n+1} &= t_n + h \\ y_{n+1} &= y_n + h\,f(t_n, y_n) \end{aligned}

It is the linear approximation y(t+h)≈y(t)+h y′(t)y(t + h) \approx y(t) + h\,y'(t) applied over and over.

python · try it yourself
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 = err
h = 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 hh roughly halves the error: Euler's method is first order.

Why the error is O(h)O(h)

Local error. By Taylor's theorem, y(t+h)=y(t)+h y′(t)+h22y′′(ξ)y(t + h) = y(t) + h\,y'(t) + \frac{h^2}{2} y''(\xi). One Euler step from the exact value therefore misses by at most Mh2/2M h^2/2, where ∣y′′∣≤M\lvert y'' \rvert \le M.

Propagation. If ∣∂f/∂y∣≤L\lvert \partial f/\partial y \rvert \le L, an error ene_n at step nn becomes at most (1+hL) en(1 + hL)\,e_n after the next step, plus the new local error:

en+1≤(1+hL) en+Mh22e_{n+1} \le (1 + hL)\,e_n + \frac{M h^2}{2}

Unrolling this recurrence (a geometric sum) and using (1+hL)n≤enhL=eL(t−t0)(1 + hL)^n \le e^{nhL} = e^{L(t - t_0)} gives

en≤Mh2L⋅(eL(tn−t0)−1)=O(h)e_n \le \frac{M h}{2L} \cdot \left(e^{L(t_n - t_0)} - 1\right) = O(h)

N=T/hN = T/h steps, each contributing O(h2)O(h^2), add up to O(h)O(h). Methods with a higher-order Taylor match, such as Runge–Kutta 4 (O(h4)O(h^4)), are what scipy.integrate.solve_ivp uses (SciPy ODEs).

Stability: when small steps are not small enough

On the decay equation y′=−λyy' = -\lambda y (λ>0\lambda > 0) the true solution shrinks, but Euler gives yn+1=(1−hλ) yny_{n+1} = (1 - h\lambda)\,y_n, so yn=(1−hλ)ny0y_n = (1 - h\lambda)^n y_0. That shrinks only if ∣1−hλ∣<1\lvert 1 - h\lambda \rvert < 1, that is h<2/λh < 2/\lambda. Beyond that, the numbers oscillate and explode even though the error bound above still technically holds: its constant eLTe^{LT} is astronomically large. Equations with a large λ\lambda (stiff equations: stiff springs, fast chemistry) force tiny steps or an implicit method.

python · try it yourself
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·dt written 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 hh below the stability limit regardless of frame rate (Fixed Timestep).
  • Learning rates. Gradient descent on a quadratic loss with curvature λ\lambda is exactly the decay example above: it diverges when the learning rate exceeds 2/λ2/\lambda. That is the textbook explanation of "loss exploded, lower the learning rate".

Exercises

Exercise 1: Two steps by hand

Use Euler's method with h=0.1h = 0.1 on y′=y+ty' = y + t, y(0)=1y(0) = 1 to estimate y(0.2)y(0.2). The exact solution is y=2et−t−1y = 2e^{t} - t - 1; what is the error?

Answer

y(0.2)≈1.22y(0.2) \approx 1.22; exact ≈1.242806\approx 1.242806, error ≈0.0228\approx 0.0228.

Solution
y1=1+0.1 (1+0)=1.1y2=1.1+0.1 (1.1+0.1)=1.22exact: 2e0.2−1.2≈2(1.221403)−1.2=1.242806\begin{aligned} y_1 &= 1 + 0.1\,(1 + 0) = 1.1 \\ y_2 &= 1.1 + 0.1\,(1.1 + 0.1) = 1.22 \\ \text{exact: } &2e^{0.2} - 1.2 \approx 2(1.221403) - 1.2 = 1.242806 \end{aligned}

Exercise 2: Phase line

Draw the phase line of y′=y2−4y' = y^2 - 4. Which equilibria are stable? What happens to the solution with y(0)=3y(0) = 3?

Answer

Equilibria y=−2y = -2 (stable) and y=2y = 2 (unstable). From y(0)=3y(0) = 3 the solution increases without bound (in fact it blows up in finite time).

Solution

y2−4>0y^2 - 4 > 0 for y<−2y < -2 and y>2y > 2 (arrows up), <0< 0 for −2<y<2-2 < y < 2 (arrows down). Arrows point toward −2-2 from both sides and away from 22. Above 2, y′≥y2−4y' \ge y^2 - 4 grows faster than linearly, like y′=y2y' = y^2, which blows up in finite time.

Exercise 3: Stability limit

Euler's method is used on y′=−50yy' = -50y. What is the largest stable step size?

Answer

h<2/50=0.04h < 2/50 = 0.04

Solution

yn+1=(1−50h) yny_{n+1} = (1 - 50h)\,y_n shrinks iff ∣1−50h∣<1\lvert 1 - 50h \rvert < 1, i.e. 0<h<0.040 < h < 0.04.

Exercise 4: Euler computes e

Apply Euler's method to y′=yy' = y, y(0)=1y(0) = 1 on [0,1][0, 1] with n=10,100,1000n = 10, 100, 1000 steps. Show the result is (1+1/n)n(1 + 1/n)^n and that the error is close to e/(2n)e/(2n).

Answer

2.5937422.593742, 2.7048142.704814, 2.7169242.716924; errors ≈0.1245\approx 0.1245, 0.013470.01347, 0.0013580.001358, close to e/(2n)=0.1359e/(2n) = 0.1359, 0.013590.01359, 0.0013590.001359.

Solution

Each step multiplies by (1+h)(1 + h) with h=1/nh = 1/n, so yn=(1+1/n)ny_n = (1 + 1/n)^n. Expanding nln⁡(1+1/n)=1−1/(2n)+…n \ln(1 + 1/n) = 1 - 1/(2n) + \ldots gives e−(1+1/n)n≈e/(2n)e - (1 + 1/n)^n \approx e/(2n).

python · try it yourself
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 t=1t = 1 with h=0.1h = 0.1. Roughly what error do you expect with h=0.025h = 0.025?

  1. 0.005
  2. 0.02
  3. 0.04
  4. 0.0003

In a direction field for y′=f(t,y)y' = f(t, y), what is drawn at the point (t,y)(t, y)?

  1. The value of the solution
  2. A segment with slope f(t,y)f(t, y)
  3. The curvature of the solution
  4. The isocline

Why does explicit Euler on y′=−λyy' = -\lambda y blow up for h>2/λh > 2/\lambda?

  1. Rounding errors
  2. The local error is O(h2)O(h^2)
  3. Each step multiplies yy by 1−hλ1 - h\lambda, whose absolute value exceeds 1
  4. The equation has no solution