An attractor visualizer does one thing over and over: take the state, ask the equations for a velocity, and move a short distance. The question is how to choose that move. Explicit Euler is the obvious choice and a poor one. Fourth-order Runge-Kutta (RK4) costs four evaluations per step and is the default in almost every attractor renderer, including my gestural attractor project. This page derives the usual methods, measures their error on a problem with a known answer, and ends with what I actually do when drawing.

A computer follows a curve by taking many small straight steps. Image: HilberTraum, CC BY-SA 4.0, via Wikimedia Commons.

Mental Model

  • A step of size estimates the average slope over the interval. The methods differ in how good that estimate is.
  • A method of order has global error . Halving divides the error by .
  • Accuracy and stability are different limits. A method can be accurate for small and still blow up once crosses a threshold set by the fastest time scale.
  • For a chaotic system the individual trajectory is wrong after a while no matter what. The question is whether the picture is still right.

1. The Methods

For , step from to with step .

Explicit Euler follows the slope at the start of the interval:

Midpoint (a second-order Runge-Kutta) takes a half step to find the slope in the middle, then uses it for the whole step:

RK4 blends four slopes, with the two midpoint slopes counted twice:

2. Local and Global Error

Comparing with the Taylor series of the true solution shows that Euler matches terms up to , so its local error (the error made in one step from an exact start) is . Midpoint matches through , local error . RK4 matches through , local error .

Reaching a fixed time takes steps and local errors accumulate, so the global error loses one power: for Euler, for midpoint, for RK4. The names “first, second and fourth order” refer to the global exponent.

3. Measuring the Order

The logistic ODE has the exact solution . With and the exact value is .

import numpy as np
 
f = lambda y: y * (1 - y)
exact = 1 / (1 + 9 * np.exp(-2.0))
 
def euler(y, h):
    return y + h * f(y)
 
def midpoint(y, h):
    return y + h * f(y + 0.5 * h * f(y))
 
def rk4(y, h):
    k1 = f(y); k2 = f(y + h / 2 * k1); k3 = f(y + h / 2 * k2); k4 = f(y + h * k3)
    return y + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
 
for step in (euler, midpoint, rk4):
    errs = []
    for n in (4, 8, 16, 32, 64):
        y = 0.1
        for _ in range(n):
            y = step(y, 2.0 / n)
        errs.append(abs(y - exact))
    orders = np.log2(np.array(errs[:-1]) / np.array(errs[1:]))
    print(step.__name__, f"{errs[-1]:.2e}", orders.round(2))

Running this gives final errors at of for Euler, for midpoint and for RK4. The measured orders, of the error ratio per halving, settle at , and (the last row for RK4 reads ). RK4 with just 4 steps (, error ) beats Euler with 64 steps, so the four evaluations per step pay for themselves.

4. Step Size and Stability

Take the test problem . Euler gives , so it decays only when , that is . At the amplification factor is and the solution grows even though the true one decays. RK4 replaces by the Taylor polynomial of up to the fourth term, which is stable up to , so .

This is the constraint that matters for attractor rendering. Along the Lorenz attractor the Jacobian’s largest eigenvalue magnitude reaches about (I sampled it along a trajectory), which puts the linear limit for RK4 near . Euler is worse than its linear limit suggests: oscillating modes (complex eigenvalues) get amplified by for every when , so Euler adds energy to every spiral it passes. Integrating the standard Lorenz system from gave:

MethodStepResult
Euler0.01stays on the attractor, but reaches 51 instead of about 46
Euler0.03overflows to NaN (it already failed at 0.025)
RK40.03stays on the attractor
RK40.12still bounded; 0.15 diverges

Measured against a high-accuracy reference (SciPy’s DOP853 at tolerance ), the trajectory deviated by 1 unit after for Euler at , for Euler at , and for RK4 at . Chaos limits that last number, as the Lyapunov page explains.

5. Symplectic Integrators

For conservative orbit problems, such as planets or a frictionless oscillator, even RK4 drifts. A symplectic integrator preserves the geometric structure of Hamiltonian flow. Energy is not conserved exactly, but it oscillates within a band instead of drifting.

For the harmonic oscillator (energy ), compare three methods at over 1000 time units:

def step_euler(q, p, h):   return q + h * p, p - h * q          # energy grows
def step_symp(q, p, h):    p -= h * q; return q + h * p, p      # symplectic Euler
# RK4 on (q, p) is the third comparison

The final energies I got are for explicit Euler (it multiplies energy by every step), for symplectic Euler and for RK4. Symplectic Euler is only first-order and its energy stays between and forever, while RK4 loses energy slowly and monotonically, so over long enough runs RK4 eventually loses. Velocity Verlet, the leapfrog variant, is second-order and also symplectic, and is the usual choice for gravity simulations.

None of this applies to the Lorenz equations, which are dissipative. Symplectic methods are for systems with zero divergence.

6. Practical Advice for Rendering Attractors

  • Use RK4 with to for Lorenz-like systems (time scale about 1) and take several substeps per frame. Draw every substep or every few for smoother trails.
  • Check the fastest rate in the Jacobian and keep well below . Systems with large parameters (Chen, Dadras) need smaller steps than Thomas or Aizawa.
  • Accept that the trajectory is not exact. Shadowing, the property that a numerical orbit stays near some true orbit, means the picture is faithful even when the specific path is not. This is why Euler at still draws a recognizable Lorenz butterfly.
  • Do the arithmetic in float32 on the GPU only if you must. Rounding noise acts like a tiny random push, which is harmless for pictures and wrong for measuring Lyapunov exponents.
  • Adaptive steppers (scipy.integrate.solve_ivp) are overkill for real-time drawing, but are the right tool for producing reference data.

Common mistake

Making Euler more accurate by shrinking is almost always a worse trade than switching to RK4. On the test above Euler needs roughly 4000 steps to match the error RK4 reaches in 4.