Module contents
Lesson 7 of 27Core 115 min

Finite differences I: elliptic and parabolic problems and the Lax theorem

Discretize Poisson and heat equations with finite differences, sparse matrices and the method of lines, then study consistency, stability and convergence.

After this lesson you can

  • Discretize the Laplacian in 1D and 2D and solve Poisson equations with Dirichlet and Neumann conditions.
  • Calculate the local truncation error and order of consistency.
  • Apply von Neumann analysis to obtain stability conditions for a heat equation scheme.
  • State and apply the Lax equivalence theorem to predict convergence.
  • Implement the method of lines and compare explicit Euler, implicit Euler and Crank-Nicolson.

Before you start

A plate and a grid

The temperature of a plate, electrostatic potential and, after a transformation, the Black-Scholes equation share diffusion operators. Their domain, data and the meaning of their variables differ; discretization does not eliminate those differences. Start with −Δu=f-\Delta u=f on a square, with values of uu on the boundary, and ut=κΔuu_t=\kappa\Delta u for heat.

A finite-difference stencil approximates a derivative using neighboring values. For a sufficiently smooth function, Taylor expansion around xix_i gives

u(xi−h)−2u(xi)+u(xi+h)h2=u′′(xi)+h212u(4)(xi)+O(h4).\frac{u(x_i-h)-2u(x_i)+u(x_i+h)}{h^2} =u''(x_i)+\frac{h^2}{12}u^{(4)}(x_i)+O(h^4).

The odd terms cancel. Consistency means that the residual from inserting the exact solution into the scheme tends to zero; here the spatial error is O(h2)O(h^2) under the stated regularity. By itself, this does not guarantee that the computed solution error decreases.

On the unit interval, −u′′=1-u''=1 with u(0)=u(1)=0u(0)=u(1)=0 has solution u=x(1−x)/2u=x(1-x)/2. For nn interior unknowns and h=1/(n+1)h=1/(n+1), the system is tridiagonal: diagonal 2/h22/h^2 and neighboring diagonals −1/h2-1/h^2. In this particular case the stencil exactly reproduces the second derivative of the quadratic solution at the nodes. This experiment helps detect sign and boundary errors, but its zero error cannot measure the order: for that we use a non-polynomial function.

In two dimensions, with spacings hx,hyh_x,h_y, add the second differences along each axis. The five-point stencil connects each node to its four neighbors. If Dx,DyD_x,D_y represent Δh\Delta_h on each axis and xx varies fastest in the vector, the matrix is

Lh=Iy⊗Dx+Dy⊗Ix,A=−Lh.L_h=I_y\otimes D_x+D_y\otimes I_x,\qquad A=-L_h.

For homogeneous Dirichlet conditions, AA is symmetric positive definite. In 1D its eigenvalues are 4h−2sin⁡2(kπ/(2(n+1)))4h^{-2}\sin^2(k\pi/(2(n+1))), k=1,…,nk=1,\ldots,n. The lowest frequency remains bounded on a fixed region and the highest grows as h−2h^{-2}: conditioning worsens under refinement. A sparse matrix stores only stencil entries; a dense format also stores zeros and rapidly consumes memory.

InteractiveFrom stencil to sparse matrix
Stencil for row 1
Matrix pattern

RCM is reverse Cuthill–McKee. Fill is symbolic for unpivoted Cholesky of the positive definite matrix: it counts new positions below the diagonal, not measured time or memory.

Ordering
1
Half-bandwidth6
Nonzeros in A156
Nonzeros in L221
Fill in L125
Select a row and change the ordering. The L factor and its fill are symbolic counts for unpivoted Cholesky on the positive matrix.

Reordering permutes rows and columns simultaneously without changing the physical solution. It can, however, change bandwidth and the new nonzeros created during elimination. RCM reverses a Cuthill-McKee traversal; red-black groups nodes by checkerboard color. No ordering guarantees minimum fill for every problem. The figure counts structural positions, not timings.

With nonzero Dirichlet values, boundary neighbors are known and their contributions move to the right-hand side. The discrete harmonic solution (Δhu=0\Delta_h u=0) at each interior node is a positive weighted average of its neighbors. By the discrete maximum principle, the maximum and minimum occur on the boundary: if an interior maximum were strictly larger than all boundary values, equality with the average would propagate it to the boundary. For −Δhu=f≥0-\Delta_h u=f\ge0, the applicable conclusion is that the minimum does not fall below the boundary minimum; we do not claim that the maximum is on the boundary.

With a homogeneous 1D Neumann condition, the centered derivative at the endpoint gives u−1=u1u_{-1}=u_1. The second derivative there is 2(u1−u0)/h22(u_1-u_0)/h^2. Pure Neumann conditions leave a constant in the null space: a solution exists only if the source is compatible with the flux, and a mean must be chosen to fix the constant. With these ghost nodes, discrete compatibility uses trapezoidal weights, half at each endpoint; in two dimensions the weights from both axes are multiplied. The matrix is not symmetric in the ordinary Euclidean inner product, although it is symmetric with those weights. The lab implements only homogeneous Neumann conditions; other derivatives require correctly incorporating the flux into the right-hand side.

Boundary treatment deserves its own analysis. Although the centered ghost-node derivative is second order, substituting it into the Poisson equation can produce an O(h)O(h) pointwise boundary residual when the third derivative is nonzero; global convergence depends on the problem and the norm. The manufactured cosine in the lab has zero odd derivatives at both endpoints, so this particular test does not establish the order for all Neumann data.

Method of lines and stability

The method of lines discretizes space first, leaving an ODE U′=κLhUU'=\kappa L_hU. High frequencies decay on a timescale proportional to h2/κh^2/\kappa: fast and slow modes coexist, creating a stiff problem. The methods and their cost per tolerance connect to integration of stiff systems.

On an infinite or periodic uniform grid, von Neumann analysis substitutes a mode eijξe^{\mathrm{i}j\xi} into the update. With r=κΔt/h2r=\kappa\Delta t/h^2 and q=4rsin⁡2(ξ/2)q=4r\sin^2(\xi/2), exact evolution of the semidiscrete system multiplies its amplitude by e−qe^{-q}. The factors for explicit Euler, implicit Euler and Crank-Nicolson are

gE=1−q,gI=11+q,gCN=1−q/21+q/2.g_{\rm E}=1-q,\qquad g_{\rm I}=\frac{1}{1+q},\qquad g_{\rm CN}=\frac{1-q/2}{1+q/2}.

The condition ∣gE∣≤1|g_{\rm E}|\le1 for all modes gives r≤1/2r\le1/2 in 1D. In 2D, with equal spacing on both axes, the uniform bound is r≤1/4r\le1/4. For finitely many Dirichlet nodes the highest-frequency mode does not reach exactly ξ=π\xi=\pi, so the exact spectral limit is slightly larger. With unequal spacings the sufficient explicit bound is κΔt(hx−2+hy−2)≤1/2\kappa\Delta t(h_x^{-2}+h_y^{-2})\le1/2.

InteractiveMode amplification
  • Explicit
  • Implicit
  • Crank-Nicolson
  • Exact semidiscrete

The lower graph visually clips values outside [−4,4]; the readout retains the calculated amplitude. For a finite Dirichlet grid, the highest mode has ξ slightly below π and the exact threshold is slightly above 1/2.

0.40
10
Mode scheme
Finite-mode factor−0.5977
Amplitude after steps5.814e-3
Compare each factor with the exact solution of the semidiscrete system. The lower wave corresponds to the highest mode of a finite grid.

Implicit Euler damps fast modes: gI→0g_{\rm I}\to0 as q→∞q\to\infty. CN is stable in norm for the linear diffusion problem because ∣gCN∣≤1|g_{\rm CN}|\le1, but gCN→−1g_{\rm CN}\to-1: a discontinuity can produce persistent alternating oscillations. Stability does not imply positivity or accuracy. Rannacher startup replaces the first CN step with two half steps of implicit Euler, whose factor (1+q/2)−2(1+q/2)^{-2} damps high frequencies; CN is then used. For smooth data and a small step, CN has second-order temporal error; startup modifies the first steps and must be included in any error study.

InteractiveOne plate, four evolutions

Initial data: click squares to toggle 0 and 1. Exterior Dirichlet boundaries are zero.

Explicit Euler

Minimum −2.0000, maximum 1.5000

Implicit Euler

Minimum 0.0013, maximum 0.8356

Crank-Nicolson

Minimum 0.0006, maximum 0.8609

CN with Rannacher startup

Minimum 0.0011, maximum 0.8304

The color scale saturates above 1; orange indicates negative values. Numbers are not clipped. Sine modes apply the matrices of each scheme exactly; Rannacher replaces the first CN step with two implicit half steps.

1.50
1
7
7
Initial condition36 hot cells
Explicit 2D stabilityoutside uniform bound
Edit the initial condition and compare the same number of steps. Boundaries are zero and the scale saturates values above one; orange marks negative values.

Fourier analysis on its own describes constant coefficients on a periodic or infinite grid. Boundaries, variable coefficients or nonlinear schemes require study of the appropriate operator and norm. For example, having every eigenvalue inside the unit disk does not by itself control powers of a highly nonnormal matrix.

Consistency plus stability

For a well-posed continuous linear problem and a consistent linear discretization, the Lax equivalence theorem relates stability and convergence in the appropriate framework of norms and limits. Consider the sufficient direction. Let ShS_h be the update, ene^n the error and τn\tau^n the local residual per unit time:

en+1=Shen+Δt τn,en=Shne0+Δt∑j=0n−1Shn−1−jτj.e^{n+1}=S_he^n+\Delta t\,\tau^n,\qquad e^n=S_h^ne^0+\Delta t\sum_{j=0}^{n-1}S_h^{n-1-j}\tau^j.

If ∥Shk∥≤CT\|S_h^k\|\le C_T uniformly for kΔt≤Tk\Delta t\le T, then

∥en∥≤CT∥e0∥+CTTmax⁡j<n∥τj∥.\|e^n\|\le C_T\|e^0\|+C_T T\max_{j<n}\|\tau^j\|.

Thus convergent initial data and a residual tending to zero imply convergence over finite time. If both errors are O(hp+Δtq)O(h^p+\Delta t^q), that order is preserved in this bound. The assumptions matter: uniform stability is not a check on a single grid, and regularity needed for the residual may fail for discontinuous data. The reverse direction requires the full framework of the theorem; it does not follow from the inequality above. See the original paper by Lax and Richtmyer.

Lab: Poisson and heat

The first cell defines the operator from scratch with Kronecker products, solves a compatible Neumann problem with zero trapezoidal mean and integrates heat. Dirichlet counts interior nodes only; Neumann includes both endpoints. The vector is ordered row by row, with xx varying fastest.

[ ]Sparse operator and time methodsBrowser
"""Laplaciano 2D y esquemas de calor con convenciones explícitas de malla."""
import numpy as np
from scipy.sparse import diags,eye,kron,csr_matrix
from scipy.sparse.linalg import spsolve,factorized

def laplacian_2d(nx,ny,hx,hy,bc='dirichlet'):
    """Devuelve Δh CSR; x varía más rápido. Neumann homogéneo con nodos fantasma.

    Dirichlet: nx×ny incógnitas interiores y valores exteriores cero.
    Neumann: nx×ny nodos incluidos ambos extremos, con derivada normal cero.
    """
    if nx<3 or ny<3 or hx<=0 or hy<=0 or bc not in ('dirichlet','neumann'): raise ValueError('malla o frontera inválida')
    def one(n,h):
        D=diags([np.ones(n-1),-2*np.ones(n),np.ones(n-1)],[-1,0,1],format='lil')
        if bc=='neumann':D[0,1]=2;D[-1,-2]=2
        return D.tocsr()/h**2
    Dx,Dy=one(nx,hx),one(ny,hy)
    return (kron(eye(ny,format='csr'),Dx,format='csr')+kron(Dy,eye(nx,format='csr'),format='csr')).tocsr()

def neumann_poisson(f,nx,ny,hx,hy,tol=1e-10):
    """Resuelve -Δh u=f con media trapezoidal cero y compatibilidad ponderada."""
    rhs=np.asarray(f,dtype=float).reshape(-1)
    if rhs.size!=nx*ny:raise ValueError('forma incompatible')
    wx=np.ones(nx);wx[[0,-1]]=.5;wy=np.ones(ny);wy[[0,-1]]=.5
    weights=np.outer(wy,wx).ravel();weights/=weights.sum()
    if abs(weights@rhs)>tol*max(1,np.max(np.abs(rhs))):raise ValueError('fuente incompatible con flujo nulo')
    A=(-laplacian_2d(nx,ny,hx,hy,'neumann')).tolil();A[0,:]=weights
    rhs=rhs.copy();rhs[0]=0.;return spsolve(A.tocsr(),rhs)

def heat_integrate(L,u0,kappa,dt,n_steps,method='explicit',rannacher=False):
    """Calor semidiscreto; Rannacher sustituye primer paso CN por dos IE de dt/2."""
    if kappa<0 or dt<=0 or n_steps<0 or method not in ('explicit','implicit','cn'):raise ValueError('parámetros inválidos')
    u=np.asarray(u0,dtype=float).copy();L=csr_matrix(L);I=eye(L.shape[0],format='csc')
    if L.shape!=(u.size,u.size):raise ValueError('forma incompatible')
    if rannacher and method!='cn':raise ValueError('arranque solo para CN')
    if method=='implicit':solve=factorized((I-dt*kappa*L).tocsc())
    if method=='cn':
        solve=factorized((I-.5*dt*kappa*L).tocsc());B=I+.5*dt*kappa*L
        if rannacher:half=factorized((I-.5*dt*kappa*L).tocsc())
    for step in range(n_steps):
        if method=='explicit':u=u+dt*kappa*(L@u)
        elif method=='implicit':u=solve(u)
        elif rannacher and step==0:u=half(half(u))
        else:u=solve(B@u)
    return u

For Dirichlet we manufacture u=sin⁡(πx)sin⁡(πy)u=\sin(\pi x)\sin(\pi y) and f=2π2uf=2\pi^2u. For Neumann we choose u=cos⁡(πx)cos⁡(πy)u=\cos(\pi x)\cos(\pi y), with zero flux and zero weighted mean. The error ratio approaches four when the resolution doubles: evidence of second order for these cases, not a universal proof.

[ ]Refinement with two boundary conditionsBrowser
for bc in ('dirichlet','neumann'):
    errors=[]
    for n in ((7,15,31) if bc=='dirichlet' else (9,17,33)):
        h=1/(n+1) if bc=='dirichlet' else 1/(n-1)
        x=np.arange(1,n+1)*h if bc=='dirichlet' else np.arange(n)*h
        X,Y=np.meshgrid(x,x)
        exact=(np.sin(np.pi*X)*np.sin(np.pi*Y) if bc=='dirichlet'
               else np.cos(np.pi*X)*np.cos(np.pi*Y)).ravel()
        f=2*np.pi**2*exact
        numerical=(spsolve(-laplacian_2d(n,n,h,h,bc),f) if bc=='dirichlet'
                   else neumann_poisson(f,n,n,h,h))
        errors.append(np.max(np.abs(numerical-exact)))
    print(bc, 'errores:',errors,'cocientes:',np.array(errors[:-1])/errors[1:])

In the next experiment r=0.2r=0.2 satisfies the two-dimensional explicit bound. BDF integrates the same semidiscrete ODE with a sparse Jacobian; the temporal comparison alone does not measure spatial error against the PDE.

[ ]Three schemes versus BDFBrowser
from scipy.integrate import solve_ivp
n=15;h=1/(n+1);L=laplacian_2d(n,n,h,h)
x=np.arange(1,n+1)*h;X,Y=np.meshgrid(x,x)
u0=(np.sin(np.pi*X)*np.sin(np.pi*Y)).ravel()
dt=.2*h*h;steps=30;T=dt*steps
reference=solve_ivp(lambda t,u:L@u,(0,T),u0,method='BDF',jac=L,rtol=1e-10,atol=1e-12).y[:,-1]
for method in ('explicit','implicit','cn'):
    u=heat_integrate(L,u0,1.,dt,steps,method)
    print(method,'error máximo respecto a BDF:',np.max(np.abs(u-reference)))

To apply a one-dimensional operator, construct D_x and solve -D_x u=f. In 2D the Kronecker product avoids constructing a dense matrix. A linear solver must also be sufficiently accurate relative to discretization error; an overly loose tolerance can obscure the order.

Exercises

ProofCrank-Nicolson stability
Prove: Prove modal stability for diffusion and examine high frequencies.
0
Let q≥0 be the product of the time step and a positive eigenvalue of −κLh.

Step 1 of 3. What factor does the trapezoidal rule produce?

ProofConsistency and stability
Prove: Prove the sufficient direction of Lax on a fixed time interval.
0
The error satisfies eⁿ⁺¹=Sₕeⁿ+Δtτⁿ and powers of Sₕ are uniformly bounded by C.

Step 1 of 3. How is the error expressed after n steps?

NumericExplicit step in one dimension
With κ=1, h=0.01 and the uniform 1D bound, what is the largest allowed Δt?
NumericNumber of steps
How many steps of Δt=0.00005 reach t=1?
QuizRefinement with fixed r
A 1D heat scheme is consistent, but explicit Euler uses fixed r=0.6 as the grid is refined. What can be concluded?
CodeSparse Laplacian
Implement laplacian_2d(nx,ny,hx,hy,bc), returning Δh in CSR with x varying fastest. Dirichlet uses nx×ny interior nodes with zero boundary; homogeneous Neumann includes endpoints and uses centered ghost nodes.
import numpy as np
from scipy.sparse import diags, eye, kron
def laplacian_2d(nx,ny,hx,hy,bc='dirichlet'):
  pass
Shift+Enter to run
Key idea
The grid and boundaries define the operator; consistency describes the residual and stability controls its propagation. Together, under the appropriate assumptions, they allow convergence to be proved.