Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Finite difference methods

ProblemSolve partial differential equations on simple domains: the heat equation , the wave equation and the Poisson equation
Devised byDifference approximations: Brook Taylor and Euler (18th century); systematic use for PDEs: Lewis Fry Richardson (1910); stability: Courant, Friedrichs and Lewy (1928), John von Neumann (1940s); Crank and Nicolson (1947); conjugate gradients: Hestenes and Stiefel (1952)
AccuracySecond order in space; first (explicit) or second (Crank-Nicolson, leapfrog) order in time
CostExplicit schemes: per step, with a stability limit on the step. Crank-Nicolson: one tridiagonal solve per step. Poisson: conjugate gradient iterations, each
Read firstFinite difference derivatives, Background: stability and conditioning
APIheat_equation_1d, wave_equation_1d, poisson_2d, solve_tridiagonal, conjugate_gradient

Overview

A partial differential equation relates the rates of change of a function in several directions: in time and space for heat flow and waves, in two space directions for the shape of a loaded membrane or an electrostatic potential. Finite difference methods replace the function by its values on a grid and each derivative by a difference quotient of neighbouring values. The PDE becomes a large set of algebraic equations, one per grid point, that a computer can solve.

The three model equations treated here are the archetypes of the three classes of second-order PDEs. The heat equation is parabolic: disturbances spread and smooth out. The wave equation is hyperbolic: disturbances travel at a finite speed without decaying. The Poisson equation is elliptic: there is no time, and the solution everywhere depends on the data everywhere. Each class brings its own numerical lesson: stability limits for parabolic problems, dispersion and the Courant condition for hyperbolic ones, and large sparse linear systems for elliptic ones.

Where it is used

Finite differences turn partial differential equations into something a computer can march forward.

  • Heat conduction. Temperatures in a wall, an engine block or a chip as it heats and cools.
  • Waves and acoustics. Vibrating strings and membranes, sound in a room and seismic waves.
  • Diffusion and transport. Spreading of a pollutant in water, dopant diffusion in semiconductor fabrication, option pricing (the Black-Scholes equation).
  • Electrostatics. The potential around electrodes by solving Poisson’s equation.

History

Difference quotients are as old as calculus, but their systematic use for PDEs began with Lewis Fry Richardson. In 1910 he computed stresses in a masonry dam by finite differences, and during the First World War, working as an ambulance driver, he attempted a numerical weather forecast by hand (published in 1922): six weeks of calculation for a six-hour forecast, which went badly wrong for reasons only understood decades later.

In 1928 Richard Courant, Kurt Friedrichs and Hans Lewy, studying the existence of solutions, discovered that an explicit scheme for the wave equation converges only if the numerical domain of dependence contains the physical one: the CFL condition. John von Neumann developed his Fourier method for analysing stability at Los Alamos in the 1940s. John Crank and Phyllis Nicolson (1947), computing heat flow in materials, introduced their unconditionally stable scheme. For elliptic problems, Magnus Hestenes and Eduard Stiefel’s conjugate gradient method (1952) became, after decades of neglect, the standard iterative solver for large symmetric systems.

The idea

Difference quotients

By Taylor’s theorem, with grid spacing ,

This central second difference is second-order accurate and uses three neighbouring points. Writing , every scheme below combines it with a difference in time.

The heat equation: explicit and implicit steps

The explicit FTCS scheme (forward in time, central in space) is

Von Neumann stability analysis substitutes a Fourier mode and finds the amplification factor . The scheme is stable, for all modes, only when . The step must therefore shrink with the square of the grid spacing: halving quadruples the number of steps. This is the stiffness of the previous entries in another guise, since the discretised heat equation is a stiff system of ODEs.

The Crank-Nicolson scheme averages the explicit and implicit (backward Euler) differences:

Its amplification factor satisfies for every , and the scheme is second order in time as well as space. Each step solves a tridiagonal system, which the Thomas algorithm (Gaussian elimination without fill-in) does in operations. For , the library’s results at :

Table 2.26. Convergence of explicit and implicit schemes for the heat equation.

grid pointsexplicit steps ()explicit errorCrank-Nicolson steps ()Crank-Nicolson error
110.1000206.16e-312.99e-2
210.0500801.52e-326.88e-3
410.02503203.79e-441.69e-3
810.012512809.46e-584.20e-4
1610.006351202.36e-5161.05e-4

Both errors fall by four when the grid is halved. The explicit scheme needs thousands of steps because of its stability limit; Crank-Nicolson reaches comparable accuracy with a step equal to the grid spacing.

The wave equation: leapfrog and the CFL condition

The leapfrog scheme uses central differences in both time and space:

The Courant number compares the distance a wave travels in one step with the grid spacing. The scheme is stable exactly when : information on the grid moves at most one cell per step, so the numerical domain of dependence contains the physical one only then (the CFL condition).

At something remarkable happens: leapfrog becomes exact on the grid, because the exact solution moves by exactly one cell per step. Below the scheme is stable but dispersive: short waves travel more slowly than long ones, and a sharp pulse sheds a wake of oscillations:

Figure 2.28. A wave pulse with Courant numbers 1 and 0.5.

The Poisson equation and the five-point stencil

On a grid with spacings , , the five-point stencil approximates

Requiring it to equal at every interior point, with the boundary values moved to the right-hand side, gives a linear system with one unknown per interior point. is enormous but very sparse (five nonzeros per row), symmetric and positive definite. Gaussian elimination would destroy the sparsity; instead the library uses conjugate gradients, which needs only the product , computed directly from the stencil without ever storing (matrix-free).

Conjugate gradients minimises the energy over a growing sequence of Krylov subspaces , choosing each new search direction -orthogonal to the previous ones so that progress is never undone. In exact arithmetic it finishes in at most steps; in practice its convergence depends on the condition number of , which grows like , so finer grids need more iterations. For on the unit square:

Table 2.27. Convergence of the five-point scheme for Poisson's equation.

gridmaximum errorratio
9 × 91/81.30e-2
17 × 171/163.22e-34.02
33 × 331/328.04e-44.01
65 × 651/642.01e-44.00
129 × 1291/1285.02e-54.00

The ratio 4.00 confirms second-order accuracy.

Algorithm

  • Heat, explicit: check ; repeat the FTCS update for the interior points, holding the ends fixed.
  • Heat, Crank-Nicolson: form the right-hand side from the explicit half step (with the boundary values added to the first and last rows) and solve the tridiagonal system by the Thomas algorithm.
  • Wave: check ; take a Taylor first step , then leapfrog.
  • Poisson: set the boundary values, move them to the right-hand side, and run conjugate gradients with the matrix-free stencil to a relative residual of .

Implementation

The Thomas algorithm:

    let mut cp = vec![0.0; n];
    let mut dp = vec![0.0; n];
    let mut denominator = b[0];
    if denominator == 0.0 {
        return Err(ErrorsJSL::RuntimeError("Zero pivot in the tridiagonal solve."));
    }
    cp[0] = c[0] / denominator;
    dp[0] = d[0] / denominator;
    for i in 1..n {
        denominator = b[i] - a[i] * cp[i - 1];
        if denominator == 0.0 {
            return Err(ErrorsJSL::RuntimeError("Zero pivot in the tridiagonal solve."));
        }
        cp[i] = c[i] / denominator;
        dp[i] = (d[i] - a[i] * dp[i - 1]) / denominator;
    }
    let mut x = dp;
    for i in (0..n - 1).rev() {
        x[i] -= cp[i] * x[i + 1];
    }
  • The explicit heat and wave solvers refuse unstable step sizes rather than return growing noise.
  • The Poisson solver stores only the grid: the stencil is applied on the fly, so memory is .
  • conjugate_gradient is public and works for any symmetric positive-definite operator given as a closure.

In practice

//! Finite differences for the heat, wave and Poisson equations.
//!
//! Run with `cargo run --release -p lib_jsl_integration --example pde_finite_differences`.

use lib_jsl_integration::pde::finite_differences::{HeatScheme, heat_equation_1d, poisson_2d, wave_equation_1d};

fn main() {
    // Heat: a rod at 0 °C with its ends held at 0 °C and 100 °C, after one time unit.
    let n = 51;
    let u0 = vec![0.0; n];
    let rod = heat_equation_1d(&u0, 1.0, 0.1, 0.01, 100, 0.0, 100.0, HeatScheme::CrankNicolson).unwrap();
    println!("rod temperature at x = 0.5 after t = 1: {:.3} °C", rod[n / 2]);
    // The explicit scheme refuses steps beyond its stability limit r = αΔt/Δx² ≤ 1/2.
    println!("explicit with r = 2.5: {:?}", heat_equation_1d(&u0, 1.0, 0.1, 0.01, 100, 0.0, 100.0, HeatScheme::Explicit).err());

    // Wave: a plucked string returns to its initial shape after one period 2L/c.
    let pluck: Vec<f64> = (0..n).map(|i| { let x = i as f64 / (n - 1) as f64; if x < 0.3 { x / 0.3 } else { (1.0 - x) / 0.7 } }).collect();
    let dx = 1.0 / (n - 1) as f64;
    let after_period = wave_equation_1d(&pluck, &vec![0.0; n], 1.0, 1.0, dx, 2 * (n - 1)).unwrap();
    let drift = pluck.iter().zip(&after_period).map(|(a, b)| (a - b).abs()).fold(0.0, f64::max);
    println!("plucked string after one period (Courant number 1): max change {drift:.1e}");

    // Poisson: −∇²u = 1 on the unit square with u = 0 on the edges (e.g. a loaded membrane).
    let u = poisson_2d(|_, _| 1.0, |_, _| 0.0, 1.0, 1.0, 65, 65).unwrap();
    println!("membrane deflection at the centre: {:.6} (series value 0.0736713...)", u[32][32]);
}

Strengths

  • Simple to derive and to implement; the grid structure makes the linear algebra cheap.
  • Well-understood stability and accuracy theory.
  • Matrix-free elliptic solvers need little memory.

Weaknesses

  • Rectangular grids fit simple domains only; curved boundaries need special treatment (finite elements handle them naturally).
  • Second order is slow compared with spectral methods for smooth solutions.
  • Explicit schemes have stability limits; implicit ones need linear solves.

Exercises

  1. Derive the amplification factor of the FTCS scheme and confirm the stability limit .
  2. Show that leapfrog with reproduces exactly on the grid.
  3. Measure the number of conjugate gradient iterations for the Poisson problem as the grid is refined. How does it grow, and why? (Hint: the condition number of the five-point matrix is about .)
  4. Solve the heat equation with a discontinuous initial condition (a step) using Crank-Nicolson with a large . What do you observe near the step, and why does the backward Euler scheme not show it? (Look at as .)
  5. Modify the Poisson example to a rectangle and compare the centre deflection with that of the square.
Hints and answers
  1. Insert a Fourier mode in : . for all requires , i.e. .
  2. With leapfrog reads . Substitute : both sides equal , so it is exact.
  3. Conjugate gradient iterations grow like : halving about doubles the iteration count.
  4. The Crank-Nicolson amplification factor for large and high wavenumbers, so the high-frequency content of the step is not damped but flips sign each step, giving oscillations near the step. Backward Euler’s factor damps them.
  5. The deflection of the rectangle is larger than that of the unit square at the centre of the long side, since the load is carried over a longer span; compare the maximum of in both cases.

Further reading

  • L. F. Richardson, Weather Prediction by Numerical Process, Cambridge University Press, 1922.
  • R. Courant, K. Friedrichs and H. Lewy, “Über die partiellen Differenzengleichungen der mathematischen Physik”, Mathematische Annalen 100 (1928) 32–74.
  • J. Crank and P. Nicolson, “A practical method for numerical evaluation of solutions of partial differential equations of the heat-conduction type”, Proceedings of the Cambridge Philosophical Society 43 (1947) 50–67.
  • M. R. Hestenes and E. Stiefel, “Methods of conjugate gradients for solving linear systems”, Journal of Research of the National Bureau of Standards 49 (1952) 409–436.
  • R. J. LeVeque, Finite Difference Methods for Ordinary and Partial Differential Equations, SIAM, 2007.