This site is version 0.0.1. Most of the code on this site is drafted by an agent and needs review. I apologize for the AI-speak, we are working on rewriting it!
viv-lang.org

PDE solvers · Diffusion (parabolic)

The heat equation

Method
Crank-Nicolson: implicit, second order in space and time, stable at any time step
Checked
the exact decay of a sine mode; the measured order of accuracy; and that the explicit scheme blows up exactly where theory says it must

A rod with its ends held at zero and a half-sine of heat along it. Diffusion damps a mode at the rate , so the exact solution is — one number to get right, at every point.

The obvious scheme, forward in time and centered in space, is stable only while : halve the grid spacing and the time step must fall by four. Crank-Nicolson averages the space derivative between the old and new time levels. That costs a tridiagonal solve per step and buys unconditional stability and second order in time. tridiag_solve is the Thomas algorithm.

What the run shows

A half-sine of heat, cooling
t = 0t = 0.05t = 0.1t = 0.2
00.51.00.20.40.60.8xu(x, t)
  • Crank-Nicolson matches the exact decay exp(-kappa pi^2 t) sin(pi x)
  • it is second order: halving h and dt together cuts the error by four
  • the explicit scheme is stable at r = 0.45 and unstable at r = 0.55, either side of 1/2
e1
0.000432585
e2
0.000108096
order
2.00067
stable
0.00154862
unstable
38852.5

Computed when this page was built, by the same interpreter that runs it in your browser: 3 of 3 tests, under 0.1 s. The numbers above are the program's show lines.

The program

82 lines, 2 functions. It is editable: change it and press Run (or ⌘/Ctrl + Enter). The tests at the bottom run too, so if your change breaks the solver, a test fails.

cn_error
One Crank-Nicolson run on n interior points to time t_end; returns the L2 error against the exact solution.
ftcs_growth
The explicit scheme's amplification of the most oscillatory mode after `steps` steps.
Viv [1]

Open in the workbench The atlas Download heat_1d.viv