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
- 29Conservation-law modelingNondimensionalization and scalingWork-precision diagram
- 03Heat equationLaplace equation and harmonic functionsSeparation of variablesFourier series
- 09Finite differencesOptimal finite-difference stepSparse matrix formatsBanded and tridiagonal solversConjugate gradientRegion of absolute stabilityStiffness and implicit methodsExplicit and implicit Euler methods
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 on a square, with values of on the boundary, and for heat.
A finite-difference stencil approximates a derivative using neighboring values. For a sufficiently smooth function, Taylor expansion around gives
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 under the stated regularity. By itself, this does not guarantee that the computed solution error decreases.
On the unit interval, with has solution . For interior unknowns and , the system is tridiagonal: diagonal and neighboring diagonals . 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 , add the second differences along each axis. The five-point stencil connects each node to its four neighbors. If represent on each axis and varies fastest in the vector, the matrix is
For homogeneous Dirichlet conditions, is symmetric positive definite. In 1D its eigenvalues are , . The lowest frequency remains bounded on a fixed region and the highest grows as : conditioning worsens under refinement. A sparse matrix stores only stencil entries; a dense format also stores zeros and rapidly consumes memory.
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 () 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 , 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 . The second derivative there is . 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 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 . High frequencies decay on a timescale proportional to : 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 into the update. With and , exact evolution of the semidiscrete system multiplies its amplitude by . The factors for explicit Euler, implicit Euler and Crank-Nicolson are
The condition for all modes gives in 1D. In 2D, with equal spacing on both axes, the uniform bound is . For finitely many Dirichlet nodes the highest-frequency mode does not reach exactly , so the exact spectral limit is slightly larger. With unequal spacings the sufficient explicit bound is .
Implicit Euler damps fast modes: as . CN is stable in norm for the linear diffusion problem because , but : 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 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.
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 be the update, the error and the local residual per unit time:
If uniformly for , then
Thus convergent initial data and a residual tending to zero imply convergence over finite time. If both errors are , 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 varying fastest.
"""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 uFor Dirichlet we manufacture and . For Neumann we choose , 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.
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 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.
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
Step 1 of 3. What factor does the trapezoidal rule produce?
Step 1 of 3. How is the error expressed after n steps?
import numpy as np
from scipy.sparse import diags, eye, kron
def laplacian_2d(nx,ny,hx,hy,bc='dirichlet'):
pass