Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

1D Diffusion

In the previous two lessons, we studied the numerical solution of the linear and nonlinear convection equations and learned about the CFL stability condition. We now turn to the one-dimensional diffusion equation:

∂u∂t=ν∂2u∂x2.\frac{\partial u}{\partial t}=\nu\frac{\partial^2 u}{\partial x^2}.

Here, ν>0\nu>0 is a constant diffusion coefficient, with units of length squared over time. This equation describes how spatial variations in uu smooth out over time. It applies to several physical settings, like:

  • the evolution of temperature along a rod, where it is called the heat equation;

  • the diffusion of a pollutant along a pipe containing still fluid; or

  • the diffusion of a dissolved substance through a stationary gel.

On a finite domain, its solution needs an initial profile and a boundary condition at each end. In this lesson, we use 0≤x≤L0\le x\le L, with L=2L=2, and hold both endpoint values fixed:

u(0,t)=u(L,t)=1,t≥0.u(0,t)=u(L,t)=1,\qquad t\ge0.

These prescribed values are called Dirichlet boundary conditions. We will specify the initial profile below.

This is the first instance where we encounter a second-order spatial derivative. Our first-derivative schemes do not directly provide an approximation for this term, so we need to derive a new finite-difference formula before advancing the solution in time.

Discretize the second derivative

The second spatial derivative measures how the slope of uu changes with position. To approximate it, we use the value at a grid point and its two immediate neighbors.

As in Lesson 6, take a uniform grid xi=iΔxx_i=i\Delta x, with i=0,…,Ni=0,\ldots,N and Δx=L/N\Delta x=L/N. At a fixed time, write ui=u(xi,t)u_i=u(x_i,t) for the exact values while deriving the spatial approximation. For a sufficiently smooth function, Taylor expansion about xix_i gives

ui+1=ui+Δx∂u∂x∣i+Δx22∂2u∂x2∣i+Δx36∂3u∂x3∣i+O(Δx4),ui−1=ui−Δx∂u∂x∣i+Δx22∂2u∂x2∣i−Δx36∂3u∂x3∣i+O(Δx4).\begin{aligned} u_{i+1} &= u_i+\Delta x\left.\frac{\partial u}{\partial x}\right|_i +\frac{\Delta x^2}{2}\left.\frac{\partial^2 u}{\partial x^2}\right|_i +\frac{\Delta x^3}{6}\left.\frac{\partial^3 u}{\partial x^3}\right|_i +\mathcal{O}(\Delta x^4),\\ u_{i-1} &= u_i-\Delta x\left.\frac{\partial u}{\partial x}\right|_i +\frac{\Delta x^2}{2}\left.\frac{\partial^2 u}{\partial x^2}\right|_i -\frac{\Delta x^3}{6}\left.\frac{\partial^3 u}{\partial x^3}\right|_i +\mathcal{O}(\Delta x^4). \end{aligned}

Adding the expansions cancels the displayed odd-derivative terms and gives:

ui+1+ui−1=2ui+Δx2∂2u∂x2∣i+O(Δx4).u_{i+1}+u_{i-1}=2u_i+\Delta x^2\left.\frac{\partial^2 u}{\partial x^2}\right|_i +\mathcal{O}(\Delta x^4).

Subtract 2ui2u_i and divide by Δx2\Delta x^2 to obtain

∂2u∂x2∣i=ui+1−2ui+ui−1Δx2+O(Δx2).\left.\frac{\partial^2 u}{\partial x^2}\right|_i =\frac{u_{i+1}-2u_i+u_{i-1}}{\Delta x^2} +\mathcal{O}(\Delta x^2).

This is a second-order accurate central difference: for a smooth profile, its leading error scales with Δx2\Delta x^2. Notice that dividing by Δx2\Delta x^2 also changes the order of the remainder from O(Δx4)\mathcal{O}(\Delta x^4) to O(Δx2)\mathcal{O}(\Delta x^2).

Forward Euler in time

Let uinu_i^n denote our numerical approximation to u(xi,tn)u(x_i,t^n), where tn=nΔtt^n=n\Delta t. Using the central difference in Equation 5 for the spatial derivative, we apply forward Euler to advance in time. As in our earlier ODE calculations, Euler’s method evaluates the rate of change using the current state:

uin+1−uinΔt=νui+1n−2uin+ui−1nΔx2.\frac{u_i^{n+1}-u_i^n}{\Delta t} =\nu\frac{u_{i+1}^n-2u_i^n+u_{i-1}^n}{\Delta x^2}.

Rearranging gives the explicit update

uin+1=uin+νΔtΔx2(ui+1n−2uin+ui−1n),i=1,…,N−1.u_i^{n+1}=u_i^n+\frac{\nu\Delta t}{\Delta x^2} \left(u_{i+1}^n-2u_i^n+u_{i-1}^n\right), \qquad i=1,\ldots,N-1.

Every value on the right-hand side belongs to the old time level nn. The new interior values can therefore be calculated directly from the old array. This combination is called forward-time, central-space (FTCS). It is first-order accurate in time and second-order accurate in space; these orders describe the truncation error for sufficiently smooth solutions.

The three-point formula applies to the interior points. At the two endpoints, we impose the prescribed boundary values instead:

u0n+1=uNn+1=1.u_0^{n+1}=u_N^{n+1}=1.

For the initial profile, we reuse the square pulse from the convection lesson:

u(x,0)={2,0.5≤x≤1,1,elsewhere on [0,2].u(x,0)= \begin{cases} 2, & 0.5\le x\le1,\\ 1, & \text{elsewhere on }[0,2]. \end{cases}

This profile makes the spreading of the pulse easy to see. Its jumps do not satisfy the smoothness assumption used in the Taylor derivation, however, so we should not use them to infer the formal order of accuracy.

Stability through convex weights

In Lesson 7, we established a stability bound by writing the convection update as a weighted average. We can reuse that argument for diffusion, now with three old values instead of two.

Read the weights

Define the diffusion number

r=νΔtΔx2.r=\frac{\nu\Delta t}{\Delta x^2}.

This ratio is dimensionless: ν\nu has units of length squared per time. Collecting terms in Equation 7 gives

uin+1=rui−1n+(1−2r)uin+rui+1n.u_i^{n+1}=r u_{i-1}^n+(1-2r)u_i^n+r u_{i+1}^n.

The weights sum to one. They are all nonnegative when

0≤r≤12.0\le r\le\frac12.

Under this condition, the new value is a convex combination: it lies between the smallest and largest of the three old values. With our fixed endpoint values, the update cannot create a value outside the range of the initial and boundary data. For the square pulse, that range is [1,2][1,2].

This explains a useful property of the solution, but stability asks about the amplification of a disturbance. As in Lesson 7, we apply the argument to the difference between two calculations.

Bound a disturbance

Consider two numerical solutions with the same grid, diffusivity, time step, and prescribed endpoint values, but slightly different initial profiles. Define

ein=ub,in−ua,in,En=max⁡i∣ein∣.e_i^n=u_{b,i}^n-u_{a,i}^n, \qquad E^n=\max_i|e_i^n|.

Here, eine_i^n is the difference between two numerical solutions, not the error relative to an exact solution. Subtracting their updates gives

ein+1=rei−1n+(1−2r)ein+rei+1n.e_i^{n+1}=r e_{i-1}^n+(1-2r)e_i^n+r e_{i+1}^n.

For 0≤r≤1/20\le r\le1/2, the triangle inequality and the nonnegative weights imply

∣ein+1∣≤r∣ei−1n∣+(1−2r)∣ein∣+r∣ei+1n∣≤rEn+(1−2r)En+rEn=En.\begin{aligned} |e_i^{n+1}| &\le r|e_{i-1}^n|+(1-2r)|e_i^n|+r|e_{i+1}^n|\\ &\le rE^n+(1-2r)E^n+rE^n\\ &=E^n. \end{aligned}

Both endpoint differences are zero because the prescribed boundary values are identical. Taking the maximum over the whole array and repeating the bound over successive steps therefore yields

En≤En−1≤⋯≤E0.E^n\le E^{n-1}\le\cdots\le E^0.

The amplification bound is one, independent of the grid spacing and number of steps. This establishes stability for the stated update and boundary treatment when 0≤r≤1/20\le r\le1/2. It does not establish that the numerical solution is sufficiently accurate.

What happens beyond the limit?

When r>1/2r>1/2, the middle weight is negative. The argument above no longer applies, but a failed proof is not itself proof of growth. To see a mechanism for growth, reuse the alternating disturbance from Lesson 7. On a grid without boundaries, let

ein=An(−1)i.e_i^n=A_n(-1)^i.

Both neighbors of the point ii have the opposite sign. Substitution into Equation 14 gives

An+1=(1−4r)An.A_{n+1}=(1-4r)A_n.

For r>1/2r>1/2, the factor 1−4r1-4r is less than -1: the disturbance reverses sign and grows in magnitude at every step. For example, r=0.6r=0.6 gives a factor of -1.4. At r=1/2r=1/2, the factor is -1, so this particular pattern changes sign without decaying. Stability permits that behavior; it does not require every disturbance to decay.

Our two solutions have identical fixed endpoint values, so their difference is zero at both ends. The alternating disturbance therefore stops at the boundaries. Each update uses only neighboring values, so the boundary’s effect moves inward by at most one grid point per step. For example, over five steps, the factor 1−4r1-4r predicts the disturbance exactly at points more than five grid intervals from either end. Closer to the endpoints, the disturbance no longer follows this simple alternating pattern.

The time step now scales with the square of the spacing

For positive diffusivity, the bound gives

Δt≤Δx22ν.\Delta t\le\frac{\Delta x^2}{2\nu}.

Halving Δx\Delta x therefore quarters the largest permitted time step. Keeping the same diffusion number on the finer grid requires four times as many steps to reach the same physical time. In contrast, the convection time-step limit in Lesson 7 scaled with Δx\Delta x. The diffusion number measures a different balance from the distance-per-step interpretation of the Courant number.

Compute the diffusion of a square pulse

We can now implement Equation 7. We use the same domain and square pulse as above, with ν=0.3\nu=0.3 and a target diffusion number of 0.2, within the bound we just derived.

As in Lesson 7, we choose a final time first. The target diffusion number gives a proposed time step; we round the number of steps up and adjust the step size to reach that time. The realized diffusion number may be slightly smaller than the target. This lets us change the grid without also changing the duration of the calculation.

In the initial-condition setup, the Boolean mask selects points satisfying both comparisons. The & combines the two Boolean arrays element by element; keep the parentheses around each comparison.

As we did for convection in Lessons 6 and 7, we put the update in a function. We will reuse it for every diffusion calculation in this lesson. Its time loop advances the interior points, using array operations for the spatial stencil.

The pulse spreads and its peak decreases, while both endpoints stay at 1. Unlike the pure-convection example, smoothing is part of the physical model here. The convex-weight argument predicts that the values remain within [1,2][1,2].

Assessing accuracy

A stable calculation with a plausible shape could still diffuse too quickly or too slowly. How can we check that the amount of diffusion is correct?

We need a reference whose evolution we know independently of the numerical calculation. For this purpose, replace the square pulse with a smooth sine profile on the same domain, keeping the endpoint values fixed at 1:

u(x,0)=1+Asin⁡(πxL).u(x,0)=1+A\sin\left(\frac{\pi x}{L}\right).

We will use A=1A=1, so the initial peak is 2, as it was for the square pulse. On 0≤x≤L0\le x\le L, the sine is nonnegative, so the profile lies within [1,2][1,2].

Exact solution

For this initial profile, a candidate exact solution is

u(x,t)=1+Ae−νk2tsin⁡(kx),k=πL.u(x,t)=1+A e^{-\nu k^2t}\sin(kx), \qquad k=\frac{\pi}{L}.

Here kk has units of inverse length, so both kxkx and νk2t\nu k^2t are dimensionless. The sine determines the spatial shape, while the exponential determines how its amplitude changes with time.

Predict the decay

The exact solution retains its sine shape while the amplitude above the background decreases as

a(t)=Ae−νk2t.a(t)=A e^{-\nu k^2t}.

At the midpoint x=L/2x=L/2, the sine equals one, so u(L/2,t)−1=a(t)u(L/2,t)-1=a(t). This gives us a simple quantity to measure in the numerical solution.

With L=2L=2 and ν=0.3\nu=0.3, the decay rate νk2\nu k^2 is approximately 0.7402. Over the short interval T=0.04T=0.04 used above, the amplitude decreases by only about 2.9%2.9\%. For the accuracy investigation, we will use T=1T=1: the amplitude then decreases from 1 to approximately 0.4770, and the peak value becomes approximately 1.4770.

Compute and compare the decay

We now reuse advance_diffusion() with the sine profile and T=1T=1. The grid still contains 41 points, including x=L/2x=L/2, where we will measure the final amplitude.

The expression nx // 2 gives the index of the midpoint x=L/2x=L/2 for this odd number of equally spaced grid points.

Now evaluate the exact amplitude and the exact solution at the final time, using the expression we checked on paper.

To state the comparison as a property of the diffusion, convert the final amplitude into a decay rate. For an exponential, the rate can be recovered from the amplitude change over the interval:

βmeasured=−1Tlog⁡(a(T)A).\beta_{\mathrm{measured}} =-\frac{1}{T}\log\left(\frac{a(T)}{A}\right).

Compare the rate measured from the computation with the exact rate β=νk2\beta=\nu k^2.

FTCS ends with a slightly smaller amplitude than the exact solution, and its measured decay rate is slightly larger than νk2\nu k^2. On this grid with this time step, the numerical solution decays slightly too quickly.

Measure the error

Compare the computed and exact solutions over the entire final array. We use the maximum absolute error:

E=max⁡i∣uicomputed−u(xi,T)∣.E=\max_i\left|u_i^{\mathrm{computed}}-u(x_i,T)\right|.

The maximum error is approximately 3.63×10−53.63\times10^{-5}. We now have a quantitative measure of a difference far too small to see on a plot. The next question is how much we can reduce this error by refining the grid, and how much additional computation that improvement requires.

Accuracy versus computational cost

We can reduce this error by refining the grid, but each refinement requires more computation. How much accuracy does that extra work buy?

Refine space and time together

The stability bound couples the two refinements. As we found above, halving Δx\Delta x at a fixed diffusion number requires quartering Δt\Delta t. We therefore keep the target diffusion number at 0.2 and refine space and time together. This is a combined refinement study: it measures how the error of the complete calculation changes along that path.

How do the two orders combine?

FTCS is first order in time and second order in space. For a smooth solution in the stable regime, the leading contributions to the signed error at a fixed position and time have the form

e≈CtΔt+CxΔx2,e\approx C_t\Delta t+C_x\Delta x^2,

where the coefficients depend on the solution and the location and time of comparison. At fixed rr, Δt=rΔx2/ν\Delta t=r\Delta x^2/\nu, so

e≈(Ctrν+Cx)Δx2.e\approx\left(C_t\frac{r}{\nu}+C_x\right)\Delta x^2.

Both leading contributions now scale with Δx2\Delta x^2, so we expect the maximum error to decrease approximately fourfold each time we halve the spacing. This does not turn Euler’s method into a second-order time integrator: we are measuring error against Δx\Delta x while reducing Δt\Delta t quadratically.

Predict the computational work

At fixed final time, quartering Δt\Delta t requires four times as many steps, and halving Δx\Delta x roughly doubles the number of interior grid points. As a simple measure of work, count the interior point updates:

W=(nx−2)Nsteps.W=(n_x-2)N_{\mathrm{steps}}.

Each update evaluates the same three-point stencil. The count measures numerical work, not elapsed runtime, so the comparison does not depend on the machine.

We predict roughly eight times the work for four times smaller error.

Run the combined refinement study

Keep every other parameter of the sine-profile calculation, and use 41, 81, and 161 points so that the spacing halves between runs.

Each entry of refinement_results is a dictionary holding one grid’s settings and measurements.

As in Lesson 6, estimate the observed order from neighboring errors. Here every spacing ratio is two, so

p=log⁡(Ecoarse/Efine)log⁡2.p=\frac{\log(E_{\mathrm{coarse}}/E_{\mathrm{fine}})}{\log 2}.

An error ratio of four gives p=2p=2.

Each refinement reduces the error by a factor close to four, an observed order near two, while the work grows by a factor slightly above eight.

Choose a calculation for a required accuracy

Suppose this benchmark requires a maximum error below 10-5 at T=1T=1. This is a numerical target for the exercise. Which tested grid meets it with the least work?

Plot the errors against work, with the target as a horizontal line. In one dimension, the number of steps grows as Δx−2\Delta x^{-2} and the number of points as Δx−1\Delta x^{-1}, so W∝Δx−3W\propto\Delta x^{-3}. With E∝Δx2E\propto\Delta x^2, this gives E∝W−2/3E\propto W^{-2/3}: the guide line, anchored to the coarsest result, shows that slope.

The 41-point grid does not meet the target. Both finer grids do, but the 81-point calculation uses 189 600189\,600 updates, compared with 1 526 4001\,526\,400 for 161 points. The 81-point grid is therefore the least expensive among those tested that satisfies this requirement. Its measured error is only slightly below the threshold; a tighter requirement would change the choice.

Ask an agent when refinement stops helping

We will keep this closing activity deliberately light. Earlier activities asked an agent to write or review code. Here we ask a different question about how an agent can support a numerical investigation: can it help us get situated when an experiment does not behave as expected?

Imagine that another calculation of the sine-profile problem produces the results in the prompt below. Refining the grid barely changes the error, and we are stuck. Should we spend more computation on a finer grid, or inspect something first?

These results come from a deliberately altered calculation, not from the correct run above. You do not need to reproduce it or write new code. The agent’s task is to answer a direct question using the problem statement and the numerical evidence.

Send a focused question

Copy only the prompt below into a new conversation with an agent. Do not attach your notebook: for this first assessment, the agent has the specified problem and the results, but has not inspected the implementation. No file access or execution is needed.

Prompt

I am solving

ut=0.3uxx,0≤x≤2,u_t=0.3u_{xx},\qquad 0\le x\le2,

with fixed endpoints u(0,t)=u(2,t)=1u(0,t)=u(2,t)=1 and initial profile u(x,0)=1+sin⁡(πx/2)u(x,0)=1+\sin(\pi x/2). The exact solution is

u(x,t)=1+e−0.3(π/2)2tsin⁡(πx/2).u(x,t)=1+e^{-0.3(\pi/2)^2t}\sin(\pi x/2).

I use forward Euler in time and a centered second difference in space. Every run ends at T=1T=1, with diffusion number r=0.3Δt/Δx2=0.2r=0.3\Delta t/\Delta x^2=0.2. At fixed rr, I expect halving the spacing to reduce the error approximately fourfold.

Grid pointsTime stepsMaximum error against the exact solutionInterior point updates
416003.5564×10−33.5564\times10^{-3}23,400
812,4003.5275×10−33.5275\times10^{-3}189,600
1619,6003.5203×10−33.5203\times10^{-3}1,526,400

My target is a maximum error below 10-5. Should I next try 321 grid points?

In no more than 150 words:

  1. Assess whether the evidence justifies that extra computation, considering accuracy and cost.

  2. Recommend one simple inspection of my existing code or settings before running again. Explain what you would compare with the stated problem.

  3. Separate what the table shows from what you only suspect.

You have not seen my code. Do not modify files or introduce another method or reference solution. You may propose a short diagnostic calculation if useful, but explain what it would establish before asking me to run it.

Judge the advice

Compare the response with your initial judgment. Does the agent recognize that the error is approaching a plateau while work grows roughly eightfold per refinement? Does it propose a specific, inexpensive inspection, and explain what that inspection could establish?

Try the same prompt in a fresh conversation with another model, or allow a small scratch calculation. Did the additional response change your next action? Identify any new evidence it supplied, rather than judging by confidence or detail.

A useful response might suggest checking the coefficient, grid spacing, final time, or exact-solution evaluation against the stated problem. It need not guess the cause. An agent that declares a particular bug from the table alone is claiming more than the evidence supports.