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:
Here, is a constant diffusion coefficient, with units of length squared over time. This equation describes how spatial variations in 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 , with , and hold both endpoint values fixed:
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 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 , with and . At a fixed time, write for the exact values while deriving the spatial approximation. For a sufficiently smooth function, Taylor expansion about gives
Adding the expansions cancels the displayed odd-derivative terms and gives:
Subtract and divide by to obtain
This is a second-order accurate central difference: for a smooth profile, its leading error scales with . Notice that dividing by also changes the order of the remainder from to .
On paper
Reconstruct the derivation by adding the two Taylor expansions. Then consider the numerator : what sign does it have at a strict local maximum? What value does it have when the three points lie on a straight line? Use the diffusion equation to predict the corresponding change in .
Forward Euler in time¶
Let denote our numerical approximation to , where . 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:
Rearranging gives the explicit update
Every value on the right-hand side belongs to the old time level . 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:
For the initial profile, we reuse the square pulse from the convection lesson:
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.
On paper
For the three values and , calculate the updated middle value while holding the endpoints fixed. Does the change agree with your prediction at a local maximum?
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
This ratio is dimensionless: has units of length squared per time. Collecting terms in Equation 7 gives
The weights sum to one. They are all nonnegative when
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 .
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
Here, is the difference between two numerical solutions, not the error relative to an exact solution. Subtracting their updates gives
For , the triangle inequality and the nonnegative weights imply
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
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 . It does not establish that the numerical solution is sufficiently accurate.
What happens beyond the limit?¶
When , 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
Both neighbors of the point have the opposite sign. Substitution into Equation 14 gives
For , the factor is less than -1: the disturbance reverses sign and grows in magnitude at every step. For example, gives a factor of -1.4. At , 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 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
Halving 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 . The diffusion number measures a different balance from the distance-per-step interpretation of the Courant number.
On paper
Reconstruct the bound on , identifying where nonnegative weights and identical boundary data enter the argument.
Calculate the three weights and the alternating-disturbance factor for , 0.5, and 0.6. Which cases control the magnitude of that disturbance?
If you halve while keeping fixed, what happens to ? Starting from , does the refined calculation still satisfy the bound?
Compute the diffusion of a square pulse¶
We can now implement Equation 7. We use the same domain and square pulse as above, with 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 your notebook
Reconstruct the grid, initial profile, and update function below. Before running the calculation, predict how the pulse will change and what range its values should remain in. You may copy the imports and plot formatting.
import numpy as np
import matplotlib.pyplot as plt# Set the font family and size to use for Matplotlib figures.
plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.size'] = 10# Define the grid and diffusion coefficient
nx = 41
L = 2.0
dx = L / (nx - 1)
nu = 0.3
x = np.linspace(0.0, L, num=nx)
# Choose a time step that reaches the requested final time
t_final = 0.04
r_target = 0.2
dt_target = r_target * dx**2 / nu
num_steps = int(np.ceil(t_final / dt_target))
dt = t_final / num_steps
r = nu * dt / dx**2
# Set the initial profile, including the fixed endpoint values
u0 = np.ones(nx)
mask = (x >= 0.5) & (x <= 1.0)
u0[mask] = 2.0
print(f'dx = {dx:.4f}, dt = {dt:.6f}, r = {r:.3f}')
print(f'{num_steps} steps to t = {num_steps * dt:.4f}')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.
def advance_diffusion(u0, nu, dx, dt, num_steps):
'''Advance 1D diffusion with FTCS, holding both endpoints fixed.'''
r = nu * dt / dx**2
u = u0.copy()
for n in range(num_steps):
u[1:-1] = u[1:-1] + r * (u[2:] - 2 * u[1:-1] + u[:-2])
return u
u = advance_diffusion(u0, nu, dx, dt, num_steps)fig, ax = plt.subplots(figsize=(5.0, 3.0))
ax.plot(x, u0, label='Initial', linestyle='--', linewidth=2)
ax.plot(x, u, color='tab:red', label=f't = {t_final:.3f}', linewidth=2)
ax.set_xlabel('x')
ax.set_ylabel('u')
ax.set_xlim(0.0, L)
ax.grid(alpha=0.3)
ax.legend()
fig.tight_layout();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 .
Self-checks
Confirm that
u[0]andu[-1]are still 1, and inspectu.min()andu.max()against your predicted range.What would happen to
u0ifadvance_diffusion()omitted.copy()? Would the plot above still show the initial profile?
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:
We will use , so the initial peak is 2, as it was for the square pulse. On , the sine is nonnegative, so the profile lies within .
Exact solution¶
For this initial profile, a candidate exact solution is
Here has units of inverse length, so both and are dimensionless. The sine determines the spatial shape, while the exponential determines how its amplitude changes with time.
On paper — check the candidate solution
Differentiate with respect to , holding fixed. Treat as a constant multiplier.
Differentiate twice with respect to , holding fixed. This time, is the constant multiplier.
Compare your expressions for and . Are they equal?
Set . Do you recover Equation 20? Then set and . Do the endpoint values remain 1 for all time?
Predict the decay¶
The exact solution retains its sine shape while the amplitude above the background decreases as
At the midpoint , the sine equals one, so . This gives us a simple quantity to measure in the numerical solution.
With and , the decay rate is approximately 0.7402. Over the short interval used above, the amplitude decreases by only about . For the accuracy investigation, we will use : 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 . The grid still contains 41 points, including , where we will measure the final amplitude.
In your notebook
Reconstruct the sine-profile setup and call your update function. Before running it, record the exact amplitude predicted at .
# Reuse the grid, nu, and r_target from the square-pulse calculation
A = 1.0
k = np.pi / L
t_final = 1.0
dt_target = r_target * dx**2 / nu
num_steps = int(np.ceil(t_final / dt_target))
dt = t_final / num_steps
r = nu * dt / dx**2
sine_profile = np.sin(k * x)
u0 = 1.0 + A * sine_profile
print(f'dx = {dx:.4f}, dt = {dt:.8f}, r = {r:.4f}')
print(f'{num_steps} steps to t = {num_steps * dt:.4f}')The expression nx // 2 gives the index of the midpoint for this odd number of equally spaced grid points.
u = advance_diffusion(u0, nu, dx, dt, num_steps)
midpoint = nx // 2
amplitude = u[midpoint] - 1.0Now evaluate the exact amplitude and the exact solution at the final time, using the expression we checked on paper.
exact_rate = nu * k**2
amplitude_exact = A * np.exp(-exact_rate * t_final)
u_exact = 1.0 + amplitude_exact * sine_profileTo 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:
Compare the rate measured from the computation with the exact rate .
measured_rate = -np.log(amplitude / A) / t_final
print(f"{'Reference':<22} {'Final amplitude':>18} {'Decay rate':>16}")
for name, final_amplitude, rate in (
('Exact PDE', amplitude_exact, exact_rate),
('Computed FTCS', amplitude, measured_rate),
):
print(f'{name:<22} {final_amplitude:18.10f} {rate:16.10f}')FTCS ends with a slightly smaller amplitude than the exact solution, and its measured decay rate is slightly larger than . 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:
error = np.max(np.abs(u - u_exact))
print(f'Maximum error against exact solution: {error:.3e}')The maximum error is approximately . 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.
Self-checks
Why do we subtract 1 before measuring amplitude? What would go wrong with using the peak value itself in the decay-rate formula?
Does FTCS decay too quickly or too slowly in this run? Support your answer with both the final amplitudes and the decay rates.
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 at a fixed diffusion number requires quartering . 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
where the coefficients depend on the solution and the location and time of comparison. At fixed , , so
Both leading contributions now scale with , 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 while reducing quadratically.
Predict the computational work¶
At fixed final time, quartering requires four times as many steps, and halving roughly doubles the number of interior grid points. As a simple measure of work, count the interior point updates:
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.
On paper
Starting from 41 grid points, 600 time steps, and the error measured above, predict the step counts and errors for 81 and 161 points. Calculate the point-update counts using Equation 27. Why are the work ratios slightly larger than eight?
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.
In your notebook
Call advance_diffusion() inside a loop over the three grids, rebuilding the grid and sine profile for each. Every run must end at the same physical time. Record the maximum error against the exact solution and the number of interior point updates. Compare the results with your predictions before interpreting the plot.
# Reuse L, nu, A, k, t_final, r_target, and exact_rate from the sine-profile setup
nx_values = [41, 81, 161]
refinement_results = [] # one dictionary of settings and measurements per grid
for nx in nx_values:
dx = L / (nx - 1)
x = np.linspace(0.0, L, num=nx)
dt_target = r_target * dx**2 / nu
num_steps = int(np.ceil(t_final / dt_target))
dt = t_final / num_steps
sine_profile = np.sin(k * x)
u0 = 1.0 + A * sine_profile
u = advance_diffusion(u0, nu, dx, dt, num_steps)
u_exact = 1.0 + A * np.exp(-exact_rate * t_final) * sine_profile
error = np.max(np.abs(u - u_exact))
work = (nx - 2) * num_steps
refinement_results.append({
'nx': nx, 'num_steps': num_steps, 'error': error, 'work': work,
})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
An error ratio of four gives .
print(f"{'nx':>5} {'steps':>7} {'max error':>12} {'order':>7} "
f"{'updates':>10} {'work ratio':>11}")
previous = None
for result in refinement_results:
if previous is None:
order_text = '-'
ratio_text = '-'
else:
order = np.log(previous['error'] / result['error']) / np.log(2)
work_ratio = result['work'] / previous['work']
order_text = f'{order:.3f}'
ratio_text = f'{work_ratio:.2f}'
print(f"{result['nx']:5d} {result['num_steps']:7d} "
f"{result['error']:12.4e} {order_text:>7} "
f"{result['work']:10d} {ratio_text:>11}")
previous = resultEach 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 . 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 and the number of points as , so . With , this gives : the guide line, anchored to the coarsest result, shows that slope.
errors = np.array([result['error'] for result in refinement_results])
work_counts = np.array([result['work'] for result in refinement_results])
work_guide = errors[0] * (work_counts / work_counts[0])**(-2 / 3)
error_target = 1e-5
fig, ax = plt.subplots(figsize=(5.0, 3.2))
ax.loglog(work_counts, work_guide, color='black', linestyle=':',
label='Slope $-2/3$')
ax.loglog(work_counts, errors, 'o', color='tab:red', label='FTCS')
ax.axhline(error_target, color='black', linestyle='--', label='Error target')
ax.set_xlabel('Interior point updates')
ax.set_ylabel('Maximum error at T = 1')
ax.grid(which='both', alpha=0.3)
ax.legend()
fig.tight_layout();The 41-point grid does not meet the target. Both finer grids do, but the 81-point calculation uses updates, compared with 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.
Self-checks
Recalculate one observed order and one work ratio from the table. Explain the different factors by which error and work change.
If the required maximum error were below , which tested calculation would you choose? How much more work would it require than the choice for 10-5?
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.
Before asking
Read the table in the prompt. In your own notebook, write two sentences: does the error decrease as you expected, and would you recommend another refinement now? Make this judgment before seeing the agent’s response.
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.
I am solving
with fixed endpoints and initial profile . The exact solution is
I use forward Euler in time and a centered second difference in space. Every run ends at , with diffusion number . At fixed , I expect halving the spacing to reduce the error approximately fourfold.
| Grid points | Time steps | Maximum error against the exact solution | Interior point updates |
|---|---|---|---|
| 41 | 600 | 23,400 | |
| 81 | 2,400 | 189,600 | |
| 161 | 9,600 | 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:
Assess whether the evidence justifies that extra computation, considering accuracy and cost.
Recommend one simple inspection of my existing code or settings before running again. Explain what you would compare with the stated problem.
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.
Your verdict
In a short paragraph, say whether you accept, revise, or reject the advice. Name the next item you would inspect and explain why that is more informative than simply requesting a finer grid. If the agent recommended refinement, assess what it expects that run to establish and whether the expected benefit justifies the cost.
Keep the prompt and response with your paragraph, and record the agent used. No further computation or debugging is required for this activity.
Your next action
Before opening the explanation below, decide what you would do next. You may accept the agent’s suggestion or choose a different inspection.
In three short sentences:
Choose: What specific expression, parameter, or setting would you inspect, and what would you compare it with?
Predict: What finding would support your suspected explanation?
Continue: If that check reveals no mismatch, what would you inspect next? You do not need to run code. Record your choice before reading the explanation.
What produced the plateau?
The altered calculation used a diffusivity of 0.303, which is larger than the specified 0.3. Its time-step selection and exact reference still used the intended value 0.3.
Refinement brings this calculation closer to the solution for 0.303, while the error is measured against the solution for 0.3. A finer grid cannot remove that mismatch. The small coefficient error leaves a smooth, bounded profile but prevents the error from approaching zero against the intended reference.
The table exposed a failure of the expected convergence behavior; it did not identify the cause. In an actual investigation, inspecting the implementation and checking the result after a correction would be necessary. Here, the agent helped propose a next step, and you judged whether that proposal was supported by the available evidence.
Looking back at your chosen inspection, would it have exposed this mismatch? If not, was it still a reasonable first step given the evidence you had?