Computing Library › Worked Examples
Worked Examples

Solving the 2D Heat Equation

March a discretized 2D diffusion problem forward in time with an explicit five-point stencil, and check the stability limit that constrains the time step.

Problem

The heat equation u_t = alpha (u_xx + u_yy) describes temperature spreading across a plate. We solve it on a unit square with a hot spot in the center and zero temperature on all edges, using a uniform grid and explicit time stepping.

Discretization

Kronos motion — operating point

Replace second derivatives with the five-point Laplacian: (u_xx+u_yy) at (i,j) is approximately (u[i+1,j]+u[i-1,j]+u[i,j+1]+u[i,j-1]-4 u[i,j]) / dx^2. An explicit Euler step then updates every interior node from its four neighbors.

python
import numpy as np
n=41; dx=1.0/(n-1); alpha=1.0
dt=0.2*dx*dx/alpha         # inside stability limit
u=np.zeros((n,n)); u[n//2,n//2]=1.0/dx/dx
lap=lambda u:(np.roll(u,1,0)+np.roll(u,-1,0)+np.roll(u,1,1)+np.roll(u,-1,1)-4*u)/dx/dx
for _ in range(2000):
    u[1:-1,1:-1]+=dt*alpha*lap(u)[1:-1,1:-1]
    u[0,:]=u[-1,:]=u[:,0]=u[:,-1]=0.0
print(u.max(), u.sum()*dx*dx)  # peak decays, integral conserved until it reaches edges

Stability

The explicit scheme is stable only when dt <= dx^2 / (4 alpha) in two dimensions. Above that limit small errors grow geometrically and the solution explodes. We chose dt = 0.2 dx^2 / alpha, comfortably inside the bound. Implicit schemes like Crank-Nicolson remove this restriction at the cost of solving a linear system each step.