(1) dP(x,y,t)/dt = alpha2 (d2/dx2 + d2/dy2)P(x,y,t)we can discretize in space and time so that the time derivative is written either as a forward difference (explicit)
(2) P(x,y,t+dt) = P(x,y,t) + alpha2 dt D P(x,y,t),where D is the discrete Laplacian, or backward difference (implicit)
(3) P(x,y,t+dt) = P(x,y,t + alpha2 dt D P(x,y,t+dt)Adding (2) and (3) and solving for P(x,y,t+dt) gives
(4) (1 - alpha2 dt D/2)P(x,y,t+dt) = (1 + alpha2 dt D/2)P(x,y,t)This is the Crank-Nicholson form. Stepping forward in time involves solving a sparse linear system.
The code ~p6730/exercises/diffusion/diffusion.cc solves the diffusion equation in one dimension with boundaries at infinity. This problem is quite easily solved with a Fourier transform, but in coordinate space the matrix D for the second derivative generates a tridiagonal matrix, which is also very easy to solve using the standard Crout reduction.