Chapter 1 · Flux differences for an elliptic balance
Assemble a conservative boundary-value problem from face fluxes, trace the effect of boundary conditions and establish a discrete energy identity.
From first principles
Derive a cell equation by integrating the physical balance
Consider steady one-dimensional conduction in a rod with area \(A(x)\), conductivity \(k(x)>0\) and heating per unit length \(s(x)\). Define heat current \(F\) positive to the right. Conservation in any finite interval requires that the current leaving equals the current arriving plus generation. Integrating over cell \(i\) fixes a discrete equation without yet approximating a derivative:
Each shared face must use the same current in its two adjacent cells. To close a face between constant-material regions with no intervening source, integrate Fourier’s law from one cell centre to the other. The heat current is constant on that interval, so it can be taken outside the integral. Defining the face resistance \(R_{i+1/2}\) makes the sign of the temperature drop explicit:
On a uniform homogeneous mesh this reduces to \(kA(T_i-T_{i+1})/h\). Across a material change the half-cell resistances must instead be added. Substituting face currents into the cell balances produces the matrix system. Boundary temperatures, prescribed currents or film laws determine which additional boundary equations close it.
Background · Conservative face flux
Use the same face flux with opposite orientations in neighbouring cells. Interior contributions then cancel in the global balance.
Open full-size diagram
Derivation and applications
Why a flux-only boundary requires a compatibility condition
An insulated or flux-controlled steady diffusion calculation can fail even when each individual face law is correct. Consider a one-dimensional bar of unit area, positive conductivity \(k\), and cell sources \(s_i\) per unit length. Define \(F_{i+1/2}\) as heat current positive to the right everywhere, including both boundaries. At steady state the current leaving the right face minus the current entering the left face equals the total source in that cell:
Summing over cells cancels every shared interior current. No detail of the face-gradient approximation can change the remaining global condition:
With only prescribed fluxes, the discrete gradient also cannot determine a temperature offset. For a connected linear system with positive face transmissibilities, its assembled quadratic form is a sum of squared temperature differences:
The nullspace consists precisely of constant temperatures. A compatible right-hand side gives a family of solutions; prescribe one reference temperature or a weighted mean to select a member. An incompatible right-hand side gives no steady solution. Physically, the imbalance would accumulate energy. Removing one algebraic equation or pinning a temperature without checking global balance can inadvertently create an unreported heat sink.
Worked example
Reconstruct temperatures from compatible flux data
Take three equal cells with source totals \(1,2,1\) W, left incoming current \(F_L=2\) W and right outgoing current \(F_R=6\) W. Internal face currents are successively \(3\) and \(5\) W. With both conductances equal to \(2\) W/K, the temperature drops are \(1.5\) and \(2.5\) K from left to right. For a prescribed arithmetic mean of \(300\) K the temperatures are \(301.833\), \(300.333\) and \(297.833\) K. Adding a common constant would leave every face measurement unchanged.
Second application
Diagnose an unbalanced insulated test
Seal both ends so \(F_L=F_R=0\) but retain the same sources. Their total is \(4\) W. If the combined heat capacity is \(200\) J/K, the heat-capacity-weighted mean temperature must rise at \(4/200=0.0200\) K/s. A steady solver reporting fixed temperatures under those conditions should be checked for a hidden imposed temperature or a dropped residual. The missing four watts have a direct transient interpretation.
Start from this chapter. Start with the difference of two face fluxes. The coefficient varies in space, so leaving its derivative out changes the manufactured source. Use the supplied solve to check the refined nodal error.
OneSimulation laboratory · Measure spatial convergence on a known field
Place fluxes where conservation uses them
Consider steady conduction on \(0<x<L\) with heat flux \(q=-k(x)T'\) and volumetric generation \(f\). Taking unit cross-sectional area, steady energy balance gives \(q'=f\). On uniform nodes separated by \(h\), integrate the balance over a control segment centred on \(x_i\):
A shared face must have the same numerical flux in both adjacent equations, otherwise summing local equations can create an artificial internal source or sink.
Use \(q_{i+1/2}=-k_{i+1/2}(T_{i+1}-T_i)/h\). Then row \(i\) of the discrete operator has diagonal \((k_{i-1/2}+k_{i+1/2})/h^2\) and off-diagonals \(-k_{i\pm1/2}/h^2\). For positive \(k\) the off-diagonals are negative and the diagonal balances them. With zero source, an unconstrained interior value is a weighted average of its neighbours. This relation explains why a source-free discrete conductor with fixed end temperatures cannot develop an interior temperature larger than both ends.
Compute the face law across an interface
For smooth \(k\) an arithmetic average of neighbouring nodal coefficients provides a second-order face approximation on a uniform grid. A sharp material interface calls for a different physical calculation. Consider two half-segments in series with constants \(k_L,k_R\) and no interface storage or contact resistance. The same flux crosses both halves. Adding their temperature drops gives \(T_L-T_R=q[h/(2k_L)+h/(2k_R)]\), hence \(k_{\rm eff}=2/(1/k_L+1/k_R)\). This is a harmonic average for equal half-widths.
With \(k_L=1,\ k_R=9\) W/(m·K) and a 10 K drop over a 0.1 m pair, the effective conductivity is 1.8 W/(m·K) and the flux is 180 W/m². Using the arithmetic mean would give 500 W/m², severely underestimating the resistance of the poorer conductor. In the limit \(k_L\to0^+\), the physical flux tends to zero while that arithmetic estimate remains finite. For unequal layer thicknesses use the actual layer resistances rather than either unweighted average.
Examine uniqueness and the role of the boundary
For homogeneous fixed temperatures and an interior vector \(u\) extended by zero at both ends, grouping adjacent row contributions gives
Each term is nonnegative. Vanishing energy requires a constant vector, and the fixed ends force that constant to be zero. Thus the interior matrix is symmetric positive definite. This reasoning justifies CG and gives a uniqueness argument that does not depend on inspection of a particular numerical matrix. With only prescribed heat fluxes a spatial constant instead remains undetermined. A solution then requires overall heat compatibility and one temperature reference or a mean constraint.
As a check, take constant \(k=1\), \(L=1\), zero end temperatures and generation 2. The exact profile \(T=x(1-x)\) has central value 0.25. Central differences recover its second derivative exactly, so all uniform grid nodes satisfy the balance without truncation error. This successful check verifies signs, boundary handling and the quadratic patch. To measure a convergence order use a smooth field with a nonzero leading truncation term, such as a sine profile, and compare at common physical positions.
Background · Can fixing one node hide an incompatible heat balance?
With specified flux at both ends, a steady source must exactly equal the net heat leaving the domain. After moving boundary terms to the right, the discrete equations have the form \(KT=b\), where \(K\) is symmetric and its rows sum to zero. Consequently
Pinning a temperature removes the undetermined additive constant. If the vector \(b\) fails this sum test, however, the pinned solve creates a reaction at that node. Physically that reaction is an unmodelled heat supply or heat sink. After solving, restore the original equation at the pinned node and inspect its residual. It exposes exactly the load that would have to be supplied to maintain the supposed steady state.
Why fixing one boundary value controls the solution
Suppose the left end of a conducting rod is held at zero temperature and the right end is insulated. A finite system of flux balances may be invertible on one mesh. We would also like a bound which survives refinement. In the continuous problem, use the space \(V=\{v\in H^1(0,L):v(0)=0\}\). Its members have square-integrable first derivatives and a well-defined endpoint value. Every admissible difference between two temperature fields belongs to this same space. The fundamental theorem of calculus and Cauchy–Schwarz give
The second inequality follows by integrating the first and bounding its inner integral by the full derivative norm squared. Thus a small temperature gradient forces the temperature itself to be small in this particular space. Take a possibly discontinuous conductivity with \(0<k_0\le k(x)\le k_1\) almost everywhere and a square-integrable heat source \(f\). Testing the balance and integrating once gives \(a(u,v)=\ell(v)\) for every \(v\in V\), with
The upper bound on conductivity gives
The lower bound gives \(a(v,v)\ge k_0\|v'\|_2^2\), called coercivity. The endpoint inequality bounds \(|\ell(v)|\) by \(L\|f\|_2\|v'\|_2/\sqrt2\). These are the hypotheses of the Lax–Milgram theorem on the Hilbert space with norm \(\|v'\|_2\). Consequently the weak solution exists and is unique. For two loads, subtract the weak equations and test with their solution difference. Cancelling one derivative norm gives
Every conforming discrete subspace inherits the same estimate.
How large a change can a load error produce?
In scaled units let \(L=1,\ k=2,\ f=3\). Integration of \(-2u''=3\), first from the insulated end and then from the fixed end, gives
Its derivative norm is
The theorem guarantees at most \(3/(2\sqrt2)=1.0607\). Raising the source everywhere by \(0.12\) changes that norm of the difference by \(0.06/\sqrt3=0.03464\), within the guaranteed \(0.04243\). The estimate also applies to nonuniform perturbations of the same load norm. If both ends are insulated, constants have zero derivative and can be added freely. A net heat input then rules out steady balance altogether.
Practise on sheet 1 · A longer rod with a clamped or insulated left end. Further reading · Heidelberg University · Lecture Notes on Scientific Computing with Partial Differential Equations · §5.5 Abstract Existence Theory, Theorem 5.22 (Lax–Milgram), and §6.3 Mixed Problem.
Eliminate boundary values with the correct sign
With four intervals on a unit rod, fixed left temperature 10, fixed right temperature 20 and zero source, multiply each row by \(h^2/k\). The three unknowns then satisfy a tridiagonal system with diagonal two, off-diagonal minus one and load \((10,0,20)^T\). Moving a fixed value to the right changes its sign, producing positive boundary contributions here. Solving gives the linearly spaced interior temperatures 12.5, 15 and 17.5. Every discrete face reports the same flux for constant \(k\).
This deliberately simple case isolates boundary elimination and sign conventions. Reversing only one load sign can generate a plausible-looking smooth curve with entirely wrong end-to-end transport. After checking the values, also sum all interior balances and verify cancellation of the internal face contributions. The resulting global statement includes only boundary fluxes and any source integrated over the interior control volumes.
Prove a discrete maximum principle from the face balances
Let positive conductances \(G_{i-1/2}\) and \(G_{i+1/2}\) connect each internal node to its neighbours, with both end temperatures specified. In the absence of internal sources its balance reads \(G_{i-1/2}(u_i-u_{i-1})+G_{i+1/2}(u_i-u_{i+1})=0\). Dividing by the sum of the conductances makes \(u_i\) a convex combination of its two neighbours. If a strict global maximum occurred inside the domain above both prescribed boundary values, its neighbours would each have to equal this maximum. Repeating along the connected grid would carry the same value to a boundary, contradicting the assumption.
The same reasoning applied to the negative field bounds the minimum. With a nonnegative internal heat source \(s_i\) on the right, an interior minimum below both boundaries would have both outgoing temperature differences nonpositive. Their positive weighted sum cannot equal a positive source, and if the sum is zero, propagation again carries the minimum to the boundary. A positive source may raise an interior maximum while preserving the lower comparison bound. Negative face conductances or a disconnected component invalidate the argument; symmetry and a small algebraic residual do not by themselves restore it.
Compare two thermal loads without inverting their matrices
Connect internal nodes 1 and 2 to end temperatures zero and ten, using consecutive conductances 1, 2 and 4 W/K. With no source the equations are
The first gives \(u_1=2u_2/3\), and the second gives
Both values lie between the boundary temperatures. The common leftward heat flow has magnitude \(40/7\) W, checked independently from each of the three temperature drops times its conductance.
Add a heat source of 7 W at node one. The difference \(v\) between new and old solutions has zero boundary values and satisfies
The second relation gives \(v_1=3v_2\), so
Both internal states warmed, consistent with the comparison principle applied to the difference. The additional outflow at the left boundary is \(1\cdot3=3\) W and at the right is \(4\cdot1=4\) W, accounting for the full applied source.
This provides two independent implementation tests. Conservation checks that the boundary power change equals the injected power. Monotonicity checks the signs of all changes in the field. A sign error in a face contribution can violate one of these checks even while the computed algebraic residual for the incorrectly assembled matrix is tiny. Both tests use physically accessible quantities and remain meaningful when no exact closed-form solution of a complex geometry is available.
The argument extends to a connected graph, since a weighted average at a maximising node requires equality along every positive-conductance edge. This observation is useful for testing an unstructured implementation. Deliberately disconnecting an entirely insulated component produces a free constant there, so boundary comparisons cannot control that component until a temperature reference or independent constraint is supplied.
Change parameters · Flux differences for an elliptic balance
Change one input at a time and compare the recalculated curves with the argument above. The browser evaluates this small model locally; the accompanying numerical values state its assumptions and reference checks. Reset restores the reference inputs, and the data can be downloaded as CSV.
Study the full derivation
Choose the physically admissible wave in a conservative update · Spatial discretisation and field equations
A discontinuous scalar flow can satisfy integral conservation in more than one way. Derive the shock speed, use a convex entropy to distinguish a compression from an expansion and build a finite-volume flux from the resulting local solution.
Chapter 2 · Weak forms and finite elements
Derive a variational statement by integration by parts, assemble element matrices for a one-dimensional rod and explain what the Galerkin solution minimises.
From first principles
Obtain the weak diffusion problem by moving one derivative
For a stationary diffusion problem \(-\nabla\cdot(k\nabla u)=f\), suppose temperature is prescribed on part of the boundary and the outward flux \(q_n=-k\nabla u\cdot\mathbf n\) on the remainder. A classical second derivative may not exist across a material interface. Instead multiply the conservative equation by a smooth test function \(v\) that vanishes where \(u\) is prescribed. The divergence theorem moves one derivative from the flux onto \(v\):
Approximate \(u\) with continuous element shape functions \(N_j\) that are differentiable inside each element. Choose each allowable shape function as the test function. Linearity then yields element contributions
Neighbouring elements contribute to the same global unknown at a shared node. Adding their contributions enforces weak equilibrium. The flux sign in the boundary term follows from an outward-positive definition; switching to prescribed inward heat supply reverses that sign in the load vector.
Background · Weak form
Integration by parts lowers the derivative requirement. Essential and natural boundary data enter the discrete system differently.
Derivation and applications
How a Robin boundary enters both the stiffness matrix and the load
A convecting boundary couples an unknown surface temperature to an ambient temperature. Unlike a prescribed heat source it contributes to both sides of the assembled equations. Consider steady diffusion \(-\nabla\cdot(k\nabla T)=s\) in a two-dimensional region of unit thickness, with \(k>0\). On a straight boundary segment impose the empirical film law \(-k\nabla T\cdot\mathbf n=h(T-T_\infty)\) using the outward normal. Multiply the field equation by a test function \(v\) vanishing on prescribed-temperature boundaries, integrate, and apply the divergence theorem:
Substitution on the film boundary \(\Gamma\) places the unknown surface term on the left and the ambient contribution on the right:
with any other natural boundary terms added separately. To assemble one linear edge of length \(\ell\), use edge functions \(N_1=1-\xi\), \(N_2=\xi\), \(\xi\in[0,1]\). Insert the nodal interpolation for \(T\) and choose each \(N_i\) as test function. Constant \(h,T_\infty\) give
The off-diagonal term is present because both nodes influence temperature across the same edge. In the limit \(h=0\) the boundary is insulated. A very large film coefficient constrains the temperature toward ambient but can introduce a large stiffness contrast.
Worked example
Assemble a convecting edge by hand
Use a one-metre out-of-plane thickness, \(\ell=0.300\) m, \(h=20.0\) W/(m² K) and \(T_\infty=290\) K. Then \(K_\Gamma\) has diagonals \(2.00\) W/K and off-diagonals \(1.00\) W/K. The load is \((870,870)\) W. At nodal temperatures \(300\) and \(310\) K the film residual \(K_\Gamma T-f_\Gamma\) is \((40,50)\) W. The sum \(90\) W agrees with \(h\ell[(300+310)/2-290]\).
Second application
Test a constant solution before using the boundary routine
Set both temperatures to \(290\) K, the ambient value. Each row has sum \(3.00\) W/K, so every residual is \(3(290)-870=0\). If the code includes the ambient load but forgets the matrix, it predicts \(1740\) W of heating at thermal equilibrium. This constant-field patch test detects sign errors and omission of the surface matrix independently of the volume mesh.
Reduce the differentiability required by equilibrium
A rod is fixed at \(x=0\), pushed by a distributed load \(f\) and by an end force \(t\) at \(x=L\). Axial displacement \(u\) satisfies \(-(EAu')'=f\), \(u(0)=0\) and \(EAu'(L)=t\). The product \(EA\) is positive. A trial profile assembled from linear pieces has jumps in its derivative, so differentiating it twice pointwise is unsuitable. Instead multiply the strong equation by a test displacement \(v\) vanishing at the fixed end and integrate by parts once.
The resulting equation is
Only first derivatives are required. The fixed displacement is imposed directly on trial and test spaces; the end traction appears in the load functional. This clarifies why prescribing both force and displacement independently at the same end can overconstrain a second-order problem. The test functions represent allowable virtual displacements, and the integral identity expresses equality of internal and external virtual work.
Background · Why can the derivative jump while the displacement stays continuous?
At a bonded interface with no concentrated force, displacement and axial force are continuous. If \(EA\) jumps, the strain \(u'\) can jump inversely even though the product \(EAu'\) is continuous. For a continuous piecewise linear displacement, the weak first derivative is the ordinary piecewise constant slope. The squared-gradient energy is therefore finite.
A displacement jump is different. Replacing a jump of size \(d\) by a straight ramp over width \(\delta\) costs strain energy \(EA d^2/(2\delta)\) for constant positive stiffness, which diverges as the ramp shrinks. A standard conforming displacement space encodes this distinction. If the mechanics really allow slip, the interface needs its own model and a space which permits the two traces to differ.
Assemble one element and connect it to its neighbour
On an element from \(x_i\) to \(x_{i+1}\) of length \(h\), use shape functions \(N_1=1-s,\ N_2=s\) with \(s=(x-x_i)/h\). Their physical derivatives are \(-1/h,\ 1/h\). For constant \(EA\), integrating products \(EA N'_aN'_b\) gives the matrix \((EA/h)\left(\begin{smallmatrix}1&-1\\-1&1\end{smallmatrix}\right)\). A constant distributed load contributes \(fh(1,1)^T/2\). Summing element contributions for a shared global node enforces balance there without prescribing the internal traction manually.
Take \(L=1,\ EA=1,\ f=2,\ t=0\) in consistent units and use two equal elements. After eliminating the fixed displacement, the stiffness matrix is \(\left(\begin{smallmatrix}4&-2\\-2&2\end{smallmatrix}\right)\) and the load is \((1,0.5)^T\). Solving gives
The exact solution is \(2x-x^2\) and agrees at both nodes. Inside the first element at \(x=0.25\), the linear interpolant gives 0.375, whereas the exact value is 0.4375. Nodal agreement can coexist with a substantial interior error.
Assemble a physical triangle from a reference element
A line element has one length scale. A triangle can stretch, rotate and shear, so the element area alone cannot determine its diffusion matrix. Start with the reference vertices \((0,0),(1,0),(0,1)\) and the linear shape functions \(1-\xi-\eta,\xi,\eta\). Send the reference triangle to a physical cell with vertices \(P_0,P_1,P_2\) by \(x=P_0+J(\xi,\eta)^T\), where the columns of \(J\) are \(P_1-P_0\) and \(P_2-P_0\). For a nondegenerate triangle, the chain rule and area transformation give
To see why the inverse transpose occurs, take an arbitrary displacement \(d\widehat x\). Both gradients must describe the same change in a shape function. Thus \((\nabla_xN_i)^TJ\,d\widehat x=(\nabla\widehat N_i)^Td\widehat x\) for every such displacement. For unit isotropic conductivity, the transformed gradients are constant and the physical stiffness entries reduce to
with \(|T|=|\det J|/2\). A constant cell load \(f\) contributes \(f|T|/3\) at each vertex because each linear shape function has mean \(1/3\).
A sheared cell and an exact affine-field check
Take \(P_0=(0,0), P_1=(2,0), P_2=(1,1)\). The columns of \(J\) are \((2,0)\) and \((1,1)\), so the cell area is \(1\). Applying \(J^{-T}\) to the three reference gradients gives \((-1/2,-1/2),(1/2,-1/2),(0,1)\). Their dot products and the load \(f=3\) yield
Every row sums to zero because a constant field has zero gradient. For a more discriminating test use \(u=x+2y\), with vertex values \(U=(0,2,3)^T\). Weighting the three gradients by these values gives \((1,2)\). The physical integral of its squared gradient equals \(1(1^2+2^2)=5\), and direct multiplication gives \(U^TKU=5\). A transposed mapping error can pass the constant test and fail this second one.
Practise on sheet 1 · Two triangles of the same area. Further reading · Heidelberg University · Lecture Notes on Scientific Computing with Partial Differential Equations · §7.4 Pₖ Finite Elements and §7.6 Construction of the Finite Element Stiffness Matrix.
Identify the energy that is best approximated
Let \(a(u,v)=\int EA\,u'v'\) and denote the external work by \(\ell(v)\). The discrete solution \(u_h\) satisfies \(a(u_h,v_h)=\ell(v_h)\) for every test function from its finite-dimensional space. The continuous solution satisfies the same equation for every such test, so \(a(u-u_h,v_h)=0\). This Galerkin orthogonality means the error is perpendicular to the trial space in the energy inner product. For any other admissible discrete \(w_h\), write \(u-w_h=(u-u_h)+(u_h-w_h)\) and expand its squared energy norm. The cross term vanishes and \(\|u-w_h\|_a^2=\|u-u_h\|_a^2+\|u_h-w_h\|_a^2\).
Thus the conforming Galerkin solution is the best energy approximation in its space for this symmetric linear problem and exact integration. The statement concerns a specific norm and model. It does not guarantee pointwise optimal stresses or carry unchanged into nonsymmetric transport problems. In the rod example the computed strain is constant on each element, replacing a linearly varying exact strain. Refinement improves this derivative field even when a table of nodal displacements already looks exact.
Recover a support reaction
The reaction at a prescribed-displacement node is hidden if one inspects only the reduced interior system. Assemble all element internal forces \(Ku_h\) before discarding constrained rows, then subtract the full external load vector. The entries at free degrees of freedom should be near zero; the entry at a prescribed degree of freedom gives the reaction in the chosen sign convention.
In the uniformly loaded rod, the first element strain is
Its internal nodal force at the left is \(-1.5\), while the first node receives an external distributed-load share of \(+0.5\). Their difference \(-2\) is the support reaction. It balances the total applied load \(2\cdot1=2\). Looking only at the derivative in the first element would have reported magnitude 1.5, missing that load share. A reaction from assembled balance and a stress recovered by pointwise differentiation are related but distinct quantities on a finite mesh.
Obtain actual norm errors from the Galerkin property
For \(-u''=f\) on the unit interval with homogeneous Dirichlet values, the elementary energy inner product is \(a(u,v)=\int u'v'\). Let \(I_hu\) be the continuous piecewise-linear interpolant of a sufficiently smooth exact solution at mesh nodes. On each element its slope is the average of \(u'\). Every linear finite-element test function \(v_h\) has constant derivative on that element. Consequently
Summing proves global energy orthogonality.
The Galerkin solution satisfies the same orthogonality, and positive definiteness gives uniqueness. Thus \(u_h=I_hu\) in this one-dimensional, constant-coefficient problem with exactly integrated load and matching boundary values. Nodal errors vanish, although the field and derivative between nodes can still be inaccurate. Variable coefficients inside an element generally destroy the simple telescoping argument because the factor multiplying \(v_h'\) is no longer constant. The result also should not be transferred to multidimensional triangulations without proof.
Compare nodal, field and flux accuracy for one solution
Choose \(u=x(1-x)\), so \(f=2\). On an element starting at \(a\) write \(s=x-a\in[0,h]\). Subtract the straight interpolant from the parabola to get \(u-u_h=s(h-s)\), vanishing at both nodes and attaining \(h^2/4\) at the element centre. Its derivative is \(h-2s\); the exact and numerical slopes agree at the midpoint but differ by magnitude \(h\) at each endpoint taken from that element. Testing only the midpoint slope or the nodal values would entirely conceal these other discrepancies.
Compute the squared energy error on this element:
With \(1/h\) equal elements, the global energy error is \(h/\sqrt3\). Similarly the element squared field error is \(\int_0^hs^2(h-s)^2ds=h^5/30\), giving global \(L^2\) error \(h^2/\sqrt{30}\). For \(h=1/4\), the two errors are approximately 0.14434 and 0.01141; the maximum field error is 0.015625. Halving the mesh width halves the energy error but divides the field error by four. All these measurements concern the very same numerical solution whose nodal error is exactly zero.
For a physical diffusion flux with constant conductivity one, flux error equals minus derivative error. A cell-averaged flux test is also special here: the numerical slope equals the exact average slope on each element for the same reason used in the proof. To verify local flux resolution, compare at more than a midpoint or a cell average and retain the measure used for convergence. A reported order is a statement about an observable and a norm as well as a finite-element space.
These formulas also identify a misleading manufactured test: if an automated comparison stores only nodal differences, the estimated order is undefined because both coarse and fine errors vanish. Adding independently evaluated quadrature points inside elements exposes the field error immediately. To check a flux implementation, use a quadrature rule capable of resolving the squared linear derivative error; a one-point midpoint rule would again report zero despite the nonzero exact energy norm.
Distribute a moving point source in a weak form
A one-dimensional Poisson problem has a concentrated source \(Q\delta(x-a)\). Its weak load against a linear hat function is \(Q\phi_i(a)\), so the two adjacent degrees of freedom share it in proportion to their shape functions.

Read values from the plot
| Source position within one element | Left basis function | Right basis function |
|---|---|---|
| 0 | 1 | 0 |
| 0.25 | 0.75 | 0.25 |
| 0.5 | 0.5 | 0.5 |
| 0.75 | 0.25 | 0.75 |
| 1 | 0 | 1 |
Change parameters · Distribute a moving point source in a weak form
Change one input at a time and compare the recalculated curves with the argument above. The browser evaluates this small model locally; the accompanying numerical values state its assumptions and reference checks. Reset restores the reference inputs, and the data can be downloaded as CSV.
Study the full derivation
Bound diffusion error by balancing a reconstructed flux · Spatial discretisation and field equations
A temperature field from a finite-element calculation looks smooth. Reconstruct a heat flux which exactly balances the source, then derive an upper bound for the true energy error without knowing the exact temperature.
Problem sheet 1 · Flux balances and virtual work
Choose the correct conductance at an interface, test pure-flux compatibility and assemble a rod with unequal stiffnesses.
Preserve heat flow across unequal layers
A wall has two layers, 0.02 m at \(k=2\) W/(m·K) and 0.06 m at \(k=12\) W/(m·K). The outer faces are held at 350 K and 320 K, respectively. Find the common flux, the interface temperature and the effective conductivity over the full thickness.
Worked solution
The resistances per unit area are \(0.02/2=0.01\) and \(0.06/12=0.005\) m²·K/W. Total resistance is 0.015, so the flux magnitude is \(30/0.015=2000\) W/m² from hot to cold. The first drop is \(2000(0.01)=20\) K, giving an interface temperature of 330 K.
The effective conductivity is \(0.08/0.015=5.333\) W/(m·K). Equal-width averaging would ignore the different thicknesses. Substituting this conductivity across the full wall reproduces the same flux.
Explore the related calculation with adjustable inputs. Vary series resistances and observe their fractions of the total drop. Divide by the stated bulk resistance when converting dimensional values to a comparison.
Check a pure-flux problem
On \(0\leq x\leq2\), the steady flux obeys \(q'=3\) in consistent units. The prescribed endpoint fluxes, both positive along increasing \(x\), are \(q(0)=2\) and \(q(2)=7\). Is a steady state possible? Correct the right flux. For \(k=1\), find a compatible temperature with mean temperature zero.
Worked solution
Integrating requires
The supplied difference is 5, so no steady solution satisfies both data. Take \(q(2)=8\), giving \(q=2+3x\).
Because \(q=-T'\), \(T=C-2x-1.5x^2\). Its average over the interval is \(C-2-2=C-4\), hence \(C=4\). The mean fixes the otherwise arbitrary temperature offset while leaving flux unchanged.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Assemble two rods in series
Two equal elements of unit length have \(EA=2\) and \(EA=6\) in consistent units. Fix the left node, apply a unit tensile load on the right and omit distributed load. Assemble the reduced matrix, solve for displacements and verify the axial forces and strain energy.
Worked solution
Assembly gives
The second row gives \(u_2-u_1=1/6\). The first then gives \(2u_1=1\), hence
The forces are \(2(1/2)=1\) and \(6(1/6)=1\). The stored energies sum to \(2(1/2)^2/2+6(1/6)^2/2=1/3\), also \(u^Tb/2=(2/3)/2\). This verifies both continuity of axial force and consistency of the assembled work.
Explore the related calculation with adjustable inputs. Check a small conservative conductance system under a changed load; the same assembled balance form applies to the rod stiffness calculation.
A longer rod with a clamped or insulated left end
For a rod of length \(2\), use \(k=4\), a unit distributed load, zero temperature on the left and insulation on the right. Compute the exact derivative norm and its coercivity bound. Then insulate the left end too. Which compatibility condition fails, and what further information would be needed if it held?
Worked solution
The flux condition gives \(u'=(2-x)/4\), so \(\|u'\|_2^2=(1/16)\int_0^2(2-x)^2dx=1/6\), giving \(0.40825\). The load norm is \(\sqrt2\). The estimate gives
The anchored solution therefore satisfies the bound.
Testing a two-insulated-end balance with the constant test function \(1\) requires
The present load integrates to \(2\). A zero-net load would restore compatibility, but \(u+C\) would solve for every constant \(C\). A prescribed mean temperature, for example, selects one representative.
Explore the related calculation with adjustable inputs. Change the propagation length scale and mesh resolution to compare shooting sensitivity with a boundary-value discretisation.
Revisit chapter 1 · Why fixing one boundary value controls the solution.
Two triangles of the same area
Stretch the reference triangle to vertices \((0,0),(4,0),(0,1/4)\). Find the gradients associated with its two axis vertices and their diagonal stiffness entries. Compare their ratio with the reference triangle, and explain why a fixed area does not ensure comparable directional stiffness.
Worked solution
Here \(J=\operatorname{diag}(4,1/4)\) has determinant one. The physical gradients are \((1/4,0)\) and \((0,4)\). Multiplying their squared lengths by the cell area \(1/2\) gives \(K_{11}=1/32\) and \(K_{22}=8\).
The ratio \(K_{22}/K_{11}=256\). On the reference triangle both entries are \(1/2\). A unit change in nodal value over the short altitude gives a much larger derivative. Area fixes the product of stretches, while gradient amplification depends on inverse stretches in each direction. This ratio describes these entries. The unrestricted element also has a constant null mode.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Revisit chapter 2 · Assemble a physical triangle from a reference element.
Chapter 3 · Finite volumes and moving fronts
Derive an upwind transport update by conservation, interpret the Courant number as a fraction of cell contents and determine what conservation says about front speed.
From first principles
Derive a conservative update from storage in a cell
Consider the one-dimensional conservation law \(u_t+\partial_x f(u)=0\) with no distributed source. Let \(\bar u_i\) denote the average over cell \(i\) of width \(\Delta x\). The integral of \(u\) over the cell is what the discrete variable stores. Integrate first over the cell and then over one time step. Only fluxes crossing the two faces can change its inventory:
Replace each time-averaged face flux by one numerical function \(\hat f\) of neighbouring states, using the same value from both sides. For constant positive advection speed \(a\), the state reaching a face comes from upstream. With piecewise-constant cell data and \(C=a\Delta t/\Delta x\le1\) this gives
The update conserves total mass on a periodic grid because every internal face cancels. Nonlinear fluxes also need a rule selecting the physically admissible interface state, especially when a jump separates two different initial cell values.
Background · Courant number
For scalar advection this compares a transported distance with a cell width. An admissible range depends on the spatial method and time integrator jointly.
Derivation and applications
Quantify the quadratic quantity lost by an upwind update
A conservative finite-volume method for advection preserves the sum of cell contents under periodic boundary conditions. It need not preserve their contrast. Consider the constant-speed transport equation \(u_t+a u_x=0\) with \(a>0\), uniform cells of width \(\Delta x\) and periodic indexing. Exact translation preserves \(\int u^2\,dx\). The first-order upwind scheme transports a fraction \(C=a\Delta t/\Delta x\) of a cell's content across its right boundary per step:
For \(0\le C\le1\) this is a convex combination and cannot create a value outside its two inputs. To see precisely how much variation is removed, square one update and complete a difference square:
Sum over all cells. Periodicity allows the shifted sum of old squared values to be relabelled. The exact discrete identity, with \(E^n=(\Delta x/2)\sum_i(u_i^n)^2\), becomes
This loss vanishes for spatially constant data and for \(C=1\), when the update shifts by one complete cell. Strong cell-to-cell jumps dissipate much more of the quadratic quantity than smooth profiles sampled with the same grid. Total mass still telescopes exactly; the two balance laws diagnose different aspects of accuracy.
Worked example
Follow one step on four periodic cells
Take \(\Delta x=1\), \(C=1/2\) and initial averages \((1,1,0,0)\). The updated values are \((0.5,1,0.5,0)\). Both arrays sum to two. The quadratic energy falls from \(1.00\) to \(0.750\). There are two unit jumps at the start, and the loss formula gives \((1/2)(1/2)(1/2)(2)=0.250\), accounting for the full change.
Second application
Use an alternating pattern as an instability detector
For \((1,-1,1,-1)\) each neighbour has opposite sign, so one step multiplies the amplitude by \(1-2C\). At \(C=1/2\) all variation disappears in one step although the exact wave would keep its amplitude. At \(C=1.10\) the factor is \(-1.20\) and energy grows by \(1.44\). The sign reversal in \(C(1-C)\) therefore predicts growth at this resolved wavelength. Conservation of the zero mean still holds in both experiments and alone cannot detect the instability.
Start from this chapter. Construct a shared flux on each interior face so neighbouring cell balances use opposite signs. Examine how resolving the source wavelength changes the computed field at fixed residual tolerance.
OneSimulation laboratory · Measure spatial convergence on a known field
Store quantities over cells
Consider a passive concentration satisfying \(u_t+(au)_x=0\) with positive constant speed \(a\) on a periodic line. Let \(\bar u_i=h^{-1}\int_{x_{i-1/2}}^{x_{i+1/2}}u\,dx\) be its cell mean. Integrating the conservation law in space and time shows that every change in cell inventory comes from fluxes through its two faces. If neighbouring cells use the same face flux, summing all updates cancels every internal transfer exactly. On a periodic line the total stays fixed, even for a discontinuous concentration.
For positive speed, material reaching the right face during a short step comes from the cell to its left. Approximate the outgoing state by that cell’s mean, giving \(F_{i+1/2}=a\bar u_i\). Forward Euler in time yields
where \(C=a\Delta t/h\). For \(0\leq C\leq1\) this is a convex average, preserving the range of neighbouring values. At \(C=1\) the entire array shifts exactly by one cell per step. If \(a<0\), information comes from the other side of the face and the upwind direction must reverse.
Identify the source of artificial spreading
Start with one cell mean equal to one and zeros everywhere else. With \(C=1/2\), one step gives adjacent means \(1/2,1/2\). A second step gives \(1/4,1/2,1/4\), while the total remains one. Exact advection over two such steps shifts the original pulse by one cell with no change in shape. The scheme has conserved mass yet broadened the pulse. Peak height or variance therefore tests information not supplied by a global balance.
For smooth \(u\), Taylor-expand the upwind update in space and time. Replace the leading \(u_{tt}\) using the exact transport equation, \(u_{tt}=a^2u_{xx}\). The leading modified equation is
The bracket acts as numerical diffusivity. It is positive for the monotone range and vanishes at \(C=1\). This local smooth expansion helps interpret observed spreading, but the Taylor expansion itself does not hold across a jump.
Choose a flux when speed depends on the state
For a nonlinear conservation law \(u_t+f(u)_x=0\), characteristics can intersect and create a discontinuity. Enclose a moving jump in a thin control volume. The net flux imbalance fixes its speed \(s=(f(u_R)-f(u_L))/(u_R-u_L)\). For Burgers flux \(f=u^2/2\) with left state 2 and right state 0, this gives \(s=1\). The faster characteristics on the left overtake the slower ones to form a shock. Reversing these states produces a spreading fan under the entropy condition even though the algebraic jump formula alone would still supply a speed.
A numerical face flux must be consistent when the two cells agree and must incorporate information from both sides when a nonlinear wave can travel either way. A conservative method that converges can reproduce the weak jump balance, while selection of a physically admissible solution also requires an entropy criterion. For practical assessment, monitor total inventory, motion of the front, overshoot and the number of cells over which it is smeared. The four measurements address distinct properties, and reducing one defect need not reduce all of them.
Move the control surface instead of the grid
Across a front moving with speed \(s\), flux in the front’s own frame is \(f(u)-su\). The jump relation enforces equality of this quantity on both sides. For the Burgers jump from 2 to 0 with speed one, the left flux in the moving frame is \(2-1\cdot2=0\), and the right flux is also zero. The laboratory flux differs across the front because a moving interface is sweeping conserved material through stationary space.
This distinction helps when checking a simulation by counting material in a region that tracks a front. Differentiating an integral over moving endpoints adds boundary-motion terms. In a periodic fixed window the update should conserve total amount without those extra terms. In a moving measurement window, physical transport through the window and motion of the window both influence the recorded inventory, even under a perfectly conservative scheme.
Distinguish a conservative jump from the physical weak solution
For inviscid Burgers flow \(u_t+(u^2/2)_x=0\), integrating conservation across a moving jump gives the Rankine–Hugoniot speed \(s=[f]/[u]=(u_L+u_R)/2\). It uses only balance, so a discontinuity with that speed satisfies the weak conservation equation for either orientation of its left and right states. To select the physically relevant solution one needs an entropy condition. For a compressive shock characteristic speeds enter it from both sides: \(u_L>s>u_R\). If \(u_L<u_R\), the characteristics separate and a continuous rarefaction fan fills the gap.
For example the entropy \(\eta(u)=u^2/2\) has entropy flux \(q(u)=u^3/3\), because \(q'=\eta'f'\). A jump produces distributional entropy \([q]-s[\eta]\), which must be nonpositive for a dissipative solution. At equal-magnitude opposite states the entropy jump \([\eta]\) is zero, so orientation alone changes the sign of the entropy production. A conservative scheme can preserve every cell total correctly yet converge to an inadmissible expansion shock if it fails this additional condition.
Choose the correct interface flux for two opposite Riemann data
Take \(u_L=-1,\ u_R=1\). Both endpoint fluxes equal one half, and the jump-speed formula gives zero. Holding this discontinuity fixed would conserve the cell totals. Its entropy production, however, is
The admissible Riemann solution is the self-similar fan: at coordinate \(\xi=x/t\), \(u=-1\) for \(\xi\le-1\), \(u=\xi\) between minus one and one, and \(u=1\) for \(\xi\ge1\). At the interface \(\xi=0\), the flux is therefore zero. Using an arithmetic average of the two endpoint fluxes would instead maintain the inadmissible jump.
For a finite-volume update with \(\Delta t/\Delta x=0.5\) and initially constant states on either side, the neighbouring left cell changes from \(-1\) to \(-1-0.5(0-0.5)=-0.75\). The right cell changes from one to \(1-0.5(0.5-0)=0.75\). Their sum remains zero. A direct integration of the fan gives the same cell averages: the disturbance occupies half of each cell and linearly brings that half from its far-state value toward zero. Thus both conservation and the local wave pattern can be verified independently.
Reverse the initial states to \(u_L=1,\ u_R=-1\). The zero-speed jump now has entropy production \(-2/3\), and both families of characteristics enter it. Its correct interface flux is one half. The same numerical update then leaves both neighbouring cell averages unchanged, exactly as required for a stationary shock. Testing both orientations is more revealing than testing a single conserved jump: they have identical endpoint flux magnitudes and the same Rankine–Hugoniot speed but different physically admissible interface states.
A further integration test shifts the interface by precisely one cell and reruns the update. On a uniform periodic grid with unchanged physical states, the new solution should be a one-cell translation of the old one. A difference between the two calculations could reveal an indexing error in the face flux even when a global conservation diagnostic remains identically zero.
Measure numerical spreading in a conservative transport step
Start with all mass in one cell. For positive velocity the explicit upwind update keeps fraction \(1-C\) and transfers fraction \(C\) to the next cell each step. Thirty updates produce a binomial distribution on an unbounded uniform grid.

Read values from the plot
| Cell offset from initial pulse | Courant number 0.25 | Courant number 0.5 | Courant number 0.85 |
|---|---|---|---|
| 0 | 0.00017858 | 9.3132e−10 | 1.9175e−25 |
| 8 | 0.15931 | 0.005451 | 1.1933e−12 |
| 15 | 0.0019305 | 0.14446 | 5.9335e−6 |
| 22 | 3.3308e−8 | 0.005451 | 0.042007 |
| 30 | 8.6736e−19 | 9.3132e−10 | 0.0076308 |
Change parameters · Measure numerical spreading in a conservative transport step
Change one input at a time and compare the recalculated curves with the argument above. The browser evaluates this small model locally; the accompanying numerical values state its assumptions and reference checks. Reset restores the reference inputs, and the data can be downloaded as CSV.
Study the full derivation
Choose the physically admissible wave in a conservative update · Spatial discretisation and field equations
A discontinuous scalar flow can satisfy integral conservation in more than one way. Derive the shock speed, use a convex entropy to distinguish a compression from an expansion and build a finite-volume flux from the resulting local solution.
Chapter 4 · Time-dependent diffusion
Derive the diffusion time-step restriction from two independent arguments and compare explicit and implicit decay of spatial modes.
From first principles
Derive the explicit heat step and its grid-dependent time scale
Take the heat equation \(T_t=\alpha T_{xx}\) with constant positive diffusivity on a uniform one-dimensional grid. Fourier conduction through each side of a cell produces a temperature update proportional to the difference of the two neighbour gradients. With forward Euler timing, collect those fluxes to obtain
When \(0\le r\le1/2\) the new temperature is a convex average of three old ones, preserving bounds on a source-free grid. To check whether a higher step could still be stable for all periodic grid disturbances, substitute \(T_j^n=g^n e^{ij\theta}\), where \(j\) is the node index. The amplification simplifies to
The alternating mode at \(\theta=\pi\) gives \(g=1-4r\), so \(|g|\le1\) again requires \(r\le1/2\). Halving spatial spacing therefore quarters the largest explicit time step for this discretization. Implicit stepping changes this restriction but still has to resolve any transient relevant to the measurement.
Derivation and applications
Can an energy-stable heat step create an alternating transient?
A diffusion mode should decay rather than oscillate. To distinguish decay of a norm from preservation of sign, examine the finite-element or finite-volume semidiscrete system \(M\dot u+Ku=0\), with symmetric positive definite mass matrix \(M\) and thermal stiffness \(K\) positive semidefinite. An eigenvector satisfying \(Kv=\lambda Mv\) has scalar amplitude \(y(t)\) obeying \(y'=-\lambda y\). A generalized \(\theta\) step applied to this mode gives
For Crank–Nicolson take \(\theta=1/2\). The factor \(G=(1-z/2)/(1+z/2)\) has \(|G|\le1\) for all \(z\ge0\) but changes sign when \(z>2\). An initial grid-scale component can therefore alternate in time. To test a remedy, replace the first full step by two half backward-Euler steps. Their combined factor is
Thereafter return to the second-order Crank–Nicolson update. After \(n\) further full steps the mode amplitudes, with and without the initial damping, are
For small \(z\), both startup strategies agree through first order, while for large \(z\) the two half steps strongly suppress the unresolved mode. This argument explains a startup treatment for nonsmooth initial data; sign preservation of every physical grid value is a stronger matrix property than sign preservation of one mode.
Worked example
Check damping of a near-grid-scale eigenmode
Take \(\lambda=2000\) s⁻¹ and \(\Delta t=0.0100\) s. Then \(z=20\). A single Crank–Nicolson step leaves \(-9/11=-0.818\) of the amplitude; two backward-Euler half steps leave \(1/121=0.00826\). The exact amplitude factor is
Both discrete results are bounded, but the startup treatment removes almost all of a mode that the time grid cannot resolve.
Second application
Check the cost for a physically slow component
For the same mesh and step, a slow mode with \(\lambda=2.00\) s⁻¹ has \(z=0.0200\). Crank–Nicolson gives \(0.99/1.01=0.980198\), the startup gives \(1/1.01^2=0.980296\) and the exact factor is \(0.980199\). The slow component changes by less than \(10^{-4}\) in this comparison. A timestep must still resolve a transient that is itself part of the desired output.
Discretise space and time separately
A heat pulse in a thin insulated rod smooths over time according to \(u_t=D u_{xx}\) for constant positive diffusivity \(D\). Use a uniform grid of spacing \(h\), and initially examine interior points or periodic boundaries so the stencil is unchanged everywhere. Replacing the second derivative by a centred difference gives a system of ordinary differential equations for the nodal temperatures. The time method still has to resolve the fastest rate that this spatial operator can generate.
An explicit Euler step yields \(u_i^{n+1}=r u_{i-1}^n+(1-2r)u_i^n+r u_{i+1}^n\) with \(r=D\Delta t/h^2\). If \(0\leq r\leq1/2\), the update is a convex combination of three temperatures. The maximum cannot rise and the minimum cannot fall in a source-free interior step. Starting with one hot node at 1 and neighbours at zero, \(r=0.4\) gives a centre value 0.2 and neighbours 0.4 after a single step. At \(r=0.6\) the centre would become negative although the continuum heat equation preserves nonnegativity.
Identify the spatial modes that set the limit
Insert \(u_j^n=g^n e^{\mathrm{i}j\theta}\), where \(\mathrm{i}\) is the imaginary unit and \(j\) indexes the grid. The two neighbouring values contribute factors \(e^{\pm\mathrm{i}\theta}\), yielding \(g=1-4r\sin^2(\theta/2)\). Long waves have \(\sin^2(\theta/2)\simeq\theta^2/4\), so their decay approaches the continuum rate as the mesh is refined. The alternating grid mode \(\theta=\pi\) has the most negative amplification and enforces \(r\leq1/2\) for bounded magnitude.
At the limiting value \(r=1/2\) the alternating mode flips sign without losing amplitude. A strict margin damps it. For \(D=10^{-4}\) m²/s and \(h=2\) mm, the maximum explicit step is
Refining to 1 mm reduces that limit to 0.005 s. The mesh gives a sharper temperature profile yet can cost four times more steps over the same physical interval, besides the increased number of spatial degrees of freedom.
Compare backward Euler and Crank–Nicolson
Writing the semidiscrete system as \(u'=-A_hu\), backward Euler solves \((I+\Delta t A_h)u^{n+1}=u^n\). Crank–Nicolson averages the old and new diffusive fluxes, giving \((I+\Delta t A_h/2)u^{n+1}=(I-\Delta t A_h/2)u^n\). For a Fourier mode put \(s=4r\sin^2(\theta/2)\). Their factors are \(1/(1+s)\) and \((1-s/2)/(1+s/2)\), respectively. Both remain bounded at arbitrarily large \(s\), but Crank–Nicolson may alternate for under-resolved sharp features.
With \(s=20\), backward Euler retains only \(1/21\) per step. Crank–Nicolson yields \(-9/11\), retaining much more of the fast component and reversing its sign. For a smooth low-frequency mode Crank–Nicolson generally gives more accurate temporal decay because it is second order. Decide whether early sharp transients or later smooth behaviour is the relevant physical quantity. To identify spatial and temporal error separately, refine \(\Delta t\) first on a fixed mesh, then refine space with time error kept well below spatial error. Merely halving both at once cannot reveal which term dominated the original discrepancy.
Apply a prescribed heat input without confusing it with temperature
An insulated periodic rod with uniform heating rate \(s\) measured in K/s has an average temperature that must rise by \(s\Delta t\) each step. Sum the centred second differences over the periodic indices: each nodal value appears with coefficients \(1,-2,1\), which cancel. The source alone changes the mean. For \(s=3\) K/s and a step of 0.02 s the numerical average must increase by 0.06 K, independently of the diffusivity and initial profile.
A code can pass this global test while still mishandling short-wave damping, since an alternating error has zero spatial mean. Pair a mean-temperature test with a nonconstant mode-decay test. Use a homogeneous periodic run for isolates of diffusion, and a uniform temperature with prescribed source for the storage term. A failure in one test then identifies a different part of the mathematical balance than a failure in the other.
Prove decay of a discrete thermal energy
Let a closed semidiscrete diffusion model be \(M\dot u+Ku=0\), with \(M\) symmetric positive definite and \(K\) symmetric positive semidefinite. Assume \(K{\bf1}=0\), expressing zero flux for a uniform temperature. Backward Euler satisfies \(M(u^{n+1}-u^n)+\Delta t Ku^{n+1}=0\). Multiplying by the constant vector and using symmetry gives
Thus the capacity-weighted sum, proportional to stored sensible heat for constant capacities and a fixed reference, is conserved for any step size.
Now multiply by \(u^{n+1}\). The identity \(a^TM(a-b)=[\|a\|_M^2-\|b\|_M^2+\|a-b\|_M^2]/2\) yields the exact balance
Both terms are nonnegative. The quadratic quantity therefore decays although total sensible heat is conserved. Subtracting the conserved mean first yields the same decay statement for temperature variation around equilibrium. The first term represents spatial smoothing measured at the new time, and the second reflects the numerical time update. This derivation gives a stability certificate on nonuniform grids without assuming Fourier modes.
Audit two cells with different heat capacities
Choose capacities 1 and 3 J/K, conductance 2 W/K, and initial temperature deviations \((4,0)^T\) K. The conserved sensible heat is 4 J, so the final equilibrium in a closed system must be one kelvin above reference. At \(\Delta t=0.5\) s the matrix \(M+\Delta tK\) has rows \((2,-1)\) and \((-1,4)\), and the right-hand side is \((4,0)^T\). The new temperatures are \((16/7,4/7)^T\). Checking their weighted sum gives \(16/7+3(4/7)=4\), as required. The unweighted average changes, which is physically appropriate for unequal capacities.
The quadratic quantity at the start is \(4^2/2=8\). After the step it is
Its drop is \(240/49\). The conductive contribution is \((0.5)(2)(12/7)^2=144/49\); the time-update contribution is
Their sum recovers the measured drop exactly. Neither contribution equals a loss of the 4 J of sensible heat. The quadratic measure depends on squared temperatures and has different physical units.
A positive heat supply or a prescribed exterior temperature introduces a boundary or source work term into these identities. Applying the closed-system decay test to an externally heated experiment would therefore diagnose the wrong physical model. Verify which conserved or dissipated quantity is actually implied by the capacity matrix, boundary conditions and source terms before comparing numerical integrators.
The conserved mean suggests another check after many large steps. The steady state must have zero conductance dissipation, which for two connected cells requires equal temperatures. Together with the weighted heat total this fixes both temperatures at one kelvin above reference. A scheme that instead approaches the unweighted initial average of two would be converging to the wrong conserved quantity despite producing a visually smooth, uniform endpoint. The measured quadratic variation about the correct mean tends to zero; the uncentred squared quantity tends to a positive constant because the remaining uniform state still has temperature above the chosen reference.
What happens to a grid-scale temperature ripple?
The alternating spatial mode on a uniform heat grid has discrete Laplacian eigenvalue \(-4/\Delta x^2\). Substitute this mode into each method and compare the amplitude after one step. The plot isolates the shortest resolvable pattern.

Read values from the plot
| Diffusion number αΔt/Δx² | Forward Euler | Backward Euler | Crank–Nicolson |
|---|---|---|---|
| 0 | 1 | 1 | 1 |
| 0.275 | −0.1 | 0.47619 | 0.29032 |
| 0.55 | −1.2 | 0.3125 | −0.047619 |
| 0.825 | −2.3 | 0.23256 | −0.24528 |
| 1.1 | −3.4 | 0.18519 | −0.375 |
Change parameters · What happens to a grid-scale temperature ripple?
Change one input at a time and compare the recalculated curves with the argument above. The browser evaluates this small model locally; the accompanying numerical values state its assumptions and reference checks. Reset restores the reference inputs, and the data can be downloaded as CSV.
Problem sheet 2 · Fronts and diffusive modes
Track conservation on a periodic mesh, distinguish shocks from expanding fans and choose a time step for an explicit diffusion solver.
Advect a marked volume
On a periodic ring of four cells take means \((1,0,0,0)\), positive speed and Courant number \(C=1/4\). Compute two first-order upwind updates, verify inventory and compare the maximum with that from an exact translation of a square pulse by half a cell.
Worked solution
The first update is \((3/4,1/4,0,0)\). Applying the same convex average gives \((9/16,6/16,1/16,0)\). Both arrays sum to one, so the total conserved amount is one cell width times this sum.
After an exact shift of half a cell, the two overlapping cell averages are \(1/2,1/2\) and the other two vanish, although the pointwise pulse height is still one. The numerical maximum of \(9/16\) is larger than the exact cell-average peak at this instant, even as the numerical support is more spread out. A peak comparison must specify whether it uses point values or cell means.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Identify a shock and a fan
For \(f(u)=u^2/2\), consider left and right states 3 and 1. Compute the discontinuity speed, compare it with the two characteristic speeds and locate its position after 0.4 s from the origin. Reverse the states and identify the edges of the entropy-admissible solution.
Worked solution
Fluxes are 4.5 and 0.5, giving \(s=(0.5-4.5)/(1-3)=2\). Since the characteristic speeds \(f'(u)\) are 3 on the left and 1 on the right, both enter the discontinuity in its moving frame. Its position is \(0.4(2)=0.8\).
With left 1 and right 3 the characteristics move apart and an expansion fan fills the region between \(x=0.4\) and \(x=1.2\). A single jump satisfying the algebraic jump balance would have the wrong entropy behaviour for these data.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Allocate a time budget on a refined grid
On a periodic rod \(D=2\times10^{-5}\) m²/s and \(h=1\) mm. Find the explicit diffusion step limit. To reach 1 s with \(r=0.4\), how many steps are needed? Repeat after halving spatial spacing and compare the total number of nodal updates on a fixed length.
Worked solution
The stability limit is
For \(r=0.4\), use \(0.4h^2/D=0.020\) s, or 50 steps. Halving \(h\) quarters the step to 0.005 s, giving 200 steps.
There are about twice as many spatial nodes on the refined line. The combination of twice as many nodes and four times as many steps requires about eight times as many local updates, neglecting boundary and setup costs.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Chapter 5 · Wave speeds and numerical dispersion
Derive the leapfrog dispersion relation, use the Courant condition to distinguish boundedness from accurate travel time and initialise a standing-wave calculation consistently.
From first principles
Derive the numerical wave dispersion relation by advancing a single mode
Consider a one-dimensional homogeneous wave with speed \(c\), uniform spatial grid \(h\) and time increment \(\Delta t\). Centred second differences approximate both accelerations and spatial curvatures using the values on either side of their evaluation point. The governing equation \(u_{tt}=c^2u_{xx}\) becomes
To determine what the grid does to one travelling component, insert \(u_j^n=e^{i(kjh-\omega n\Delta t)}\) and divide by the value at \((j,n)\). In both directions the pair of opposite phases combines to a cosine. Using \(2-2\cos z=4\sin^2(z/2)\) then gives
Long wavelengths recover \(\omega\simeq c|k|\). Short waves can propagate at a different phase speed even in a perfectly homogeneous physical medium. Requiring a real \(\omega\) for every resolved \(k\) gives \(C\le1\). This derivation concerns interior grid modes; domain boundaries can introduce reflected waves as a separate numerical effect.
Derivation and applications
Derive a conserved energy for the centred wave update
A time-stepping method can support a numerical travelling wave while transporting its phase at a slightly incorrect speed. For a second diagnostic, ask whether total discrete vibration energy remains bounded. Consider a uniform one-dimensional periodic grid for \(u_{tt}=c^2u_{xx}\), unit mass density and no forcing. Denote the forward spatial difference by \(D\) and the half-step velocity by \(v^{n+1/2}=(u^{n+1}-u^n)/\Delta t\). Summation by parts on this grid gives \(\langle v,D^\mathsf TD u\rangle=\langle Dv,Du\rangle\) using the grid inner product. The centred step can be written
Take the inner product with \((v^{n+1/2}+v^{n-1/2})/2\). The left side becomes a difference of two kinetic energies. On the right use \(\Delta t(v^{n+1/2}+v^{n-1/2})=u^{n+1}-u^{n-1}\) and move \(D\) to the other factor:
The potential term couples consecutive time levels. Writing it in terms of the midpoint displacement \(\bar u=(u^{n+1}+u^n)/2\) identifies when the invariant bounds the solution:
Since \(\|Dv\|\le2\|v\|/\Delta x\), the kinetic part is bounded below by \((1-C^2)\|v\|^2/2\), with \(C=c\Delta t/\Delta x\). The invariant controls nonconstant waves for \(C<1\). An exact but indefinite conservation law alone would not guarantee a bounded numerical solution.
Worked example
Read a timestep from a material and grid
Take \(c=100\) m/s, \(\Delta x=0.0500\) m and \(\Delta t=0.400\) ms. Then \(C=0.800\) and the bound preserves at least \(1-C^2=0.360\) of the usual half-step kinetic term even in the worst spatial mode. The customary limiting step from this argument is \(0.500\) ms.
Second application
Show why equality of successive energies can mislead
Take the alternating grid mode for which \(\|Dv\|=2\|v\|/\Delta x\), and choose adjacent displacements whose midpoint is zero. At \(C=1.20\) the invariant for this state is
Negative energy here is a property of the numerical quadratic form. A solver can preserve it exactly and still exhibit amplitude growth.
Distinguish transport of phase from transport of energy
A taut string with small transverse displacements and fixed tension obeys \(u_{tt}=c^2u_{xx}\). The physical speed \(c\) is independent of wavelength in this ideal one-dimensional model. A discrete solver can transport long waves at nearly the correct speed while short waves arrive late. In a pulse comprising many wavelengths, this artificial dependence on frequency distorts its shape even in a stable computation. A phase comparison at a probe provides information beyond monitoring maximum amplitude.
Use centred second differences in both time and space, with \(C=c\Delta t/h\). Solving explicitly for the new level gives
To initialise, expand \(u(\Delta t)=u(0)+\Delta t\,v(0)+(\Delta t)^2 c^2u_{xx}(0)/2+\cdots\). Replacing \(u_{xx}(0)\) by the same spatial difference gives a first level consistent with the initial velocity and acceleration. Simply copying the starting displacement to level one can introduce a spurious launch velocity.
Derive the discrete dispersion relation
Take a travelling mode \(u_i^n=\exp[\mathrm{i}(i\theta-n\omega_h\Delta t)]\) with spatial phase \(\theta=kh\). Inserting it makes the temporal second difference proportional to \(-4\sin^2(\omega_h\Delta t/2)\) and the spatial second difference proportional to \(-4\sin^2(\theta/2)\). Thus on the positive-frequency branch
A real \(\omega_h\) exists for all resolvable real spatial phases only when \(C\leq1\). If \(C>1\), the shortest wave makes the right-hand side exceed one; a temporal amplification root then lies outside the unit circle. Even when stable, the ratio of numerical to physical phase speed is \(2\arcsin[C\sin(\theta/2)]/(C\theta)\). A fine spatial sample makes \(\theta\) small and the ratio tends to one. At \(C=1\) the ideal uniform one-dimensional interior stencil reproduces the wave phase on the resolved branch. Boundaries, material transitions and multiple dimensions require separate analysis.

Estimate a travel-time error
Take \(C=0.5\) and four points per wavelength, so \(\theta=\pi/2\). Then
The physical advance is
The numerical phase speed is about 0.920 of the true speed. After ten physical periods, its accumulated phase is about 9.20 cycles. A stable solution can therefore be nearly one oscillation behind while retaining a visually plausible amplitude.
Group velocity is \(d\omega_h/dk\), obtained by differentiating the dispersion relation. On this branch \(v_g/c=\cos(\theta/2)/\sqrt{1-C^2\sin^2(\theta/2)}\), about 0.756 in the four-point example. A narrow-band packet’s envelope and an individual crest then propagate at different numerical speeds. When interpreting a probe trace, say whether the reported arrival corresponds to a crest, an envelope or a threshold. Repeat the calculation at additional points per wavelength using the same Courant number to isolate spatial-phase improvement from changes in the time integration.
Interpret the grid’s travelling domain of dependence
In one explicit wave step, a node uses only itself and its two nearest neighbours. After \(n\) steps its numerical domain of dependence extends at most \(n\) grid cells to either side. The continuous wave at the same time can depend on initial data a distance \(cn\Delta t\) away. For convergence that physical domain must fit inside the numerical one, giving \(c\Delta t\leq h\). This reproduces the Courant condition from geometry without inserting a Fourier mode. It is a necessary information-speed test; by itself it does not establish stability or accuracy of an arbitrary scheme.
As an example, with \(c=340\) m/s and \(h=0.01\) m, the step bound is about 29.4 microseconds. A 20 microsecond step satisfies it but need not give an accurate answer for a mode represented by only three or four points per wavelength. Time-of-flight information and wavelength resolution are related to different discretisation choices. Document both when comparing two wave calculations.
Derive a reflected wave from a discrete outgoing condition
For a one-dimensional wave travelling right at speed \(c\), the outgoing continuum condition is \(u_t+cu_x=0\) at the right boundary. It annihilates an exact right-travelling waveform. A numerical boundary update using forward time and backward space gives
where \(C=c\Delta t/h\). A wave satisfying the interior discrete dispersion relation need not satisfy this one-sided relation. Even when the continuum boundary is perfectly absorbing, a mismatch of discrete phase relations can send energy back into the computational domain.
Let \(z=e^{-i\omega\Delta t}\), with the incident and reflected grid waves represented by \(e^{i\theta(j-N)}z^n\) and \(R e^{-i\theta(j-N)}z^n\). At the boundary their sum is \(1+R\) times \(z^n\). Substitution in the outgoing update and grouping incident and reflected terms gives
This amplitude ratio assumes a homogeneous grid, a propagating frequency and distinct incident and reflected branches. It compares each wave at the boundary itself. Signals measured farther inward acquire additional phase and travel-time factors and can interfere if both arrive in the same observation window.
Calculate a reflection generated by numerical mismatch
Use the centred wave scheme with \(C=1/2\) and grid angle \(\theta=\pi/2\), four cells per wavelength. The interior relation gives \(\sin(\omega\Delta t/2)=(1/2)\sin(\pi/4)=1/(2\sqrt2)\), hence \(z=0.75-i\sqrt7/4\). The incident mismatch in the numerator is \(0.25-i(\sqrt7/4-0.5)\); the reflected denominator is \(0.25-i(\sqrt7/4+0.5)\). Squaring the magnitudes gives \((3-\sqrt7)/4\) and \((3+\sqrt7)/4\), respectively. Therefore \(|R|=\sqrt{(3-\sqrt7)/(3+\sqrt7)}\approx0.2505\). Roughly one quarter of the incident amplitude is reflected solely by this discrete boundary treatment.
For incident and reflected branches on the same symmetric grid, their group-speed magnitudes match. The corresponding reflected energy fraction is \(|R|^2\approx0.0627\), about six percent. That is small enough for a short experiment to appear satisfactory until the pulse returns to a sensor. Testing only the incident travel time would miss this boundary error. Compare a time window before reflection with the expected window for the return journey.
At \(C=1\) and \(0<\theta<\pi\), the right-moving interior root is \(z=e^{-i\theta}\). The numerator vanishes exactly and the boundary update transmits that branch without reflection. This exact compatibility is special to this one-dimensional grid, this step size and this outgoing condition. Varying the propagation angle in two dimensions, changing an interface spacing or using a higher-order interior stencil changes the phase relation that the boundary operator needs to match.
There is a practical way to isolate this reflection in a pulse computation. Record incident and outgoing velocity or flux at the same interior sensor, and choose the duration so that the reflected signal arrives after the incident pulse has passed. Normalise amplitudes in the same physical variable, and avoid dividing a pressure peak by a displacement peak. A broadband pulse contains many values of the grid angle, so its returned waveform can change shape even when each monochromatic component obeys the calculated reflection coefficient.
Change parameters · Wave speeds and numerical dispersion
Change one input at a time and compare the recalculated curves with the argument above. The browser evaluates this small model locally; the accompanying numerical values state its assumptions and reference checks. Reset restores the reference inputs, and the data can be downloaded as CSV.
Study the full derivation
How much of an outgoing wave reflects from the numerical boundary? · Spatial discretisation and field equations
A finite grid truncates an effectively open medium. Derive an exact one-dimensional radiation condition, predict the angular reflection of its two-dimensional extension and design a pulse experiment that separates boundary reflection from interior dispersion.
Chapter 6 · Verification, refinement and local error
Use a manufactured solution to verify an implementation, estimate observed convergence and identify when adaptivity is needed for the physical quantity of interest.
From first principles
Derive the observed order and an extrapolated continuum output
Verification compares the discretized problem against a known solution or controlled refinement. Choose one scalar output \(Q\), the same geometry and the same physical observation point on each mesh. Assume a smooth leading error \(Q_h=Q+C h^p+o(h^p)\) on geometrically similar meshes, with refinement ratio \(r>1\). Subtract successive estimates to remove the unknown continuum output:
Their ratio approaches \(r^p\), provided the leading coefficient is nonzero. Solve for the order, then use the finest pair to remove the leading error term:
The ratio is meaningful only when a consistent leading error dominates. Differential changes of solver tolerance, geometry or timestep across the meshes can contaminate it. A manufactured solution independently tests discretization and boundary terms by inserting a chosen exact field into the differential operator and supplying the resulting source.
Background · Observed convergence order
Errors must refer to the same observable and norm. Cancellation, singular boundaries and a reference solution of insufficient accuracy can distort the result.
Derivation and applications
How the measured norm changes an observed convergence rate
A verification study may report very different rates for the same discrete field. Choose a fixed one-dimensional domain of length one, divided into cells of width \(h\). Suppose the solution is smooth away from an interface, where a nearby discontinuity, boundary approximation or reconstruction produces a localized error. Let the error magnitude be \(A h^\alpha\) on a fixed number \(m\) of cells near the interface, and at most \(B h^p\) elsewhere. The count \(m\) stays fixed under refinement. For a finite \(q\ge1\) use the physically weighted norm instead of an unweighted vector norm:
As \(h\) decreases the term with the smaller exponent decays more slowly. If the indicated leading magnitudes are actually attained, the corresponding rate of the norm is
The extra \(1/q\) comes from the shrinking physical measure of the affected region. It disappears in a maximum norm. A single signed integral of error can give still another result because opposite local errors cancel:
A convergence statement therefore requires the reported norm, physical location, and mesh sequence. If an interface stays at a changing subcell position as the grid is refined, the leading coefficient can vary; observed slopes from just two grids can then be misleading.
Worked example
Calculate three norms for a displaced step
Let one cell of a piecewise-constant reconstruction differ from the exact field by \(1.00\), with zero error elsewhere. At \(h=1/64\), the \(L^1\) error is \(1/64=0.015625\), the \(L^2\) error is \(\sqrt{1/64}=0.125\) and the maximum error is \(1.00\). Refining to \(h=1/256\) gives \(0.003906\), \(0.0625\) and \(1.00\). The measured rates are one, one half and zero for precisely the same displacement.
Second application
Compare cancellation with local accuracy
Suppose two adjacent cells at \(h=1/100\) have errors \(+0.500\) and \(-0.500\). The signed integral discrepancy is zero; the \(L^1\) error is \(0.0100\) and the \(L^2\) error is
Checking only total inventory would certify the output but miss the incorrect distribution. A local measurement or absolute-error norm verifies a different and often more demanding quantity.
OneSimulation laboratory
Predict grid error from the wavelength
Can a solver satisfy every discrete balance to roundoff and still overpredict the field? Consider a unit square with zero values on all four sides and a uniform diffusion coefficient. Prescribe the continuous field \(u=\sin(ax)\sin(ay)\) with \(a=m\pi\) and integer \(m\). Differentiating it twice in each direction gives the source \(f=2a^2u\) for \(-\nabla^2u=f\). This constructs a known solution before any numerical calculation.
Predict the grid’s response. For an evenly spaced line with interval \(h=1/N\), add the two neighbouring values of a sampled sine using the angle addition rule. The negative second difference in one direction becomes a multiple of the original sample:
The square contributes the same factor twice. Its discrete eigenvalue is \(\lambda_h=8\sin^2(ah/2)/h^2\). Since the source was constructed with the continuous eigenvalue, the grid solution is \(u_h=(2a^2/\lambda_h)u\) at the nodes. Expanding the sine gives the amplitude ratio \(1+(ah)^2/12+O((ah)^4)\). At a fixed mode, halving the mesh spacing should reduce the leading amplitude error fourfold.

Read the comparison. For mode 2, refinement from 24 to 48 cells per side changes the largest nodal error from 0.005731 to 0.001429. The ratio is 4.01. Compare modes at a common mesh size to see why a smooth but shorter-wavelength field can be harder to resolve. The prediction evaluates the maximum on the actual nodes because some grids miss the continuous peaks.
Try a different wavelength. Choose mode 4 on 16, 32 and 64 cells. Compare the output with mode 2 on 8, 16 and 32 cells. These pairs have the same number of cells per half-wave. Predict which error values carry over.
Further reading · Gilbert Strang, Difference matrices and eigenvalues, §5.5 (PDF).
Download the OneSimulation model (Python). Set up the local runtime, then run the downloaded file:
python poisson-mode.py --mode 4 --cells 16 32 64Start from this chapter. Predict an error ratio of four for second-order spatial accuracy when both grid spacings halve. Compare three meshes at the same sine mode, then test a shorter wavelength.
OneSimulation laboratory · Measure spatial convergence on a known field
Build a test with a known answer
Consider \(-\nabla\cdot(D\nabla u)+\kappa u=f\) on the unit square. Select the exact field \(u_\star=\sin(\pi x)\sin(\pi y)\) and prescribe its value at the boundary. Now choose \(D=1+x\), \(\kappa=2\), using coordinates normalised to a metre. Differentiation gives
The required source is therefore
The derivative of \(D\) is essential: inserting only the local value of \(D\) times the Laplacian specifies a different differential equation. Manufacturing a source tests whether the code solves the stated model and boundary conditions. Experimental validation asks a separate question about fidelity to physical observations. A polished plot resembling the exact field does not substitute for a numerical error measure with defined sample positions and units.
Read a three-grid study
On successively halved mesh spacings suppose the error in one norm follows \(E_h=C h^p+o(h^p)\). Taking ratios gives
Three grids provide two such estimates, indicating whether a consistent asymptotic trend is present. A single ratio may result from cancellation between terms of different order. State the norm, grid location, geometry representation, time step if applicable, and the residual tolerance. Comparing a cell average on one grid with a nodal peak on another can produce a meaningless rate.
For the variable-diffusion square, maximum nodal errors at 24, 48 and 96 intervals per axis are approximately \(1.33345\times10^{-3},3.33763\times10^{-4},8.34283\times10^{-5}\). The observed orders are approximately 1.998 and 2.000. The finest-grid algebraic residual is already far below the field error in its respective normalisation. Tightening the iteration tolerance alone will not remove the leading spatial defect. Raising the sine mode while holding the mesh fixed increases derivatives of the exact solution and tests a different resolution regime. Inspect the grid and mode experiment.
Decide where further resolution matters
A manufactured sine is smooth everywhere. Actual domains may contain a re-entrant corner, a material jump or a narrow source. Derivative bounds used in theoretical convergence estimates can fail locally there. Uniformly halving a two-dimensional mesh roughly quadruples the cell count while spending most new cells away from a localised feature. Local refinement attempts to concentrate new degrees of freedom where they matter to a chosen output. Which cells merit refinement depends on the equation, boundary data and the output being measured.
For a conforming finite-element approximation, one class of error indicators combines an element residual with jumps in normal flux across interior faces. The residual tests whether each element satisfies the differential balance, while the jumps measure disagreements between neighbouring reconstructed fluxes. In a constant-coefficient Poisson example, a piecewise linear solution can have zero elementwise Laplacian even when it bends globally; the slope changes then appear at interelement faces. An indicator using only the interior derivative would miss this information. Mesh-length factors and coefficient weights are necessary to combine the terms in a specific norm.
Finish a refinement study by tracking the physical observable itself. If the objective is integrated heat flow, a changing maximum pointwise gradient near one corner may have little influence on that integral. Conversely, apparently stable domain averages can hide an unresolved peak. Report observed change with resolution and an independent balance or analytic check, specifying exactly which quantity has been verified.
Choose cells to refine from residuals and flux jumps
A mesh-convergence table needs several complete solutions. To spend the next refinement locally, examine the equation that the present field still fails to satisfy. For \(-u''=f\) with zero Dirichlet endpoints, let \(u_h\) be its conforming piecewise-linear Galerkin solution. Integrating the error equation by parts on each cell \(K\) gives
The sum over \(z\) includes interior nodes only. Even when the cell derivative is constant and \(u_h''=0\) in each open cell, its jumps measure failures of flux continuity. Dropping these terms would miss part of the weak residual. Galerkin orthogonality lets us substitute \(v-I_hv\) for \(v\), where \(I_hv\) is a local conforming approximation. Local interpolation and trace estimates supply the mesh-length factors in an indicator. One conventional allocation on a uniform mesh is
The half shares a node between its two neighbors. An upper bound on the energy error involves the square root of the summed indicators and a mesh-independent constant. Efficiency estimates can also involve unresolved variations in the load. The indicator is a refinement criterion, not a measured cell error.
Spending one refinement near a source
On the two half-intervals let \(f=0\) on the left and \(f=4\) on the right. The central hat function integrates to \(1/4\) on the right, so the interior load is \(1\). Its stiffness is \(4\). The central temperature is \(1/4\). The cell slopes are \(1/2,-1/2\), so \(J=1\). The jump contributes \(1/4\) to each indicator squared. The source contributes zero on the left and \((1/2)^2(16/2)=2\) on the right. Thus the right cell accounts for \(2.25/2.5=90\%\) of the total. A bulk-marking rule targeting at least \(75\%\) marks this one cell.
An exact check explains the distinction between indicator and error. Integrating the differential equation gives the exact slope \(1/2\) throughout the left cell and \(1/2-4(x-1/2)\) on the right. The true squared energy error is zero on the left and \(\int_0^{1/2}(1-4s)^2ds=1/6\) on the right. The indicator assigns some weight to the neighbor because both cells share a flux jump. Its largest contribution nevertheless identifies the curved part of the field.
Practise on sheet 3 · Refine a three-cell source patch. Further reading · Heidelberg University · Lecture Notes on Scientific Computing with Partial Differential Equations · §9.2 Residual-based a-posteriori Error Estimator and §9.3 Local Mesh Adaptation.
Check refinement at an identical location
Suppose a displacement is reported at the centre of a square. On an even grid that point may coincide with a node, whereas on an odd grid it can lie at the centre of a cell. Taking the maximum over mesh nodes produces a different sample on each grid. A refinement curve can then combine field discretisation error with the movement of the evaluation point. Choose a fixed physical point and evaluate each solution there with its own consistent interpolation, or compare a well-defined integral over the same physical region.
Similarly, compare gradients on compatible supports. Nodal averages of element stresses can look smoother than the individual element values, yet smoothing can alter extrema and convergence rates. Record the native support and any recovery operator. This makes an apparent improvement reproducible and gives students enough information to explain a discrepancy between two otherwise credible simulation reports.
Separate space and time with a crossed refinement study
Suppose a reported output has asymptotic error \(Q(h,k)-Q_\star=A h^p+B k^q\) plus smaller terms, with spatial spacing \(h\) and time step \(k\). Refining both coordinates in a fixed relation examines only one line across this two-dimensional error surface. Opposite signed contributions can cancel on that line. A genuine spatial order check uses several \(h\) at fixed sufficiently small \(k\), and a temporal check uses several \(k\) at controlled \(h\). When exact values are available, the individual error signs provide particularly clear evidence of cancellation.
A small crossed design with coarse and fine settings in both directions already offers a structural test. Denote its four outputs by \(Q_{cc},Q_{cf},Q_{fc},Q_{ff}\), with the first subscript indicating the spatial mesh. For an additive leading error the spatial change \(Q_{cc}-Q_{fc}\) equals \(Q_{cf}-Q_{ff}\). Their difference, \(Q_{cc}-Q_{cf}-Q_{fc}+Q_{ff}\), measures a mixed contribution or departure from the leading separated model. A small difference supports that model over the tested settings but cannot prove that the assumed orders are correct; additional refinement levels are needed to estimate orders from the data.
Recover a hidden temporal bias from four runs
Take a manufactured output \(Q=10+2h^2-k\). The benchmark value is ten. Choose \(h_c=0.2,\ h_f=0.1,\ k_c=0.1,\ k_f=0.05\). The four outputs are respectively \(9.98,\ 10.03,\ 9.92,\ 9.97\). At either time step, halving the spatial mesh reduces the output by 0.06. At either spatial mesh, halving the time step increases the output by 0.05. The mixed difference is zero. Refining both together moves the value by only −0.01, concealing spatial and temporal changes five or six times larger.
If the orders are independently known as \(p=2,\ q=1\), the fine-grid spatial bias is
The fine-time bias is
Subtracting both from the fine result gives \(9.97-0.02+0.05=10\), exactly recovering the limit in this idealised expansion. Choosing instead \(k=2h^2\) on every paired run would return exactly ten for every mesh, including a very coarse one. A convergence plot along that line would demonstrate cancellation rather than independent verification.
Explicit stability restrictions can make unrestricted crossing impractical. If a coarse time step is unstable on the finest spatial grid, choose a stable common range or use an implicit reference to isolate spatial error. Keep output locations, boundary representation and integration tolerances consistent across the crossed study, since changes in those other approximations can also enter the mixed difference.
A fifth run can interrogate the assumption that the fine-grid spatial change is asymptotic. At \(h=0.05,\ k=0.05\) the manufactured output is 9.955. The change from 9.97 is 0.015, one quarter of the earlier spatial change 0.06 at the same time step. This independent ratio supports \(p=2\) for the tested family; it does not distinguish a true zero cross term from a smaller mixed term below the numerical resolution.
Resolve a second spatial frequency on the same grid
Set the exact field on the square to \(\sin(m\pi x)\sin(m\pi y)\) and manufacture the corresponding source for diffusion coefficient \(1+x\) and reaction coefficient 2. Run the downloadable OneSimulation model with m = 1 and 2 on each grid. The boundary data agree, while the source and the exact interior curvatures change.

Read values from the plot
| Uniform intervals per axis | 1 half-wave per axis | 2 half-waves per axis |
|---|---|---|
| 8 | 0.012068 | 0.052561 |
| 16 | 0.0030008 | 0.012829 |
| 24 | 0.0013335 | 0.0056768 |
| 32 | 0.0007509 | 0.0031883 |
| 64 | 0.00018768 | 0.00079605 |
Download the OneSimulation model (Python)
Change parameters · Resolve a second spatial frequency on the same grid
Change one input at a time and compare the recalculated curves with the argument above. The browser evaluates this small model locally; the accompanying numerical values state its assumptions and reference checks. Reset restores the reference inputs, and the data can be downloaded as CSV.
Study the full derivation
Bound diffusion error by balancing a reconstructed flux · Spatial discretisation and field equations
A temperature field from a finite-element calculation looks smooth. Reconstruct a heat flux which exactly balances the source, then derive an upper bound for the true energy error without knowing the exact temperature.
Problem sheet 3 · Wave resolution and verification
Prescribe the first time level of a vibrating string, measure a convergence order and decide what a residual reveals under grid refinement.
Release a mode from rest
For a unit string with fixed ends take initial shape \(u_i^0=\sin(\pi i/N)\) and initial velocity zero. Derive the factor relating \(u_i^1\) to \(u_i^0\) for the centred wave scheme with Courant number \(C\). Evaluate it for \(N=4,\ C=0.5\).
Worked solution
The central second difference of the sine is \(-4\sin^2(\pi/(2N))u_i^0\) before dividing by \(h^2\). The first-step Taylor formula therefore gives
At \(N=4,C=0.5\), the factor is
Copying the initial displacement instead would omit the physical acceleration produced by the curved shape.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Quantify a grid-dependent observable
A computed outflow on meshes \(h,h/2,h/4\) is 2.080, 2.020 and 2.005 W. Assuming an asymptotic \(Q_h=Q+c h^p\), estimate \(p\), the extrapolated flux and the fine-grid error. Can those figures alone demonstrate conservation to the same tolerance?
Worked solution
The successive differences are 0.060 and 0.015 W, whose ratio is 4. Thus
Extrapolate \(Q=2.005+(2.005-2.020)/3=2.000\) W, giving estimated fine-grid error +0.005 W.
A separate conservation check must sum inflows, outflows, sources and storage. A sequence of outflow values can converge cleanly even under a method that systematically loses heat elsewhere.
Explore the related calculation with adjustable inputs. Refine the grid on a known solution and keep the small linear-solver residual separate from the spatial field error.
Relate flux jumps to a residual indicator
A unit rod is approximated by two equal linear elements with nodal values \((0,1,1)\) and \(k=1\). Compute each element’s flux, the flux jump at their interface, and the elementwise second derivative. In a source-free steady model, explain what a check based only on that second derivative would miss.
Worked solution
The slopes are 2 and 0, giving fluxes −2 and 0 in the positive coordinate direction. The right-element flux minus the left-element flux is therefore 2. Second derivatives vanish inside both linear pieces.
In a source-free steady conductor the same flux must cross the interface from either element. An interior derivative check would report zero inside each element while ignoring the change at the joining node. An indicator including interface flux mismatch detects this loss of balance.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Refine a three-cell source patch
Split the unit interval into thirds and set \(f=0,9,0\) on successive cells, with zero temperature at both ends. Assemble the two interior values, calculate all three indicators and find a smallest set that accounts for \(80\%\) of the sum of indicator squares.
Worked solution
The middle cell contributes \(9(1/3)/2=3/2\) to each endpoint. The interior matrix is \(3\begin{pmatrix}2&-1\\-1&2\end{pmatrix}\), so symmetry gives
The slopes are \(3/2,0,-3/2\). Both jumps have magnitude \(3/2\).
Each attached jump contributes \((1/6)(3/2)^2=3/8\) to a cell. The middle source term contributes \((1/3)^2(81/3)=3\). Thus the indicator squares are \(3/8,15/4,3/8\), totaling \(9/2\). The middle fraction is
Marking just that cell exceeds the target.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Revisit chapter 6 · Choose cells to refine from residuals and flux jumps.
Predict the error before making a finer grid
In the variable-diffusion laboratory the mode-one errors on 24, 48 and 96 cells per side are \(1.33345\times10^{-3}\), \(3.33763\times10^{-4}\) and \(8.34283\times10^{-5}\). Estimate the last observed order, then predict the error at 192 cells and the number of interior unknowns. Decide whether reducing only the algebraic residual tolerance is likely to produce the same improvement.
Work through the solution
For \(E_N\approx C N^{-p}\), the last doubling gives
Another doubling predicts \(E_{192}\simeq2.09\times10^{-5}\). Eliminating prescribed boundary nodes leaves \(191^2=36\,481\) interior values. The observed rate is a checkable prediction for this smooth fixed mode. A smaller residual on the 96-cell mesh solves the same discrete equations more accurately. The reported residual is already small, and refinement is what changes their truncation error.
Chapter 7 · Interfaces, contact resistance and Robin data
Derive a face flux that transports the same heat through two different materials and through a convective boundary.
From first principles
Derive an interface flux from two half-cell temperature drops
Two neighbouring cell centres can lie in materials with sharply different conductivities. Consider a planar interface between them, normal to a one-dimensional steady heat flow. Let \(d_L,d_R\) be the distances from the centres to the interface, and suppose there is no interface source, storage or contact resistance. Steady conservation requires one heat flux \(q\), positive to the right, and perfect contact requires one interface temperature \(T_I\). Applying Fourier’s law to each half gives
Solve each expression for its temperature drop, add the two drops and eliminate \(T_I\). The conductance follows from the actual material distances:
For equal distances this is the harmonic mean; only equal conductivities recover the same result as the arithmetic mean. If one material approaches zero conductivity with positive thickness, the flux approaches zero. A finite thermal contact resistance adds another temperature drop \(qR_c\), while a heat-generating interface alters the flux-continuity condition itself.
Derivation and applications
Enforce the flux jump at a heat-generating interface
Two materials in series carry the same conductive current only if their common interface stores and generates no energy. Consider two homogeneous slabs with an idealized thin heater between them. Let \(T_L,T_R\) be prescribed outer surface temperatures, \(R_L,R_R\) the positive thermal resistances per unit area in m² K/W, and \(s\) the heater release in W/m². Assume perfect thermal contact, steady conduction and negligible thickness of the heater. Define the interface temperature as \(T_I\) and flux \(q\) positive to the right.
Fourier’s law integrated through each slab relates its own constant flux to its temperature drop. The pillbox balance across the heater requires the right flux to exceed the left one by the generated heat:
Substitute the two face laws into the balance. With \(g_j=1/R_j\) as the two conductances per area, the interface temperature and individual fluxes are
Alternatively eliminate \(T_I\) to express the fluxes as through-flow plus a split source. The resistances determine the fraction of added heat directed to each boundary:
Setting \(s=0\) restores a single common flux. Equal outside temperatures send more generated heat toward the lower resistance. For an interface at a mesh face the two cells therefore need distinct physical face fluxes linked by the stated jump; assigning exactly the same flux while adding no source anywhere violates energy balance.
Worked example
Determine both heat flows through an instrumented wall
Let \(T_L=320\) K, \(T_R=300\) K, \(R_L=0.100\), \(R_R=0.200\) m² K/W and \(s=150\) W/m². The interface sees conductances \(10.0\) and \(5.00\) W/(m² K) and reaches \(323.33\) K. The left flux is \(-33.3\) W/m² and the right flux \(116.7\) W/m². Heat leaves on both sides, including toward the hotter external surface. Their oriented difference equals \(150\) W/m².
Second application
Select a heater setting that makes one sensor read zero
Keeping the same temperatures and layers, impose \(q_L=0\). Then
All generated heat exits on the right. Reducing \(s\) to zero instead gives \(66.7\) W/m² from left to right through both layers. A zero left-side flux in the heated experiment therefore does not imply an insulating left layer.
Touch two long solids: which temperature does the interface acquire?
Two long blocks, initially at temperatures \(T_L>T_R\), are pressed into ideal thermal contact at \(x=0\). Denote conductivity by \(k\), volumetric heat capacity by \(C\), and diffusivity by \(\alpha=k/C\). At early times the penetration distance on each side is small compared with its length. Model the blocks as half-spaces with a common interfacial temperature \(T_*\). This transient contact problem has no fixed layer thickness to insert into a pair of steady thermal resistances.
In the right half-space the similarity coordinate is \(x/(2\sqrt{\alpha_R t})\). Substituting a function \(F\) of this coordinate into the heat equation gives
Its bounded solution matching a fixed surface and a uniform distant temperature has an error-function shape. Thus \(T_R(x,t)=T_*+(T_R-T_*)\operatorname{erf}[x/(2\sqrt{\alpha_R t})]\). The left solution uses distance \(-x\), its own diffusivity and the initial left temperature. These profiles share their interface temperature by construction; conservation still requires their heat fluxes to match.
Differentiate the error functions at zero and apply Fourier's law. The left flux equals \(e_L(T_L-T_*)/\sqrt{\pi t}\), and the right flux is \(e_R(T_*-T_R)/\sqrt{\pi t}\), both oriented from left to right. Here \(e=\sqrt{kC}\) is thermal effusivity. Equating the fluxes gives
The interfacial temperature is independent of time within this idealisation, while the penetration layers broaden continuously.
Open full-size diagramFor the notebook's \(k_L=4,\ k_R=1\,\mathrm{W/(m\,K)}\) and equal capacities of \(10^6\,\mathrm{J/(m^3\,K)}\), the effusivity ratio is two. Between 80 and 20 degrees Celsius the common temperature is 60 degrees Celsius. The initially infinite ideal flux is integrable: the energy transferred by time \(t\) equals \(2tq(t)\) per unit contact area. The notebook independently integrates temperature loss and gain throughout the two bodies and checks this balance. A real surface resistance, a finite approach time or the far surface of a finite specimen would eventually invalidate different parts of the idealisation.
A finite-volume scheme offers a sensitive check of this benchmark. On a sufficiently long computational domain, sum nodal or cell-average energies on each side at the same time. Internal face fluxes cancel in the total by conservation. A scheme may pass that global check while partitioning energy incorrectly between materials. Compare both individual energy changes, the early flux integrated over the first step and the temperature nearest the interface. This combination tests the material weighting and the time integration independently.
Keep both initial temperatures and conductivities fixed, but multiply the right-hand volumetric heat capacity by four. Predict \(T_*\) and the right-hand penetration depth at the same time.
Work through the solution
The right effusivity doubles and now equals the left one. The interface becomes 50 degrees Celsius. At fixed \(k_R\) the right diffusivity falls to one quarter, so the penetration distance proportional to \(\sqrt{\alpha_Rt}\) halves. A larger local capacity can draw more flux while confining the altered temperature to a narrower region.
Change parameters · Explore this notebook example
Change one input at a time and compare the recalculated curves with the argument above. The browser evaluates this small model locally; the accompanying numerical values state its assumptions and reference checks. Reset restores the reference inputs, and the data can be downloaded as CSV.
One flux through resistances in series
Let \(q=-kT'\) be heat flux in the positive coordinate direction, with unit cross-sectional area and no internal source. Between two cell centres separated by an interface, let the left and right centre-to-interface distances be \(d_L,d_R\). Piecewise constant conductivities \(k_L,k_R>0\) make the equilibrium temperature linear in each segment. If the interface has perfect contact, its temperature \(T_f\) is continuous. Integrating Fourier's law on each side gives
Adding eliminates the unknown interface temperature.
For equal distances this amounts to using the harmonic mean conductivity over the full centre spacing. Inserting the same signed \(q\) as the outflow of the left cell and the inflow of the right cell produces cancellation when their balances are added. If a material interface stores energy or supplies heat independently, a flux jump belongs in the balance and this steady series calculation must be modified.
Measure the temperature drop
Take \(d_L=d_R=0.01\) m, \(k_L=2,\ k_R=10\) W/(m K) and \(T_L=30,\ T_R=18\) °C. The series resistance per unit area is \(0.005+0.001=0.006\) m²K/W. The flux is \(2000\) W/m² and the interface temperature is \(30-2000(0.005)=20\) °C. The lower conductivity carries the larger temperature drop despite carrying the same flux. Using the arithmetic mean 6 with the centre difference over 0.02 m instead predicts \(3600\) W/m².
Introduce a contact resistance \(R_c=0.002\) m²K/W. Its temperature jump is \(qR_c\); the total resistance rises to 0.008, reducing the heat flux to 1500 W/m². The two sides of the contact now have temperatures 22.5 and 19.5 °C. Imposing a single interface temperature on this model would remove the physically measured 3 K jump.
OneSimulation · Resolve a temperature jump at imperfect contact
Two slabs are each 0.06 m thick, with conductivities 12 and 3 W/(m K). Their outer surfaces are held 30 K apart. A contact resistance \(R_c\) permits two distinct temperatures at the shared physical location. The flux stays continuous. The face law and the exact reference for the whole assembly are
The code adds \(R_c\) only to the resistance between the two cells adjacent to the contact. OneSimulation solves the resulting balance system. The flux falls from 1200 to 800 W/m² for \(R_c=0.0125\) m² K/W. Reconstructing the two face temperatures gives 326 K and 316 K. Connecting only the cell-centre temperatures would smear this 10 K jump over one mesh cell. Refining an ideal-contact model would converge to the wrong interface law.
"""Find the temperature jump at an imperfect contact between two slabs."""
import matplotlib.pyplot as plt
import numpy as np
from onesim.numerics.linear.matrices.dense_linear_algebra import solve_dense
n = 12 # even number of equal, cell-centred control volumes
length = 0.12 # m
dx = length / n
k = np.repeat([12., 3.], n // 2) # W/(m K)
left, right = 330., 300. # K
centres = (np.arange(n) + 0.5) * dx
fig, ax = plt.subplots(figsize=(6.8, 3.8), constrained_layout=True)
for contact, colour in [(0.0, "#a4492b"), (0.0125, "#176879")]: # m² K/W
resistance = np.r_[dx/(2*k[0]), dx/(2*k[:-1]) + dx/(2*k[1:]), dx/(2*k[-1])]
resistance[n//2] += contact
g = 1 / resistance
matrix = np.diag(g[:-1]+g[1:]) - np.diag(g[1:-1], 1) - np.diag(g[1:-1], -1)
rhs = np.zeros(n)
rhs[0], rhs[-1] = g[0]*left, g[-1]*right
temperature = solve_dense(matrix, rhs)
fluxes = -np.diff(np.r_[left, temperature, right]) / resistance
q = fluxes[0]
assert np.allclose(fluxes, (left-right)/(length/2/k[0]+contact+length/2/k[-1]))
hot_face = temperature[n//2-1] - q*dx/(2*k[0])
cold_face = temperature[n//2] + q*dx/(2*k[-1])
assert np.isclose(hot_face-cold_face, q*contact)
x = np.r_[0, centres[:n//2], length/2, length/2, centres[n//2:], length]
y = np.r_[left, temperature[:n//2], hot_face, cold_face, temperature[n//2:], right]
ax.plot(100*x, y, color=colour, label=f"Contact resistance {contact:g} m² K/W")
print(f"Flux {q:.0f} W/m²; interface jump {hot_face-cold_face:.1f} K")
ax.set(xlabel="Distance through slabs (cm)", ylabel="Temperature (K)")
ax.legend()
ax.grid(alpha=0.2)
fig.savefig("partial-differential-equations.png", dpi=160)

Apply a convective boundary
At an exterior face the outward heat flux obeys \(q=h_c(T_s-T_\infty)\), a Robin condition. Eliminate the unknown surface temperature as above to obtain
If \(h_c\) tends to zero, the boundary becomes insulating. With very large \(h_c\), the surface approaches ambient temperature while the finite centre-to-face resistance remains. For \(d=0.01\) m, \(k=2\), \(h_c=100\) W/(m² K), \(T_P-T_\infty=15\) K, the predicted flux is 1000 W/m² and the surface is 10 K above ambient. Multiplying by face area converts this flux to the power used in a cell energy balance. Mixing up these two quantities makes the result depend incorrectly on mesh area.
A jump located inside a cell
If the materials change at a known position inside a segment, the fractions of that segment matter. Moving the interface so that 75 percent of the length has conductivity 2 and 25 percent has conductivity 10 produces effective conductivity \(1/(0.75/2+0.25/10)=2.5\) W/(m K). Giving each material half the segment instead would give \(10/3\) W/(m K). The harmonic rule depends on actual layer thicknesses. A mesh-refinement study that snaps the interface to different positions at every refinement can mix geometric representation error with flux-discretisation error.
Derive effective transport parallel and normal to layers
A fine laminate of isotropic materials can have a direction-dependent macroscopic conductivity. Consider two perfectly bonded planar layers occupying thickness fractions \(\theta\) and \(1-\theta\), with conductivities \(k_1,k_2\). Assume steady conduction, no internal sources, and boundary conditions that permit a one-dimensional field for the loading orientation being tested. For transport normal to the layers, continuity forces equal flux. Adding their temperature drops across a total thickness \(L\) gives
For transport parallel to the layers the imposed longitudinal gradient is common and the area-weighted fluxes add, giving \(k_\parallel=\theta k_1+(1-\theta)k_2\).
The arithmetic and harmonic expressions are thus both correct, but apply to different geometries of imposed transport. Their ordering follows without a conductivity table: multiplying the two positive weighted sums \(\theta k_1+(1-\theta)k_2\) and \(\theta/k_1+(1-\theta)/k_2\) gives \(1+\theta(1-\theta)(k_1-k_2)^2/(k_1k_2)\ge1\). Equality requires identical conductivities or a missing layer. Spatial averaging performed before identifying the flux direction would erase precisely the distinction that determines the coarse physics.
Predict two experiments on the same material sample
Suppose a repeated laminate consists of 40 percent material with conductivity 1 and 60 percent with conductivity 10 W/(m K). Then \(k_\parallel=0.4+6=6.4\) W/(m K) and \(k_\perp=1/(0.4+0.06)=50/23\approx2.174\) W/(m K). A temperature drop of 4 K over 0.02 m imposes gradient magnitude 200 K/m. Perfectly normal loading produces flux magnitude about 434.8 W/m², whereas the same gradient parallel to the layers yields 1280 W/m². The larger flux is consistent with the fast material providing a continuous path in the latter orientation.
For the normal experiment the low-conductivity phase occupies 0.008 m and accounts for a drop \(434.8(0.008)/1\approx3.478\) K. The high-conductivity phase occupies 0.012 m and drops only \(434.8(0.012)/10\approx0.522\) K. Adding recovers the imposed four kelvin. For the parallel experiment individual flux densities are 200 and 2000 W/m². Averaging by their area fractions gives
These local checks use the same two material properties and explain the difference in the observed coarse responses.
Using the effective tensor assumes the observation scale spans representative layers. A sensor within one layer may respond to its local temperature slope instead. Finite contact resistance adds a temperature jump in the normal direction; if the number of interfaces per macroscopic length changes, the effective normal resistance changes even at identical material fractions. Measuring both orientations can distinguish geometric or contact effects that a single scalar fitted conductivity would conceal.
Rotating a laminate specimen through ninety degrees interchanges the roles of these two effective values without changing its volume fractions. This makes an orientation experiment particularly discriminating: a fit that happened to reproduce the first orientation by adjusting a scalar conductivity predicts the same flux for the rotated specimen, whereas the fine-layer balance predicts a factor of about \(6.4/(50/23)=2.94\) between them.
Repeating the test over multiple layer spacings also probes the assumption of negligible contact resistance.
Separate the temperature jump from the bulk gradient
A steady one-dimensional stack has two positive bulk conduction resistances in series with a contact resistance \(R_c\). Flux is common to all three. Scale \(R_c\) by the sum of bulk resistances and predict where probes would measure the imposed end-to-end temperature difference.

Read values from the plot
| Contact resistance / combined bulk resistance | At interface | Within the two layers |
|---|---|---|
| 0 | 0 | 1 |
| 1.25 | 0.55556 | 0.44444 |
| 2.5 | 0.71429 | 0.28571 |
| 3.75 | 0.78947 | 0.21053 |
| 5 | 0.83333 | 0.16667 |
Change parameters · Separate the temperature jump from the bulk gradient
Change one input at a time and compare the recalculated curves with the argument above. The browser evaluates this small model locally; the accompanying numerical values state its assumptions and reference checks. Reset restores the reference inputs, and the data can be downloaded as CSV.
Study the full derivation
Bound diffusion error by balancing a reconstructed flux · Spatial discretisation and field equations
A temperature field from a finite-element calculation looks smooth. Reconstruct a heat flux which exactly balances the source, then derive an upper bound for the true energy error without knowing the exact temperature.
Chapter 8 · Anisotropic diffusion and mesh alignment
Relate a diffusion tensor to principal directions and test whether a face-flux approximation can represent a rotated material.
From first principles
Derive the anisotropic diffusion operator from a rotated material law
Choose the principal axes of a homogeneous medium. Along them the measured flux response is diagonal, so heat conduction in direction 1 has coefficient \(k_1>0\) and in direction 2 has \(k_2>0\). Let orthogonal matrix \(R\) map principal-axis components into laboratory coordinates. Gradients rotate back with \(R^\mathsf T\), while the calculated flux rotates forward with \(R\). The material law in laboratory axes is therefore
Insert this vector law into local steady conservation \(\nabla\cdot\mathbf q=s\), with \(s\) a positive volumetric source. Expanding for constant \(K\) gives the mixed derivative explicitly:
Positive principal conductivities make \(\nabla T^\mathsf T K\nabla T\) nonnegative, the basic energy property that a spatial discretization should respect. In a rotated material, the flux need not be perpendicular to an isotherm. A face formula using only the difference of two temperatures separated along the face normal may therefore omit a real transverse-gradient contribution.
Derivation and applications
When a two-point face flux is exact for anisotropic diffusion
A discretization can preserve conservation and still send heat in the wrong direction. Consider a planar face with area \(A\), outward unit normal \(\mathbf n\) from cell \(P\) toward cell \(N\), and centre displacement \(\mathbf d=\mathbf x_N-\mathbf x_P\). Let the constant material tensor \(K\) be symmetric positive definite. For a linear temperature field \(T=T_0+\mathbf g\cdot\mathbf x\), the continuum face rate and measured neighbour difference are
A candidate two-point law is
For it to reproduce the exact flux for every possible gradient, the two vectors multiplying \(\mathbf g\) must be identical. This gives a joint mesh-material condition:
On a grid aligned with a principal axis and with cell centres aligned along the normal, this relation gives the familiar transmissibility. Otherwise split \(AK\mathbf n\) into a component parallel to \(\mathbf d\) and a remainder \(\mathbf c\) perpendicular to it. Taking a scalar product with \(\mathbf d\) yields
The correction requires a second gradient component, usually reconstructed from more cells. Using one corrected flux with opposite signs for the two neighbours still preserves conservation. The derivation checks consistency for an exactly linear field; monotonicity and stability require separate tests.
Worked example
Test a Cartesian face in a tilted material
Let \(A=1.00\) m², \(\mathbf d=(0.200,0)\) m, \(\mathbf n=(1,0)\) and \(K\) have entries \((K_{xx},K_{xy},K_{yy})=(4,1,2)\) W/(m K). For \(\mathbf g=(0,3.00)\) K/m the neighbour difference vanishes, yet the exact outward flux is \(-3.00\) W. The decomposition gives \(\tau=20.0\) W/K and \(\mathbf c=(0,1)\) in compatible units. The entire flux therefore comes from the reconstructed transverse gradient.
Second application
Choose a skew cell arrangement that needs no correction
Keep the same tensor and normal but set \(\mathbf d=(0.200,0.0500)\) m. It lies along \((4,1)=K\mathbf n\), so \(\tau=20.0\) W/K and \(\mathbf c=0\). For a gradient \((2.00,-1.00)\) K/m the neighbour temperature rise is \(0.350\) K, giving \(-7.00\) W. Direct evaluation \(-[4(2)+1(-1)]\) agrees. Geometric orthogonality to the physical face is not required when the tensor itself tilts the relevant direction.
Begin with an energy and a constitutive law
In a conducting sheet with directional properties, heat flux is
where \(K\) is symmetric positive definite. With constant volumetric capacity, conservation gives a diffusion operator proportional to \(\nabla\cdot(K\nabla T)\). For insulating boundaries and no sources, multiplying by \(T\) and integrating by parts gives a decay term \(-\int\nabla T^TK\nabla T\). It is nonpositive because the eigenvalues of \(K\) are positive. This energy test checks the sign of a discrete spatial operator even when flux and gradient do not point along the same line.
Let the principal conductivities be 4 and 1. Rotating the principal axes through 45 degrees gives
Along the diagonal direction \((1,1)/\sqrt2\), multiplying by \(K\) scales the gradient fourfold; along the other diagonal the scale is one. Along the Cartesian \(x\) direction a transverse flux component appears. The off-diagonal entries express a real constitutive response and cannot be dropped by refining the same incorrect stencil.
A patch test for a face flux
Use the exact affine temperature \(T(x,y)=y\), whose gradient is \((0,1)^T\). The flux is \((-1.5,-2.5)^T\). A vertical face with outward normal \(e_x\) therefore carries \(-1.5\) units of flux per unit length. A two-point formula based only on temperatures at the left and right cell centres sees identical temperatures and returns zero. Both fields have zero divergence in the interior because each flux is constant, so checking interior residuals alone would miss the incorrect boundary transport. Compare individual face fluxes as well as cell residuals in a linear patch test.
To recover the normal flux one can reconstruct the full gradient using neighbouring data, or choose a weak form integrating \((\nabla v)^TK\nabla T\) over each element. On a triangle with affine basis functions the gradients are constant, so constant \(K\) yields an element matrix \(A_{ij}=|E|\nabla\phi_i^TK\nabla\phi_j\). Symmetry is immediate and the row sums vanish because the basis functions sum to one.
Distinguish length scales from transport axes
For constant \(K\), a Fourier mode \(e^{i\xi\cdot x}\) decays with factor \(e^{-t\xi^TK\xi}\) when capacity is one. At unit wave number, a mode along the fast principal axis falls to \(e^{-4}\approx0.0183\) after one unit of time; a perpendicular one retains \(e^{-1}\approx0.368\). This test excites the two conductivities separately. On an elongated mesh the mesh dimensions also affect the fastest discrete time scale, so the same physical tensor can require different explicit step sizes on two grids.
Rotate the temperature, keeping the material fixed
The directional heat transport along a unit vector \(n\) is controlled by \(n^TKn\) when the imposed temperature gradient is parallel to \(n\). For the worked tensor and \(n=(1,0)^T\), this effective conductivity is 2.5 even though the full flux has a transverse component. If the specimen instead has insulated long sides, then its transverse gradient can adjust until transverse flux vanishes. Solving \(1.5T_x+2.5T_y=0\) gives \(T_y=-0.6T_x\) and effective longitudinal flux \(-1.6T_x\). The same material therefore gives different one-dimensional reductions under different boundary constraints.
Construct a positive directional stencil for a rotated tensor
For constant \(K=\left(\begin{smallmatrix}a&b\\b&c\end{smallmatrix}\right)\), the diffusion operator is \(a u_{xx}+2b u_{xy}+c u_{yy}\). On a square grid, the centred second difference along the lattice diagonal \((1,1)\), divided by \(h^2\), approximates \((\partial_x+\partial_y)^2u\), including the required mixed derivative with positive sign. For \(b\ge0\) one can therefore combine the three directional second differences with coefficients \(a-b,c-b,b\) along the horizontal, vertical and positive diagonal directions. Expanding these terms recovers the desired operator for every quadratic field.
If all three coefficients are nonnegative, a local maximum has a nonpositive spatial diffusion update. This sign property supports a discrete maximum principle and, with a sufficiently small explicit time step, a positive averaging update. For negative \(b\), the opposite diagonal changes the mixed derivative sign and the analogous coefficients involve \(|b|\). Positive definiteness of the continuum tensor only requires \(ac>b^2\), which is weaker than both \(a\ge|b|\) and \(c\ge|b|\). A physically valid material can therefore defeat this particular compact positive stencil.
Reach a strongly tilted direction using a wider stencil
Set \(a=1,\ b=1.5,\ c=4\). The determinant \(4-2.25=1.75\) is positive and both eigenvalues are positive. Yet the compact three-direction construction would assign horizontal coefficient \(-0.5\). To see the numerical problem, give the centre value zero, both horizontal neighbours value one and all diagonal and vertical neighbours zero. The centre is a minimum, but the compact operator returns \(-1/h^2\). An explicit positive time step would drive that minimum below zero, contradicting the smoothing behaviour expected from a monotone diffusion discretisation.
Consider instead a second difference along the longer lattice vector \((1,2)\). Dividing by \(h^2\) with coordinate increments \(h,2h\) approximates \(u_{xx}+4u_{xy}+4u_{yy}\). Multiplying it by \(0.75\) produces the desired mixed coefficient three. The remaining horizontal and vertical coefficients are \(1-0.75=0.25\) and \(4-3=1\), both positive. At an interior node this wider stencil has all positive neighbour couplings. On the quadratic patch \(u=xy\) the exact operator value is three; the long diagonal evaluates the centred difference as four, and its weighted contribution is exactly three while both axial differences vanish.
The longer reach introduces a boundary question: a point one row from the edge may lack a neighbour two rows away. Replacing it ad hoc with a nearest available value can destroy consistency or positivity. A boundary treatment, a mesh aligned to the material axes or a compatible finite-element formulation must address that issue separately. Selecting a positive interior stencil alone does not prove a complete domain discretisation monotone.
For the wider stencil an explicit update at an interior node has centre coefficient \(1-2(0.25+1+0.75)\Delta t/h^2\) for unit heat capacity. Preserving nonnegative weights therefore requires \(\Delta t\le h^2/4\) in the units of this example. Positive face couplings are necessary for this argument, while a compatible time step supplies the remaining condition.
Change parameters · Explore the worked calculation
Change one input at a time and compare the recalculated curves with the argument above. The browser evaluates this small model locally; the accompanying numerical values state its assumptions and reference checks. Reset restores the reference inputs, and the data can be downloaded as CSV.
Problem sheet 4 · Material interfaces and anisotropy
Recover face temperatures and fluxes, and use a linear temperature field to test a rotated conductivity tensor.
Add an interface contact
Two cell centres at 45 and 15 °C each lie 0.02 m from a contact. The conductivities are 4 and 2 W/(m K), and the contact resistance is 0.005 m²K/W. Find flux, both surface temperatures and the conducted power over 0.03 m².
Worked solution
The resistances are \(0.02/4=0.005,\ 0.005,\ 0.02/2=0.010\) m²K/W in series. Total 0.020 gives \(q=30/0.020=1500\) W/m² toward the colder cell.
The hot-side face is \(45-1500(0.005)=37.5\) °C. The cold-side face is \(37.5-7.5=30\) °C, and the last drop is 15 K. Power is \(1500(0.03)=45\) W.
Explore the related calculation with adjustable inputs. Vary series resistances and observe their fractions of the total drop. Divide by the stated bulk resistance when converting dimensional values to a comparison.
Identify a convective resistance
The centre temperature is 50 °C, ambient is 20 °C and outward flux is 1200 W/m². The half-cell resistance is 0.01 m²K/W. Determine surface temperature and boundary heat-transfer coefficient. Test the prediction after halving the centre-to-face distance while keeping centre and ambient values fixed.
Worked solution
The surface is \(50-1200(0.01)=38\) °C. Boundary resistance is \((38-20)/1200=0.015\) m²K/W, giving \(h_c=66.67\) W/(m²K).
The new total resistance is \(0.005+0.015=0.020\), so flux is 1500 W/m² and surface temperature is 42.5 °C. The material and boundary laws were held fixed; the unchanged centre value now belongs to a different physical location.
Explore the related calculation with adjustable inputs. Vary series resistances and observe their fractions of the total drop. Divide by the stated bulk resistance when converting dimensional values to a comparison.
Test a rotated flux
Take \(K=\left(\begin{smallmatrix}3&-1\\-1&3\end{smallmatrix}\right)\), \(T=2x+y\). Find both flux components and eigenvalues. Which diagonal plane-wave direction decays faster, and what normal flux should an east-facing face record?
Worked solution
\(K\nabla T=(5,1)^T\), so the flux is \((-5,-1)^T\). The principal conductivities are 2 along \((1,1)\) and 4 along \((1,-1)\).
With equal wave numbers and unit capacity, the second diagonal decays twice as rapidly in its exponent. An east-facing face has normal \(e_x\) and records −5. Dropping the off-diagonal coefficient would instead give −6.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Notebook practice · Touch two long solids: which temperature does the interface acquire?
Chapter 9 · Cell Péclet number and monotonicity
Derive the sign restriction for centred transport, identify a numerical boundary layer and quantify the diffusion introduced by upwinding.
From first principles
Derive the Péclet restriction for a centred steady stencil
Take steady one-dimensional transport with constant speed \(a>0\), diffusivity \(D>0\) and no interior source. Conservation requires constant total flux \(J=au-Du'\). On a uniform mesh of spacing \(h\), approximate the advective face value by the arithmetic mean and the face gradient by a difference. The right face flux becomes
Equating the two neighbouring face fluxes and collecting the centre coefficient gives a relation among the three consecutive values:
For \(|\mathrm{Pe}_h|\le2\) the centre value is a positive weighted average of its neighbours. Above that threshold one weight becomes negative and the discrete solution can overshoot even when the continuum solution is monotone. This restriction is on the local cell Péclet number, not on \(aL/D\) for the whole physical domain. Smaller cells, an upwind flux or an exponentially fitted flux can change the discrete behaviour.
Derivation and applications
Distinguish an imposed inlet flux from an imposed inlet concentration
With diffusion, a concentration measurement alone does not specify the total material entering a channel. Consider steady one-dimensional advection at constant speed \(a>0\) and diffusion coefficient \(D>0\), constant area, no reaction, and coordinate \(0<x<L\). Concentration is \(u(x)\). The net species flux is the sum of advection and diffusive backflow. Conservation makes it constant throughout the interval:
Suppose the upstream supply delivers a specified total flux \(J=a u_f\), where \(u_f\) is the incoming feed concentration used to normalize the supply rate. Prescribe an outlet concentration \(u(L)=u_L\) maintained by a reservoir. Subtract the uniform particular solution \(u_f\). The resulting first-order homogeneous equation for the excess has a convenient outlet-referenced solution:
At the inlet the interior concentration can differ from the feed because diffusion also contributes to the prescribed mass rate. Define \(\mathrm{Pe}=aL/D\) and evaluate both terms at \(x=0\):
For large Péclet number the outlet affects only a layer of thickness \(D/a\). For small Péclet number the outlet reservoir can affect the whole channel. Imposing both \(u(0)=u_f\) and the specified total flux at the inlet would impose more conditions than this problem needs. A numerical method should record which physical boundary condition it approximates.
Worked example
Compute a moderate-Péclet-number channel profile
Take \(L=1.00\) m, \(a=0.0200\) m/s, \(D=0.0100\) m²/s, \(u_f=1.00\) and \(u_L=0\) kg/m³. The inlet concentration is \(1-e^{-2}=0.8647\) kg/m³ and the midpoint is \(1-e^{-1}=0.6321\) kg/m³. Inlet advection carries \(0.01729\) kg/(m² s) and diffusion supplies \(0.00271\) kg/(m² s), giving the prescribed total \(0.0200\).
Second application
Quantify a boundary-condition error
If a code instead fixes \(u(0)=1.00\) and \(u(L)=0\), its exact constant flux for those Dirichlet data satisfies
Hence \(J=0.0200/(1-e^{-2})=0.0231\) kg/(m² s), about \(15.7\%\) too large for the original feed problem. Grid refinement can converge cleanly to that incorrect-for-purpose value because the error lies in the boundary model.
Which length sets the balance?
Model a steady scalar on \([0,L]\) with \(a u'-\kappa u''=0\), constant speed \(a>0\) and diffusivity \(\kappa>0\). Advection and diffusion balance over length \(\ell=\kappa/a\). On a mesh with spacing \(h\), the cell Péclet number \(P=ah/\kappa\) measures how many layer lengths fit into one cell. This definition uses the full cell spacing; some conventions divide it by two. Stating the convention matters when quoting a threshold.
Write the centred interior equation in flux form. Its coefficients multiplying \(u_{j-1},u_j,u_{j+1}\) are \(-\kappa/h^2-a/(2h),2\kappa/h^2,-\kappa/h^2+a/(2h)\). For \(P\le2\), the neighbour coefficients are nonpositive and the row sum is zero, so each interior value is a weighted average of its neighbours. For \(P>2\), one weight changes sign. The discrete maximum principle can fail even though the centred derivative is formally second-order accurate on smooth resolved fields.
Watch a node cross below the boundary range
Take \(L=1,a=1,\kappa=0.1\), \(u(0)=0,u(1)=1\) and two equal cells. Then
At the only interior node the coefficients are \(-1.4,0.8,0.6\). The numerical value is \(-0.75\), outside the prescribed boundary range. The exact solution is \((e^{ax/\kappa}-1)/(e^{aL/\kappa}-1)\), increasing and close to zero except near the outlet. At \(x=0.5\) it is \(1/(e^5+1)\approx0.00669\). The coarse grid does not resolve a physical layer of width 0.1.
Using the upstream difference \((u_j-u_{j-1})/h\) changes the coefficients to \(-2.4,2.8,-0.4\); the computed midpoint is \(1/7\). The value lies in range but the layer is excessively broad. A monotone method can replace an oscillation with a large smoothing error. Plot the magnitude of the profile at fixed physical locations while refining to distinguish those outcomes.
Explain the extra diffusion
Expand \(u_{j-1}=u_j-hu'_j+h^2u''_j/2+\cdots\). The upstream derivative is \(u'_j-hu''_j/2+O(h^2)\). The leading modified equation therefore contains effective diffusivity \(\kappa+ah/2\). In the example the artificial addition is 0.25, larger than the physical diffusivity 0.1. Reducing \(h\) below 0.2 restores the coefficient-sign requirement for the centred formula, while resolving the layer shape accurately generally needs several cells across \(\ell\). A convergence study should report both bounds compliance and the actual layer width or flux.
Fit the face flux to a constant-coefficient cell
For smooth constant coefficients the total flux \(J=au-\kappa u'\) is constant in a source-free cell. Solve this first-order equation between endpoints separated by \(h\). The exact relation is \(u_R=e^P u_L+(J/a)(1-e^P)\), hence \(J=a(e^P u_L-u_R)/(e^P-1)\). At large positive \(P\), the flux approaches \(a u_L\), the value carried from upstream. As \(P\) tends to zero, expansion gives a diffusive difference \(-\kappa(u_R-u_L)/h\) plus the centred advective contribution \(a(u_L+u_R)/2\). This exponential fitting uses additional local knowledge of the differential equation. It reproduces the constant-coefficient cell relation exactly, but variable material properties and sources require new local approximations.
Allocate grid points to a singularly perturbed outflow layer
For steady positive advection and small diffusivity the outflow layer shape is approximately \(e^{-(L-x)/\ell}\), with physical thickness scale \(\ell=\kappa/a\). A uniform grid that resolves that scale at a fixed number of points may waste most of its cells where the solution is almost flat. A simple layer-adapted strategy divides the domain into a coarse interval and a fine interval ending at the outflow boundary. Choose the fine-region width \(\tau\) by specifying how small the layer should already be at their interface.
If \(e^{-\tau/\ell}=N^{-2}\) for a grid with \(N\) total cells, then \(\tau=2\ell\log N\). Capping this width at \(L/2\) prevents a separate-layer construction when the physical layer is no longer thin. Place half the cells on each subinterval. This produces a piecewise-uniform grid, often called a Shishkin mesh for this boundary-layer setting. The amplitude threshold motivates its construction; it is not itself a proof of a particular numerical convergence rate. Such a proof must also control truncation, stability and matching across the grid transition.
Compare the information captured by sixty-four cells
Consider \(L=1\) m, \(a=1\) m/s and \(\kappa=0.002\) m²/s. Then \(\ell=0.002\) m. A uniform mesh of 64 cells has spacing 0.015625 m, almost eight physical layer lengths per cell. The first interior point back from the outflow has layer amplitude about \(e^{-7.8125}\approx0.000405\). Most of the transition from nearly zero to one takes place in a single cell. A method may fit an acceptable boundary value while giving a poor near-wall shape or slope.
The two-region design instead places its transition \(\tau=0.004\log64\approx0.01664\) m before the end. With 32 fine cells, their width is approximately 0.000520 m, so the fine cell Péclet number is about 0.260. At the last interior point the layer amplitude is now \(e^{-0.260}\approx0.771\). Several distinct intermediate values are available near the wall. At the coarse-to-fine transition the amplitude is \(64^{-2}\approx0.000244\), just as designed.
The coarse cells on the remaining 0.98336 m have width about 0.03073 m and cell Péclet number about 15.4. Their small expected layer amplitude does not license an unstable or nonmonotone coarse discretisation. Use a spatial scheme whose behaviour is controlled there, and check flux continuity through the changing cell sizes. If advection reverses, the thin layer moves to the opposite boundary; retaining the old mesh would concentrate cells in the wrong region. In time-dependent transport, moving layers may similarly call for adaptive tracking instead of a fixed partition.
The wall derivative supplies a more demanding check than a prescribed boundary value. For the exponential layer its exact slope at outflow has magnitude \(1/\ell=500\) per metre. A backward difference across the final fine cell gives approximately \((1-0.771)/0.000520=440\) per metre. Even this substantially improved mesh still underestimates the wall slope by about twelve percent, which matters if wall flux is the reported observable.
Expose a monotonicity failure on ten cells
For constant positive advection and diffusion solve \(u''-\mathrm{Pe}\,u'=0\) with end values zero and one. At cell Péclet number three, the centred recurrence has ratio \((1+\mathrm{Pe}_h/2)/(1-\mathrm{Pe}_h/2)=-5\); the upwind ratio is four.

Read values from the plot
| Position / domain length | Exact | Centred cells | First-order upwind |
|---|---|---|---|
| 0 | 0 | 0 | 0 |
| 0.2 | 3.7658e−11 | 2.4576e−6 | 1.4305e−5 |
| 0.5 | 3.059e−7 | −0.0003201 | 0.00097561 |
| 0.8 | 0.0024788 | 0.04 | 0.062499 |
| 1 | 1 | 1 | 1 |
Change parameters · Expose a monotonicity failure on ten cells
Change one input at a time and compare the recalculated curves with the argument above. The browser evaluates this small model locally; the accompanying numerical values state its assumptions and reference checks. Reset restores the reference inputs, and the data can be downloaded as CSV.
Study the full derivation
Choose the physically admissible wave in a conservative update · Spatial discretisation and field equations
A discontinuous scalar flow can satisfy integral conservation in more than one way. Derive the shock speed, use a convex entropy to distinguish a compression from an expansion and build a finite-volume flux from the resulting local solution.
Chapter 10 · Incompressibility and discrete pressure modes
Derive the velocity–pressure block system and use a periodic mesh to detect a pressure pattern that exerts no discrete force.
From first principles
Eliminate velocity to expose the pressure equation
In a mixed incompressible discretization, velocity responds to applied force and pressure while pressure enforces zero discrete divergence. Let \(A\) be a positive definite velocity block after applying boundary conditions, \(B\) the discrete divergence, and use \(B^\mathsf T\) with the corresponding weak pressure sign convention. With forcing \(f\) and prescribed divergence \(g\) the block equations are
Eliminate velocity by applying the inverse action of \(A\) to the first equation and substituting into the second. The resulting pressure Schur system is
Since \(p^\mathsf TSp=(B^\mathsf Tp)^\mathsf T A^{-1}(B^\mathsf Tp)\), a pressure vector is invisible precisely when its discrete gradient vanishes. A constant pressure often has this property by physics; additional oscillatory pressure null modes can indicate incompatible spaces. Fixing a pressure reference removes the arbitrary constant but does not cure those extra modes. Once pressure is obtained, substitute it back to recover a velocity satisfying the original continuity equation.
Derivation and applications
Follow a pressure Fourier mode through two discrete gradients
The divergence and pressure-gradient operators must recognize every nonconstant pressure that is meant to constrain the velocity. Consider an even number of uniformly spaced periodic cells along a line, with pressure \(p_j\) at cell centres. A one-dimensional Fourier mode \(p_j=e^{ij\theta}\) is a convenient algebraic test; the constant mode is the expected arbitrary pressure reference. Suppose a colocated method uses a centred pressure gradient at the same locations:
The pressure Schur operator in a simplified projection with identity velocity mass is \(G_c^\ast G_c\). Its eigenvalue is the squared magnitude of that gradient multiplier. It vanishes both at \(\theta=0\) and at the checkerboard \(\theta=\pi\). To compare, place normal velocity at faces and difference its adjacent cell pressures:
Combining the face gradient with its adjoint yields two different pressure operators on the same grid:
At long wavelengths both agree with \(k^2\) for physical wavenumber \(k=\theta/h\). At the alternating mode, staggered differences detect adjacent pressure differences even though a centred two-cell difference cancels them. This calculation isolates one spatial compatibility issue; other geometries and velocity boundary conditions require the full divergence-gradient pairing to be checked.
Worked example
Compare a resolved oscillation with a checkerboard
On a grid with \(h=0.100\) m, choose \(\theta=\pi/2\). The two Schur eigenvalues are \(100\) and \(200\) m⁻². At \(\theta=\pi\) they become zero and \(400\) m⁻² respectively. A unit-amplitude alternating pressure consequently produces zero centred forces, although its differences across neighbouring faces have magnitude \(20.0\) per metre.
Second application
Test the effect of setting the pressure mean to zero
An even periodic grid with pressure values \(+3,-3,+3,-3\) Pa has zero arithmetic mean. Fixing that mean does nothing to its spurious mode in the centred scheme. With face velocities the pressure gradients alternate between \(-60\) and \(+60\) Pa/m for \(h=0.100\) m. A compatible projection sees these forces and excludes this pattern from the nullspace. Removing an arbitrary constant addresses a different degeneracy.
Pressure enforces a constraint
For a steady incompressible viscous fluid, one simplified model is \(-\mu\Delta u+\nabla p=f\), \(\nabla\cdot u=0\), with prescribed wall velocity. Multiplying momentum by a velocity test function vanishing at the wall and integrating by parts gives
Testing incompressibility with a pressure test function completes a coupled weak formulation. Adding a constant to pressure leaves its gradient unchanged, so use a reference pressure or impose zero mean in a closed domain.
Choose discrete velocity and pressure spaces, and define \(B\) as the negative weak divergence. After eliminating prescribed velocities, the block equations are
with \(A\) positive definite under these boundary conditions. Eliminating velocity yields the pressure operator \(BA^{-1}B^T\). Its quadratic form is \((B^Tp)^TA^{-1}(B^Tp)\). A nonconstant pressure whose discrete gradient vanishes therefore survives as a spurious null mode, even if the velocity block is exceptionally well conditioned.
Test a checkerboard
On an even periodic one-dimensional grid use the collocated centred gradient \((p_{j+1}-p_{j-1})/(2h)\). Choose \(p_j=(-1)^j\). The two neighbouring pressures match, so the gradient is zero at every velocity point. The pressure has zero mean and amplitude one, making it independent of the constant pressure ambiguity. For values \(1,-1,1,-1\) and \(h=0.25\), the result is still the identically zero vector. A pressure solver applied to such a discretisation can retain arbitrary amounts of this alternating pattern without changing the velocity residual.
Placing velocities on the faces instead leads to a face gradient \((p_{j+1}-p_j)/h\). On the same four-cell grid its magnitudes are all 8 with alternating signs. This layout couples the previously invisible pressure variation to the velocity unknowns. The one-dimensional example diagnoses an algebraic pairing issue. In higher dimensions the geometry, boundaries and full selection of discrete spaces also affect stability.
A uniform coupling requirement
A family of stable mixed spaces requires a lower bound, independent of mesh size, on the largest discrete divergence pairing a normalised pressure can obtain with a normalised velocity test. This is the discrete inf-sup condition, with pressures measured after removing their constant ambiguity. It excludes both exact checkerboards and nearly invisible modes that become worse as the mesh is refined. A standard finite-element pairing on suitable triangulations combines continuous quadratic velocities with continuous linear pressures. Other pairings need a separate stability argument or stabilising terms.
Check discrete divergence and momentum, then inspect pressure on grid-scale patterns. A smooth velocity, or even a small residual in both block equations, provides very little information about the amplitude of a pressure component on which those equations have no sensitivity.
Give pressure a reference without changing forces
Replacing a four-cell periodic pressure vector \((2,4,6,8)^T\) by its zero-mean representative \((-3,-1,1,3)^T\) leaves every face difference unchanged. The mean removal fixes one arbitrary pressure level. Adding the checkerboard \((1,-1,1,-1)^T\) also preserves its mean, yet changes the individual face differences. This distinction makes a practical diagnostic: verify a constant shift has no physical effect, then test whether a nonconstant alternating shift produces a physically nonzero force in the chosen velocity space. Passing the former test alone cannot reveal uncoupled pressure coordinates.
Project a tentative velocity onto discrete incompressibility
After an explicit force update a tentative velocity \(v^\ast\) may have nonzero discrete divergence. Suppose \(M\) is a symmetric positive definite velocity mass matrix and the desired constraint is \(Bv=0\). Find the divergence-free velocity closest to \(v^\ast\) in the kinetic metric by minimising \((v-v^\ast)^TM(v-v^\ast)/2\). Introducing a multiplier \(p\) gives
Applying \(B\) to the resulting corrected velocity yields
Here \(p\) acts as a pressure impulse; conversion to a physical pressure depends on the time-step and scaling conventions.
The correction \(M^{-1}B^Tp\) is mass-orthogonal to every admissible velocity \(w\), since \(w^TB^Tp=(Bw)^Tp=0\). Hence the norm of the tentative state splits into squared norms of the corrected velocity and removed component. This projection never increases kinetic energy in homogeneous constraints. A null pressure mode with \(B^Tp=0\) does not affect the corrected velocity; fixing a gauge can select a unique multiplier. If the discrete gradient and divergence are assembled inconsistently, the orthogonality and corresponding energy argument may fail even if a pressure equation is solved accurately.
Follow an impulse through three velocity unknowns
Choose \(M=\operatorname{diag}(1,2,1)\), and let \(Bv=(v_1-v_2,v_2-v_3)^T\). Constraint-compatible velocities have all three components equal. The tentative velocity is \((0,0,2)^T\), with weighted momentum two and kinetic energy two. Its divergence vector is \((0,-2)^T\). Multiplying \(BM^{-1}B^T\) gives diagonal entries 1.5 and off-diagonal entries −0.5. Solving this two-by-two system yields
Recover \(B^Tp=(-0.5,-1,1.5)^T\), then
Subtracting gives \(v=(0.5,0.5,0.5)^T\), now satisfying both constraints. Its weighted momentum is still two because the constant velocity vector is admissible and therefore mass-orthogonal to the correction. The final kinetic energy is 0.5. The removed component has energy \([0.25+2(0.25)+2.25]/2=1.5\), exactly the energy difference. Both conservation of uniform momentum and removal of the incompatible component have been checked numerically.
With prescribed boundary fluxes the target constraint is generally inhomogeneous. The closest admissible velocity then lies in an affine space; the preceding zero-centred energy decrease need no longer hold because boundaries can do work. Transforming to fluctuations about a boundary-compatible lifting can restore an orthogonality statement for the correction. Before interpreting a pressure projection's apparent dissipation or energy injection, specify the boundary conditions and the metric used in its derivation.
For the same tentative state an ordinary unweighted Euclidean projection would set all velocities to their arithmetic mean \(2/3\). That also makes both discrete differences zero, but the weighted momentum becomes \(8/3\), exceeding its initial value two. A check on incompressibility alone would accept this physically different state. Choosing a mass matrix in the pressure correction is therefore consequential whenever cell masses, staggered volumes or basis-function weights differ. Evaluating both the discrete divergence and the physically weighted momentum provides information that neither result supplies on its own.
The impulse components give an additional equation-level diagnostic because applying their discrete gradient must reproduce the actual velocity correction.
Change parameters · Explore the worked calculation
Change one input at a time and compare the recalculated curves with the argument above. The browser evaluates this small model locally; the accompanying numerical values state its assumptions and reference checks. Reset restores the reference inputs, and the data can be downloaded as CSV.
Problem sheet 5 · Transport weights and pressure spaces
Locate the onset of a sign error and test which discrete pressure differences actually drive a velocity.
Resolve a layer
Let \(a=3\) m/s, \(\kappa=0.06\) m²/s on a 1 m interval. Find the minimum number of equal cells for the centred operator's nonpositive neighbour coefficients, and the number giving five cells per physical layer length. Estimate the upwind artificial diffusivity at each resolution.
Worked solution
The layer length is
The sign test requires \(h\le2\ell=0.04\) m, hence at least 25 cells. Five cells across \(\ell\) require \(h\le0.004\) m or 250 cells.
The upwind addition \(ah/2\) is 0.06 m²/s at 25 cells and 0.006 at 250. The monotonicity threshold and satisfactory physical resolution describe quite different demands.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Change transport direction
On an equally spaced grid take \(a<0\). Derive the upstream discrete derivative, its leading artificial diffusivity in \(a u'-\kappa u''\), and the boundary near which a thin outflow layer forms for fixed unequal Dirichlet values.
Worked solution
With flow toward decreasing \(x\), upstream information lies to the right, giving \((u_{j+1}-u_j)/h=u'_j+hu''_j/2+O(h^2)\).
Multiplying by a negative speed gives the modified coefficient \(-(\kappa+|a|h/2)u''\). On \([0,L]\) inflow is at \(L\) and outflow at zero. The term \(e^{ax/\kappa}\) decays away from zero, locating a possible outflow boundary layer there.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Find the pressure nullspace
For an even periodic grid with six pressure nodes, solve \(p_{j+1}-p_{j-1}=0\) for all \(j\). Remove the constant ambiguity and give the dimension of the remaining nullspace. Repeat the argument for five nodes.
Worked solution
The relation is
Six nodes split into independent even and odd cycles, giving two arbitrary amplitudes. Removing the constant leaves one alternating mode.
With five nodes, increments of two cycle through every index, so all entries agree. Only the constant remains and zero mean removes it. This finite odd-grid observation by itself does not establish a mesh-independent mixed stability bound.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Chapter 11 · Multigrid and coarse-grid correction
Combine smoothing with a coarse residual equation and compute which components a two-grid correction can remove exactly.
From first principles
Derive the coarse-grid correction as a residual equation
Let a linear discretization satisfy
For an iterate \(\tilde u_h\) define error \(e_h=u_h-\tilde u_h\) and residual \(r_h=b_h-A_h\tilde u_h\). Subtracting the equations gives an exact identity:
A coarse mesh cannot represent arbitrary fine error. Suppose the error remaining after smoothing is approximated by \(Pe_H\), with prolongation \(P\) from coarse to fine. Choose coarse coefficients so the remaining residual is orthogonal to the coarse test directions; with restriction \(R=P^\mathsf T\) this condition becomes
Update the fine iterate by \(\tilde u_h\leftarrow\tilde u_h+Pe_H\). If the coarse solve is exact, this removes any error initially in the range of \(P\). Components outside that range must be reduced by smoothing or another correction. This separation explains why simply smoothing a fine mesh for longer can be inefficient when long-wavelength error survives each relaxation sweep.
Derivation and applications
Choose a Jacobi weight for the errors a coarse grid cannot resolve
A multigrid smoother should damp oscillations left invisible or ambiguous on the coarse mesh. Consider the uniform one-dimensional discretization of \(-u''\) with stencil \((-1,2,-1)/h^2\), away from boundaries or on a periodic grid. Let the error be a Fourier mode \(e_j=e^{ij\theta}\). The Jacobi diagonal is \(D=(2/h^2)I\). Inserting the Fourier mode into the discrete operator and dividing by \(D\) gives
One weighted Jacobi step \(\tilde u\leftarrow\tilde u+\omega D^{-1}(b-A\tilde u)\) therefore multiplies the error by a real factor. With standard factor-two coarsening, call the interval \(\pi/2\le|\theta|\le\pi\) high frequency:
The maximum absolute value on this interval lies at an endpoint. To minimize that worst factor, set the two endpoint values equal in magnitude and opposite in sign. The solution is
An ordinary undamped Jacobi sweep (\(\omega=1\)) leaves the checkerboard oscillating with unchanged magnitude. The optimal weight here depends on the operator, dimensionality and coarsening convention. It should not automatically be transferred to anisotropic grids or different stencils.
Worked example
Calculate how many smoothing sweeps are needed
A pure high-frequency error initially has amplitude \(0.900\) K. With \(\omega=2/3\), three sweeps reduce it to at most \(0.900/27=0.0333\) K. For the checkerboard the factor is \(-1/3\), so after the third sweep the error has reversed sign. Four sweeps bound the amplitude by \(0.0111\) K. A residual norm insensitive to sign still sees the decay.
Second application
Observe why smoothing alone is slow
At \(\theta=\pi/16\), the same smoother gives
After ten sweeps a unit component still has amplitude \(0.9872^{10}=0.879\). A high-frequency component over the same ten sweeps is at most \(3^{-10}=1.69\times10^{-5}\). Coarse-grid correction targets the slowly decaying component that these sweeps leave behind.
Two kinds of persistent error
For a uniform Dirichlet grid let \(A_h\) be the positive three-point approximation to \(-u''\). A smooth algebraic error changes slowly between adjacent nodes. Its local residual can be modest even when its amplitude is appreciable. High-frequency errors have large second differences and respond rapidly to a suitable relaxation sweep. Weighted Jacobi uses \(u\leftarrow u+\omega D^{-1}(f-A_hu)\), with diagonal \(D=2I/h^2\). On a sine mode of grid angle \(\theta\) its error multiplier is \(1-\omega(1-\cos\theta)\).
For \(\omega=2/3\), this multiplier lies between \(-1/3\) and \(1/3\) for angles between \(\pi/2\) and \(\pi\). Low angles have multipliers near one, so repeated sweeps alone cost increasingly many iterations as the grid is refined. Those surviving smooth errors can often be represented on a coarser mesh. The purpose of restricting a residual is to solve an error equation for that representation.
Derive the correction
Let \(P\) interpolate coarse values to the fine grid and \(R\) restrict a fine vector. Choose the Galerkin coarse operator \(A_H=RA_hP\). Given current residual \(r=f-A_hu\), solve \(A_He_H=Rr\) and add \(Pe_H\). If the true error is precisely \(Pv\), the right-hand side equals \(A_Hv\). An exact coarse solve recovers \(v\) and removes the entire error in one correction. For general errors the new residual satisfies \(Rr_{\rm new}=0\); high-frequency components may remain on the fine grid.
Compute one correction by hand
Take \(h=1/4\) with three interior fine nodes and one interior coarse node at the midpoint. Linear interpolation is \(P=(1/2,1,1/2)^T\), and full weighting gives
The fine operator is 16 times the tridiagonal matrix with diagonal 2 and off-diagonal −1. Multiplication gives \(A_hP=(0,16,0)^T\) and \(A_H=8\). Suppose \(u=0\) and the exact fine solution is \(P\), so the load is \((0,16,0)^T\). The restricted residual is 8. The coarse correction returns the coefficient one and removes the error exactly.
For error \(e=(1,0,-1)^T\), the fine residual is \(32e\), whose restriction is zero. The coarse grid cannot correct this component. Its grid angle is \(\pi/2\), so one weighted Jacobi sweep leaves \(e/3\). These two vectors demonstrate why combining the two operations matters. Repeating the idea recursively gives a V-cycle. With a fixed number of smoothing steps per level, geometrically shrinking grids have total work proportional to the finest number of unknowns, provided coarse solvers and transfers also have linear cost. Good convergence rates still depend on smoothing and approximation properties for the actual operator.
Coarse linear solves do not have to be exact at every level
In the three-node example with fine error \(P\), suppose an approximate coarse solve returns 0.9 instead of one. The correction leaves \(0.1P\), so the restricted residual falls from 8 to 0.8. A recursive V-cycle effectively uses one approximate correction of this kind on intermediate levels; only the smallest system is usually solved directly. Measure the residual reduction per cycle across a family of grids. A roughly constant work per unknown is valuable only if the number of cycles required for a fixed reduction also remains controlled.
Predict a smoothing failure in anisotropic diffusion
For the operator \(-\alpha u_{xx}-\beta u_{yy}\) on an equal-spacing Cartesian grid, weighted point Jacobi has error multiplier
This follows by substituting a Fourier error mode into the tridiagonal second differences in each direction and dividing by the diagonal \(2(\alpha+\beta)/h^2\). Algebraic smoothness depends on the coefficients, while representability on a coarse mesh depends on geometric sampling. Under strong anisotropy a mode highly oscillatory in the weak direction can produce little residual relative to the diagonal and therefore survive point relaxation. A standard coarse interpolation space may also fail to represent it.
A line smoother solves all strongly coupled unknowns along a row together. Its block diagonal retains the horizontal second differences and the diagonal part of the vertical coupling. Modes constant along that row see no horizontal stiffness after applying the block, so the scale of their correction is set by the weaker vertical coupling rather than the large point diagonal. Alternatively, semicoarsening retains fine resolution in a direction in which troublesome oscillations must remain representable. The correct choice depends on the orientation of the anisotropy relative to the actual mesh.
Evaluate an error mode ignored by the ordinary two-grid cycle
Take a periodic grid with an even number of rows, \(\alpha=100,\ \beta=1,\ \omega=2/3\), and error \(e_{ij}=(-1)^j\), constant along each row. Its discrete horizontal curvature is zero and its vertical curvature has eigenvalue \(4/h^2\). Point Jacobi divides by \(202/h^2\), giving \(g=1-4/(303)=299/303\approx0.9868\). Ten sweeps still leave about \(0.876\) of the error amplitude. Geometrically the mode is as oscillatory as the grid permits, yet pointwise smoothing barely changes it.
Full weighting in the vertical direction uses weights \(1/4,1/2,1/4\). Applied to the alternating signs it gives zero, so the restricted residual also vanishes and an ideal coarse solve receives no information about this error. This calculation identifies a concrete failure of the usual assumption that all components missed by coarsening have already been strongly damped. A high-quality coarse linear solve cannot repair a zero coarse right-hand side.
For a horizontal line Jacobi block the horizontal part contributes zero on a row-constant vector, leaving block eigenvalue \(2/h^2\). The preconditioned error-mode eigenvalue is now \((4/h^2)/(2/h^2)=2\), and a damped line sweep has multiplier \(1-(2/3)2=-1/3\). Ten such sweeps reduce the amplitude to \(1/59049\). Each line sweep costs more than a point sweep, so the practical comparison also depends on implementation and geometry. The dramatic contrast in this mode calculation explains which coupling the extra solve is buying and why iteration counts alone are insufficient for benchmarking.
For diagonal anisotropy the identity of a strongly coupled row can change as the material rotates across the grid. A line relaxation designed only for horizontal coupling may then lose its advantage in another subdomain. Compare mode or patch tests aligned with several local principal directions before generalising the success of the horizontal example.
Change parameters · Explore the worked calculation
Change one input at a time and compare the recalculated curves with the argument above. The browser evaluates this small model locally; the accompanying numerical values state its assumptions and reference checks. Reset restores the reference inputs, and the data can be downloaded as CSV.
Chapter 12 · Adjoints and errors in a chosen output
Weight equation residuals by the response of a chosen observation and distinguish algebraic error from mesh error.
From first principles
Derive an output error from an adjoint solve
Consider a nonsingular discrete linear problem \(Au=b\) with approximate solution \(\tilde u\). A user may care about one output \(J(u)=c^\mathsf Tu\) rather than every entry of \(u\). The unknown error \(e=u-\tilde u\) satisfies \(Ae=r\) with residual \(r=b-A\tilde u\). Directly computing \(e\) would require another solve for a complete field. To weight the known residual for this output, select a vector \(z\) whose transposed action reproduces the output coefficients:
Substitution yields an exact algebraic output identity and a norm bound:
Large entries of \(z\) identify rows where a residual matters strongly to this particular observable, including possible sign cancellation between rows. A different output requires a different adjoint. The identity concerns error in solving the stated algebraic system. To estimate error relative to a continuum solution, discretization residuals and a suitable continuous or enriched adjoint must also enter.
Derivation and applications
Weight a distributed residual for one point-temperature measurement
A local output need not be equally sensitive to residuals everywhere on the domain. Consider \(-u''=f\) on \(0<x<L\) with homogeneous Dirichlet boundaries and constant unit diffusivity. Suppose a smooth reconstructed numerical field \(\tilde u\) satisfies both boundary values. Define the residual \(r=f+\tilde u''\) so that the error \(e=u-\tilde u\) obeys \(-e''=r\). Seek the error in one output \(J(u)=u(\xi)\) at an interior location \(\xi\).
Introduce a weight \(z\) that solves \(-z''=\delta(x-\xi)\) with zero end values. Away from \(\xi\) the weight is linear, and integrating the equation through the observation point determines its slope jump:
Continuity at \(\xi\) and the endpoint conditions determine both linear pieces. They give an explicit tent-shaped influence function
Multiply the error equation by \(z\) and integrate by parts on the two intervals. The exterior terms vanish and the unit slope jump isolates the requested point value:
A residual near the chosen output can have a larger effect than an equal residual near a prescribed boundary. Residuals of opposite signs can cancel for this observation without producing a globally accurate field. For piecewise linear finite-element fields, the distributional second derivative also contains jumps of the first derivative; omitting those terms would invalidate the identity.
Worked example
Calculate a local temperature error
Take \(L=1\) m and \(\xi=0.250\) m. Suppose \(r=8.00\) K/m² on \(0<x<0.250\) m and zero elsewhere. The relevant weight is \(0.750x\), so the point error is
The positive residual means the exact temperature at the observation exceeds the reconstructed value.
Second application
Move the same residual nearer the far boundary
Put the same \(8.00\) K/m² on \(0.750<x<1.00\) m instead. Now the weight is \(0.250(1-x)\), yielding \(8(0.250)(0.250)^2/2=0.0625\) K. Both residuals have identical \(L^1\) and \(L^2\) magnitude; the first affects this particular sensor three times as strongly. Moving the sensor would change the ranking without changing either residual field.
A residual has a direction
Let \(Au=b\) be an invertible linear discrete model and let \(Q(u)=c^Tu\) report a scalar output, for example a weighted mean temperature. For a computed approximation \(\tilde u\), set \(r=b-A\tilde u\). The error is \(A^{-1}r\), and hence \(Q(u)-Q(\tilde u)=c^TA^{-1}r\). Define the adjoint or dual solution by \(A^Tz=c\). Then the exact output identity is
A single adjoint gives the output effect of many possible residuals. A large residual where the observation has low sensitivity can contribute less than a small residual elsewhere. Opposite contributions can cancel in this particular output, even though they represent substantial state errors.
Compute the weight of each row
Take \(A=\left(\begin{smallmatrix}2&-1\\-1&2\end{smallmatrix}\right)\), \(b=(1,0)^T\), and observe the second unknown with \(c=(0,1)^T\). Then \(u=(2/3,1/3)^T\) and \(z=(1/3,2/3)^T\). For \(\tilde u=(0.6,0.3)^T\), the residual is \((0.1,0)^T\). Its weighted sum is \(1/30\), exactly the missing part \(1/3-0.3\). If a solve produced residual \((0,0.1)^T\) instead, the same residual norm would double the output error. This output cares twice as much about the second row as about the first.
For residual \((0.2,-0.1)^T\), the signed estimate is exactly zero. The sum of absolute contributions is \(2/15\), an upper bound insensitive to cancellation. An analyst interested only in the selected output can accept a calculation whose state vector another observer would reject. Specify the observation before choosing stopping and refinement criteria.
Move from an algebraic error to a mesh error
An accurately solved finite-element system has almost zero algebraic residual in its own discrete test space. It can still differ from the continuum solution. Let \(a(u,v)=\ell(v)\) be the continuum weak equation and define \(R(v)=\ell(v)-a(u_h,v)\). For a linear observation the continuum dual satisfies \(a(v,z)=Q(v)\), giving \(Q(u)-Q(u_h)=R(z)\). Galerkin orthogonality means \(R(z_h)=0\) for every test function on the same mesh, hence \(R(z)=R(z-z_h)\).
Estimating this term requires a dual approximation richer than the test space used for the primal solve, or an independent reconstruction. Integrating element residuals by parts can expose both cell defects and jumps in normal flux. Weight these local contributions by the unresolved dual variation to discover which regions can affect the output strongly. Check an estimated correction against actual output changes on a refined mesh; a poor dual approximation can misidentify important regions even when the primal residuals have been evaluated exactly.
Compare a point observation with an average
In the two-unknown example, replace the second-node observation by the mean \(c=(1/2,1/2)^T\). The constant vector is an eigenvector of \(A\) with eigenvalue one, so the adjoint becomes \(z=c\). A purely antisymmetric residual \((0.1,-0.1)^T\) makes the mean output error zero. For the earlier second-node output the same residual gives \(-1/30\). A mesh designed to resolve an average can therefore allocate effort differently from one designed for a single sensor. Whenever a reported error changes markedly between observables, inspect the dual weights before attributing the change to a flaw in the physical simulation.
Turn primal and dual approximation errors into an output bound
For a symmetric coercive bilinear form \(a\), let the exact state \(u\) satisfy \(a(u,v)=\ell(v)\), and the exact dual \(z\) satisfy \(a(v,z)=Q(v)\) for a linear output \(Q\). With conforming Galerkin approximations on the same trial space, \(a(u-u_h,v_h)=0\) for every discrete test. Consequently \(Q(u)-Q(u_h)=a(u-u_h,z-z_h)\). Cauchy–Schwarz in the energy inner product gives an absolute bound by \(\|u-u_h\|_a\|z-z_h\|_a\). Accuracy of either the state or the observation sensitivity can separately make the output error small.
When the primal and dual energy errors both decrease proportionally to \(h\), their product guarantees an \(O(h^2)\) output error under these assumptions. It does not guarantee second order for every possible observation. A point evaluation in a higher-dimensional continuum problem may be unbounded on the energy space or yield a dual solution with a strong singularity. Then the dual error may converge much more slowly. Likewise nonconforming approximation, inexact integration or inconsistent boundary terms introduce additional residual terms that are absent from the simple Galerkin cancellation.
A case where the product bound is exact
Let \(a(v,w)=v^TAw\) with \(A=\operatorname{diag}(2,8)\), exact state \(u=(1,2)^T\), and reduced approximation space spanned by \(s=(1,1)^T\). The Galerkin coefficient is
Choose output \(Q(v)=(6,8)v\); its exact dual is \(z=(3,1)^T\) since \(Az=(6,8)^T\). Projecting that dual onto the same space gives coefficient \((6+8)/10=1.4\). The primal and dual errors are therefore \((-0.8,0.2)^T\) and \((1.6,-0.4)^T\).
Their energy inner product is
Direct evaluation gives \(Q(u)=22\) and \(Q(u_h)=25.2\), confirming the signed error exactly. Squared energy errors are
Their square-root product is 3.2, attaining the absolute bound because the two error vectors are antiparallel. The bound cannot determine the sign; the signed dual residual can.
Replace the observation by \(Q_2(v)=(2,8)v\). Its exact dual is \(s\), already representable, so \(z-z_h=0\) and the output error vanishes even though the state error is unchanged. Indeed \(Q_2(u)=18=Q_2(u_h)\). A mesh judged solely by that particular observable could look exact. A different sensor weighing the same simulation states produces a demonstrably nonzero output error, which is why adaptive refinement objectives should name their actual observations.
If the approximate dual used the same one-dimensional space and one simply evaluated the primal residual on it, the reported correction would be exactly zero for either output. The first observation shows that such a number can be badly misleading. An enriched dual must include a direction outside the primal test space; in this two-coordinate example, adding either coordinate direction gives the full space and recovers the signed error exactly. On a fine physical mesh full enrichment may be too expensive, making local higher-order reconstruction or an independently refined dual mesh attractive. The product bound then clarifies which additional error in the dual approximation needs to be controlled.
It also identifies the observation for which refining the primal mesh alone is unnecessary.
Bound the uncertainty of an approximate dual correction
A practical enriched dual \(\tilde z\) may itself have numerical error. In the symmetric positive definite algebraic setting the difference between true output error and its estimated correction is \((z-\tilde z)^Tr\), where \(r=b-Au_h\). With dual residual \(r_z=c-A\tilde z\), this equals \(r_z^TA^{-1}r\). Cauchy–Schwarz bounds its magnitude by \(\|r_z\|_{A^{-1}}\|r\|_{A^{-1}}\). This identity explains why a small ordinary residual norm can be insufficient for either the primal or dual solve: directions associated with small eigenvalues receive greater weight in the inverse-energy norm.
In the preceding example choose \(\tilde z=(2.5,1)^T\). The primal residual is \((-1.6,1.6)^T\); the approximate correction is therefore \(-4+1.6=-2.4\), moving the coarse output 25.2 to 22.8. The actual output is 22, leaving error −0.8 after correction. The dual residual is \((1,0)^T\), with squared inverse-energy norm \(1/2\). The squared primal residual norm in the same metric is 1.6. Their product of norms is \(\sqrt{0.8}\approx0.8944\), containing the observed remaining discrepancy. For larger problems, estimating these norms can itself require a separate bound or preconditioner. Reporting only the corrected value without assessing the accuracy of the dual can make a visually improved output appear more certain than the calculation warrants.
Which source errors matter to a point measurement?
For \(-u''=f\) with zero values at both ends of the unit interval, seek the sensitivity of \(u(a)\) to a point load. The adjoint is piecewise linear, vanishes at the endpoints, is continuous at \(a\) and has derivative jump minus one.

Read values from the plot
| Source location | Sensor at 0.25 | Sensor at 0.5 | Sensor at 0.8 |
|---|---|---|---|
| 0 | 0 | 0 | 0 |
| 0.25 | 0.1875 | 0.125 | 0.05 |
| 0.5 | 0.125 | 0.25 | 0.1 |
| 0.75 | 0.0625 | 0.125 | 0.15 |
| 1 | 0 | 0 | 0 |
Change parameters · Which source errors matter to a point measurement?
Change one input at a time and compare the recalculated curves with the argument above. The browser evaluates this small model locally; the accompanying numerical values state its assumptions and reference checks. Reset restores the reference inputs, and the data can be downloaded as CSV.
Problem sheet 6 · Transfers and observation error
Track which error can survive a grid transfer and compute an exact adjoint correction for a nonsymmetric system.
A smooth mode survives smoothing
Weighted Jacobi for a Dirichlet Laplacian uses \(\omega=2/3\). Compute the multiplier at grid angles \(\pi/3\) and \(2\pi/3\), and the error left by two sweeps. Explain how this affects the choice of a coarse-grid space.
Worked solution
For \(\pi/3\) the multiplier is \(1-(2/3)(1-1/2)=2/3\), leaving \(4/9\) after two sweeps. At \(2\pi/3\) it is \(1-(2/3)(1+1/2)=0\), so the error vanishes in one sweep.
Smoother errors can persist while oscillatory components decay. A coarse interpolation space should approximate those persistent smooth components. A coarse solve alone cannot remove arbitrary fine-grid error.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Test exact coarse correction
Use \(A=\left(\begin{smallmatrix}2&-1\\-1&2\end{smallmatrix}\right)\), \(P=(1,1)^T\), \(R=P^T/2\). Find the coarse operator and the coarse correction for true error \((3,1)^T\). Verify the restricted residual afterward.
Worked solution
\(AP=(1,1)^T\) and \(RAP=1\). The initial residual is
Its restriction is 2, giving coarse correction \(P\,2=(2,2)^T\).
The remaining error is \((1,-1)^T\), with residual \((3,-3)^T\). Restricting gives zero even though the fine error remains. An exact coarse solve eliminated only the represented component.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Use the transpose
Let \(A=\left(\begin{smallmatrix}2&1\\0&3\end{smallmatrix}\right)\), \(c=(1,0)^T\), and suppose a computed state's residual is
Compute the observation error with an adjoint, verify it by solving \(Ae=r\), and explain the sign.
Worked solution
Solving \(A^Tz=c\) gives \(2z_1=1,\ z_1+3z_2=0\), so \(z=(1/2,-1/6)^T\). Its dot product with \(r\) is −0.05.
The error equation gives \(e_2=0.1,\ 2e_1+0.1=0\), hence
A positive second-row defect forces a negative first-component change through the positive off-diagonal coupling. Using \(A\) instead of its transpose for the dual would miss that effect.
Explore the related calculation with adjustable inputs. Inspect the Taylor remainder with the correct and wrong-sign adjoint. The explorer uses a two-state equilibrium; apply the stated scalar or nonsymmetric operator to obtain this exercise’s exact gradient.
Decide if another grid refinement answers the engineering question
A steady diffusion solver predicts a dimensionless mean sensor value of 0.42800, 0.42200 and 0.42050 on meshes with 16, 32 and 64 cells per side. The linear solver reports relative residuals below 10⁻¹⁰. Estimate the converged value and the error on the finest grid. A measurement reads 0.4170 with uncertainty ±0.0010. Can the discrepancy be attributed to mesh error alone?
Worked solution
Assume the same smooth solution, geometry, sensor integration and refinement ratio on all three grids. The ratio of successive differences is 0.0060/0.0015 = 4.0, giving observed order p = 2. Extrapolate the fine estimate by adding (0.42050−0.42200)/(2²−1) = −0.00050. The resulting estimate is 0.42000.
The fine-grid spatial error magnitude is therefore about 0.00050. A relative algebraic residual near 10⁻¹⁰ describes the discrete equations and is in different units from the absolute sensor error. It cannot replace this grid calculation. Repeating the study with a local peak instead of a mean can give a different observed order.
The measurement interval spans 0.4160 to 0.4180. Even the extrapolated prediction exceeds its upper end by 0.0020. Under the assumed error model mesh refinement alone appears too small to explain that gap. Test coefficient uncertainty, boundary data and sensor averaging separately. The numerical experiment in chapter 6 supplies a known exact field for checking the discretisation independently of the physical measurement.
Explore the related calculation with adjustable inputs. Refine the grid on a known solution and keep the small linear-solver residual separate from the spatial field error.
Chapter 13 · Pure flux boundaries, compatibility and the missing constant
If a steady diffusion equation prescribes only fluxes, a solver can return a singular-matrix warning for two different physical reasons. Derive the mass balance and the nullspace separately, then decide when choosing a reference value resolves the problem.
Test the continuum equation with a constant
On \(0<x<1\) take a unit conductivity, positive rightward flux \(q=-u'\), and a steady source f with \(q'=f\). Prescribe the rightward flux at both endpoints as \(q_L,q_R\). Integrating the divergence equation gives
The outward unit normal is negative at the left endpoint, so the net outward flow is \(q_R-q_L\), even when both recorded sensor values are positive. In several dimensions the same requirement follows by integrating the divergence and applying the divergence theorem.
Testing the weak equation with \(v=1\) makes its left side identically zero. This recovers the flux balance without differentiating an approximate field. For every compatible right-hand side, adding any constant to u leaves its gradient and both prescribed fluxes unchanged. The magnitude of a potential is undetermined, while potential differences and flux can be well defined. Each disconnected region with pure-flux boundaries has its own compatibility equation and arbitrary constant.
Background · Compatibility condition
For minus the Laplacian of u equal to f with pure Neumann data, this integral condition is required. A constant still has to be fixed separately.
Separate the left nullspace test from the gauge condition
Take cell-centred finite volumes with equal width h and face flux \(q_{i+1/2}=-(u_{i+1}-u_i)/h\). The balance of each cell is \(q_{i+1/2}-q_{i-1/2}=h f_i\), with prescribed values replacing the two exterior faces. Add all rows. Interior face contributions cancel in equal and opposite pairs. The resulting symmetric matrix A has a constant right null vector and its range is orthogonal to that vector. Let b be the integrated loads including boundary terms and \(w_i=h\) the integration weights. A mean value \(\bar u\) on this unit interval can be imposed by the augmented system
For compatible data \(\lambda=0\). For incompatible data the first block solves for a deliberately modified source \(f_i-\lambda\). Choosing a mean makes the augmented system solvable either way; checking the multiplier identifies what it solved. Pinning a node and silently dropping one conservation equation can conceal the same mismatch as an artificial reaction at the pin.
Predict four cell values and audit an inconsistent measurement
Set \(f=2,\ q_L=0,\ q_R=2\). Exact integration gives
For a continuous mean of zero \(C=1/3\). With four equal cells the centre coordinates are 1/8, 3/8, 5/8 and 7/8. The centroid samples of \(-x^2\) have mean −0.328125, so the discrete mean-zero solution is \(0.3125,0.1875,-0.0625,-0.4375\). Adjacent differences give interior face fluxes 0.5, 1.0 and 1.5. The difference between the discrete centre values and the continuous mean-zero samples is the constant \(-h^2/12\); every interior face gradient is exact.
Now change only the recorded right flux to 2.4. The original source supplies 2 units per unit time and the boundaries demand 2.4. Thus \(\lambda=-0.40\) and the augmented system supplies an effective uniform source of 2.4. Alternatively, keeping the original source and the left measurement forces a right flux of 2. The plot shows both reconstructions and tells which data were modified. Adjusting only the mean translates either field without changing its slope. In a transient storage model, imbalance would change the mean in time instead of permitting a steady solution.
Set a nonzero flux mismatch, then vary the mean and the cell count independently. Observe which differences can be removed by a vertical translation. Check that the integrated imbalance remains the same under refinement.
Tutorial · locate the bias and choose a comparison observable
A unit-length domain receives \(f(x)=1+2x\). A left sensor reports rightward flux 0.3 and a right sensor reports 2.1. Compute the integrated residual. If both flux sensors are trusted, find the constant source adjustment implied by the augmented system. If only the source and left sensor are trusted, predict the right measurement. What quantity can two solvers compare without agreeing on a gauge?
Show the diagnostic
The source integral is 2 and net outflow is
Their difference is +0.2. The multiplier is +0.2, so the adjusted source would be \(0.8+2x\). Keeping the original source instead predicts
Differences \(u(x_b)-u(x_a)\), gradients and fluxes are gauge independent. A single imbalance equation cannot tell which instrument is wrong. Independent source or flux measurements are needed to choose between these reconstructions.
Further reading · FEniCS Project · Poisson equation with pure Neumann boundary conditions and a mean-value multiplier
Study the full derivation
A Fourier Poisson solver and the trouble caused by unresolved products · Spatial discretisation and field equations
In a periodic medium the constant part of a source decides whether a Poisson problem has any solution. Derive the Fourier solver, separate spectral and finite-difference symbols, and see how a nonlinear product can inject a false low-frequency source.
Chapter 14 · Building a local residual estimator and refining where it matters
A finite-element solution can satisfy the assembled equations to machine precision while still missing curvature between nodes. Integrate the residual of the computed field by parts on each element and use the resulting cell and interface terms to decide where to spend the next degrees of freedom.
Ask what the discrete solution does to an unresolved test function
Consider \(-u''=f\) on a unit interval with zero Dirichlet data. Use continuous piecewise-linear finite elements with exact integration on a possibly nonuniform mesh. The weak solution satisfies \(a(u,v)=\int u'v'=\int fv\) for every test function vanishing at the endpoints. For \(e=u-u_h\), subtract the computed field to obtain
The algebraic system makes \(R(v_h)=0\) for all functions in the chosen finite-element space. Tests with more local structure expose what is missing.
The sign follows by adding the right boundary term of the left cell and the left boundary term of the right cell. On a linear cell \(u_h''=0\) classically. Its piecewise constant gradient jumps at interior nodes. In diffusion with varying coefficient k the corresponding jump is in \(k u_h'\), since continuity of normal flux is the conservation condition. A discontinuous material coefficient can cause an exact gradient jump without any flux imbalance.
Scale the cell and node terms before marking
Subtract the finite-element interpolant or a local quasi-interpolant from v inside the residual. Galerkin orthogonality permits this subtraction and bounds the remaining test magnitude by local length times its gradient. This leads to a computable residual indicator. One common one-dimensional choice with a symmetric edge length \(h_i\) equal here to the smaller neighbouring cell is
Sharing the node contribution prevents double counting. Under the usual mesh and coefficient assumptions such estimates bound the energy error up to constants; their absolute numbers need not equal the measured error. Data oscillation can matter if the source is approximated or oscillates within a cell. To mark by bulk contribution, sort \(\eta_K^2\) in descending order and take cells until their sum exceeds a chosen fraction of the global squared estimator. Bisect marked cells, transfer the coefficient data, assemble and solve again. Reusing the old gradient jumps after refinement would skip the effect of the new trial space.
Work through the first two-element decision
Let \(f=1\) on the left half and \(f=9\) on the right. With two equal cells and zero end values there is a single interior hat unknown. Diagonal stiffness is 4 and the integrated hat load is
The middle value is therefore 0.625. The slopes are 1.25 and −1.25, giving \(J=-2.5\). Since \(h=0.5\), the two cell terms are 0.125 and 10.125. Each side receives \((1/2)(0.5)(2.5)^2=1.5625\) from the node. The right cell contributes \(11.6875/(1.6875+11.6875)=87.38\%\) of the squared indicator. A 50% bulk mark selects only that cell.
For this particular problem the finite-element solution equals the piecewise-linear interpolant of the true nodal values. This follows by testing the derivative of the interpolation error against a constant basis gradient on each element. For constant f on each element the derivative error is therefore a line of slope −f with zero mean. Its exact squared energy norm is \(\sum f_K^2 h_K^3/12\). Splitting the right half into two equal cells reduces that half's contribution by a factor of four. Total energy error falls from 0.924 to 0.470 with one extra degree of freedom. Splitting only the left cell leaves about 0.920. Run the loop and compare the indicator's ranking with this independent verification quantity.
Run the mesh from zero to three refinement rounds with a 50% bulk mark. Record error against free values. Repeat with a 90% mark and compare equal computational costs where available. Which choice targets the source localization most strongly?
Tutorial · predict the benefit of two candidate splits
Consider a left cell of length 0.50 with \(f=1\) and a right cell of length 0.125 with \(f=9\). Which single split would remove more exact squared energy error? Show how stiffness residual and source localization answer distinct questions.
Show the local comparison
Bisection removes three quarters of that cell's \(f^2h^3/12\). Before division by 12 the left weight is \(1(0.5)^3=0.125\); the right weight is
Refining the small right cell still yields about 27% more improvement. Conversely the assembled nodal residual could already be zero on either mesh after a direct solve. Reducing the algebraic tolerance further would improve neither piecewise-linear profile. This calculation is a verification benchmark made possible by the manufactured piecewise-constant data.
Further reading · Joachim Schöberl, Interactive Finite Elements · a posteriori error estimation by residuals
Study the full derivation
Bound diffusion error by balancing a reconstructed flux · Spatial discretisation and field equations
A temperature field from a finite-element calculation looks smooth. Reconstruct a heat flux which exactly balances the source, then derive an upper bound for the true energy error without knowing the exact temperature.
Chapter 15 · What a periodic grid does to a decaying Fourier mode
A periodic diffusion solver predicts the shape of a sampled wave while its amplitude decays too slowly. Fourier analysis separates spatial differentiation error, an unresolved physical mode and errors caused by the time integrator.
Diagonalise the differential operator on the periodic interval
Use a dimensionless coordinate \(0\le x<2\pi\) and solve \(u_t=\kappa u_{xx}\) with periodic values and periodic derivatives. The complex exponentials \(e^{imx}\), with integer m, satisfy both conditions and are eigenfunctions of the second derivative. Put \(u(x,t)=A_m(t)e^{imx}\) and cancel the common exponential. The scalar amplitude equation is
Thus every cosine or sine mode decays by \(\exp(-\kappa m^2t)\), with no phase shift, while the m=0 mean is conserved.
On a uniform grid \(x_j=2\pi j/N\), the samples of \(m\) and \(m+\ell N\) agree for every integer \(\ell\). A discrete Fourier transform returns coefficients in one representative band. For the real cosine test with even N we can fold a positive physical mode into \(k=\min(r,N-r)\), \(r=m\bmod N\). A Fourier spectral Laplacian multiplies that coefficient by \(-k^2\). For a resolved mode it differentiates the trigonometric interpolant exactly, up to arithmetic. For unresolved data it differentiates the aliased representative; no operation using only those samples can identify the original m.
Apply the centred difference stencil to a single wave
The standard second difference is \((u_{j+1}-2u_j+u_{j-1})/h^2\), \(h=2\pi/N\). Put the grid wave \(u_j=e^{ikjh}\) into the stencil. Factor out the common phase and simplify with \(e^{i\xi}+e^{-i\xi}=2\cos\xi\). This gives the symbol and its small-h expansion:
The effective squared wavenumber is smaller than \(k^2\) for every nonconstant mode in the resolved band, so this spatial approximation decays too slowly if the time equation is integrated exactly. The error is modest when \(kh\ll1\), but at the Nyquist mode \(kh=\pi\) the ratio is
A stable time integrator cannot repair this spatial attenuation error without additional modeling. The experiment exponentiates both discretizations' symbols exactly, isolating space and sampling here.
Measure separate errors with the same sampled initial data
Choose \(\kappa=0.5,\ m=3,\ N=16\). The true squared wavenumber is 9 and the difference stencil gives 8.006. Starting at unit amplitude, at \(t=0.20\) exact and spectral amplitudes are 0.40657; finite differences give 0.44906. Doubling N to 32 changes the difference result to 0.41716. The absolute amplitude error falls from 0.04249 to 0.01059, a ratio of 4.01 consistent with the second-order expansion. This is a spatial-convergence study because time evolution introduces no truncation error.
Now take \(m=12,\ N=16\). Every sampled cosine equals the low mode \(k=4\) at \(t=0\). At \(t=0.02\), the continuum amplitude for the true physical mode is \(e^{-1.44}=0.237\), whereas the spectral grid predicts
A spectral computation can therefore agree exactly with its trigonometric interpolant and disagree strongly with the evolution of the intended signal. Sampling on a finer grid or obtaining prior bandwidth information resolves that ambiguity. The mean mode is particularly revealing when a nonconstant physical cosine aliases to a constant.
Start at mode 3 and successively double N from 8 to 32. Compute two amplitude-error ratios at the same time. Then use mode 12 on 16 points to observe an alias, and increase N until the Fourier grid represents the intended mode.
Tutorial · resolve a damping rate to a target tolerance
For a mode well inside the grid bandwidth, estimate the number of samples per wavelength needed for a relative error below 1% in the decay rate with centred differences. Test the estimate for \(m=2\). How could the time integrator contaminate a measurement of this spatial error?
Show the resolution estimate
Writing p for samples per wavelength gives
The relative rate error is approximately \((kh)^2/12\). Requiring at most 0.01 gives \(p\gtrsim18.14\); try 19 samples per wavelength, or \(N=38\) for \(m=2\). The exact ratio \([\sin(\pi/19)/(\pi/19)]^2\) is about 0.991. A forward-Euler step would replace exponential propagation by \(1-\kappa k_{\rm eff}^2\Delta t\). Its repeated-step error could partly mask the underdamping of the spatial stencil. Compare with the exponential of the discrete symbol before attributing a measured rate to space alone.
Further reading · Lloyd N. Trefethen, Spectral Methods in MATLAB · periodic grids, Fourier differentiation and downloadable programs
Check the discrete eigenvalue with OneSimulation
A spatial sine also diagonalises the five-point Dirichlet Laplacian on a square. Use the same modified wave-number argument in both coordinate directions. Run python poisson-mode.py --mode 2 --cells 8 16 32 and compare the observed nodal error with the discrete eigenvalue prediction in the CSV. This is a steady forced problem whose spatial operator can be checked independently of any time integrator. Download the OneSimulation verification model.
Study the full derivation
A Fourier Poisson solver and the trouble caused by unresolved products · Spatial discretisation and field equations
In a periodic medium the constant part of a source decides whether a Poisson problem has any solution. Derive the Fourier solver, separate spectral and finite-difference symbols, and see how a nonlinear product can inject a false low-frequency source.
Chapter 16 · Why two finite-element wave solvers propagate the same mode at different speeds
Build the element mass matrix by integrating shape functions and track the effect of diagonal lumping on the wave spectrum.
From a continuum wave to nodal masses
For \(u_{tt}=c^2u_{xx}\), multiply by a test function and integrate by parts. On a periodic line the boundary contributions cancel. A piecewise-linear element of width \(h\) uses shape functions \(1-\xi,\xi\), with \(\xi\in[0,1]\). Integrating products of shape functions gives
Integrating derivative products gives
Row-sum lumping replaces each mass row by its sum on the corresponding diagonal, \(h/2\). This preserves the mass associated with a uniform velocity but changes the response to a velocity that varies within an element.
Background · Numerical dispersion
A discretised wave can retain its amplitude and still propagate at the wrong speed. Compare phase and group errors over the actual resolved wavelengths.
Diagonalise the assembled periodic problem
A periodic nodal mode has \(u_j=e^{ij\theta}\). Each neighbour contributes \(e^{\pm i\theta}\) relative to node \(j\). Thus \(K\) multiplies by \(2c^2(1-\cos\theta)/h\), consistent \(M\) by \(h(2+\cos\theta)/3\), and lumped \(M\) by \(h\). Dividing stiffness by mass gives the discrete squared frequency. Relative to the exact frequency \(c\theta/h\),
Both tend to one for long waves; the leading quadratic errors have opposite signs. This is a spatial effect, present even with exact time integration.
Two wavelengths in one mesh
At four cells per wavelength \(\theta=\pi/2\). The lumped ratio is \(2\sqrt2/\pi\approx0.9003\); the consistent ratio is about 1.1027. One wave solver lags by roughly ten per cent and the other leads by roughly ten per cent. At eight cells per wavelength the ratios move much closer to one, but repeated propagation over many wavelengths can still accumulate visible phase error.
At the shortest grid mode \(\theta=\pi\), the consistent frequency is \(\sqrt{12}c/h\) and the lumped frequency \(2c/h\). A central-difference time integrator stable for \(h_t\omega\le2\) therefore requires a smaller step for the consistent mass. Accuracy at one wavelength and stability at the grid scale are different design criteria.
Tutorial on interpreting a convergence test
Which mass gives the exact kinetic energy for a linear velocity varying from \(v\) to \(-v\) on one element?
Worked solution
The continuum energy with unit density is \(hv^2/6\). The consistent matrix reproduces it by exact integration. The lumped kinetic energy is \(hv^2/2\), because it assigns both end masses the full endpoint speed.
How would you isolate spatial dispersion from time stepping in a measurement of a cavity eigenfrequency?
Worked solution
Solve the generalised eigenproblem \(Kq=\omega^2Mq\) directly for increasingly fine meshes or converge time steps on each fixed mesh. Then compare with the continuum frequency and report both \(h\) and the time tolerance.
Chapter 17 · Moving a cell average without inventing or losing material
Derive a conservative transport step from cell overlap and measure how a monotone scheme spreads a pulse despite conserving its total mass exactly.
Transport is a translation
For constant \(a>0\), the solution to \(u_t+au_x=0\) is \(u(x,t)=u_0(x-at)\). Consider periodic cells of width \(h\). Over one step \(\Delta t\), a cell translated back through distance \(a\Delta t\) overlaps part of its original cell and part of its left neighbour. If the initial reconstruction is constant in each cell and \(C=a\Delta t/h\) lies between zero and one, the new average is
Summing all cells telescopes on a periodic grid, preserving total material \(h\sum_j u_j\). Each new value is a convex combination, so the maximum cannot increase and the minimum cannot fall. For \(C>1\) this particular two-cell overlap ceases to describe the translated interval.
Derive the spreading instead of reading it off a plot
Start from one unit of material in one cell and follow its distribution on an effectively unbounded grid. After one step its index increment behaves like a Bernoulli choice: zero with weight \(1-C\), one with weight \(C\). Repeated convolution gives a binomial profile. Its mean index after \(n\) steps is \(nC\) and variance \(nC(1-C)\). Multiplying by \(h^2\) and using \(n=t/\Delta t\) gives a physical variance \(a h(1-C)t\). Equating this with \(2D_\mathrm{num}t\) gives
This growth describes numerical spreading of a translated shape even though the scheme conserves mass.
Two ways to reach the same physical time
A pulse should move 12 cells. Taking 12 steps with \(C=1\) shifts data by exactly 12 indices. Taking 24 steps with \(C=0.5\) has the same mean displacement but an added variance of six cell widths squared. In a source-free transport test, peak height and width reveal an error hidden from the total-mass budget.
The experiment starts with one full cell on a ring of 80 cells. Up to 40 steps avoid wraparound across the displayed pulse for the chosen starting index. The blackboard binomial calculation predicts centroid and spread independently of the plotted recurrence.
Tutorial on interpreting artificial diffusion
If \(C=0.25\) and the pulse has moved ten cells on average, what is its added variance?
Worked solution
Mean travel requires \(n=40\) steps. Variance in cell units is \(40(0.25)(0.75)=7.5\). Multiplying by \(h^2\) gives the physical variance.
Is a larger time step always the cure for pulse spreading?
Worked solution
For constant transport on this uniform grid \(C=1\) happens to align the translation with cell boundaries. Multiple speeds, nonuniform meshes and source physics generally preclude such alignment everywhere. A higher-order bounded reconstruction can reduce spreading while preserving conservation.
Read the university treatment
Use the advection examples to compare convergence in a norm with conservation of an integral and propagation of an extremum. Randall LeVeque · Finite Difference Methods for Ordinary and Partial Differential Equations
Chapter 18 · When diffusion destabilises a uniform state
Two scalar signals on a ring respond locally to each other and exchange signal with their neighbours. A single well-mixed cell returns to its reference state after a small disturbance. Can coupled cells amplify a spatial pattern? Derive a condition for this surprising outcome and test how faithfully a finite grid represents its wavelength.
Begin with a stable, spatially uniform experiment
Let \(u\) and \(v\) be small dimensionless departures from a reference operating point. They represent signed deviations, so their components can be negative without implying a negative absolute material quantity. Choose local time evolution \(u_t=u+v,\ v_t=-3u-2v\). A positive \(u\) tends to increase itself immediately; the second channel subsequently feeds back on the first. To determine whether a perturbation persists one must examine both channels together. Looking only at the positive diagonal coefficient in the first equation would give a wrong stability conclusion.
Write the state as a column and call the coefficient matrix \(J\). The characteristic polynomial of a two-by-two matrix is \(\mu^2-\mathrm{tr}(J)\mu+\det J\). Here the trace is minus one and the determinant is one. The two roots are \((-1\pm i\sqrt3)/2\). An isolated cell therefore has damped oscillatory motion for every initial perturbation; no normal mode has a positive growth rate. Some observables can still grow transiently in mixtures of modes. The present experiment asks about exponential growth of a mode over time.
Allow spatial exchange by adding \(D_u u_{xx}\) and \(D_v v_{xx}\) on a periodic ring of dimensionless circumference \(L\). Both diffusion coefficients are positive. Without coupling each field's Fourier component would decay at a rate proportional to the square of its wavenumber. The system changes qualitatively when the two diffusion rates differ because the path that restores local stability involves both fields. A spatially varying signal in one channel can be smoothed before it delivers the same feedback as in a spatially uniform experiment.
Reduce the field equation to one matrix per wavelength
Periodicity imposes \(k_m=2\pi m/L\) for integer \(m\). Write a normal mode as \(w\exp(ik_m x+\mu t)\). Differentiating the spatial factor twice gives \(-k_m^2\). Define \(q=k_m^2\). Substitution shows that \(\mu\) must be an eigenvalue of \(J-qD\), where \(D\) is diagonal with entries \(D_u,D_v\). Distinct modes do not interact in this spatially homogeneous linear model. One may analyse each mode separately and superpose the results.
The trace \(\tau\) is negative for every \(q\ge0\). Complex conjugate roots therefore have negative real parts. A positive eigenvalue must be real and accompanied by a negative one, so the determinant must be negative. Conversely, negative determinant ensures real eigenvalues of opposite signs. The instability question has become a test of the sign of a quadratic function on nonnegative arguments. Both at zero and at arbitrarily large \(q\) the determinant is positive. If a growing mode exists, it must occupy an intermediate range.
Put \(b=D_v-2D_u\) and \(c=D_uD_v\). The minimum occurs at \(q=b/(2c)\), which is positive only if \(b>0\). Its value is \(1-b^2/(4c)\). Thus the continuous dispersion curve contains an open interval of growing wavenumbers if \(b>0\) and \(b^2>4c\). At equality one neutral wavenumber appears; a neutral mode neither grows nor establishes instability. The physically allowed mode numbers of the finite ring must still place some squared wavenumber inside the interval. A condition derived for a continuum of wavelengths alone can overpredict what fits in a short apparatus.
Calculate the unstable band before running a simulation
Choose \(D_u=0.02,D_v=1\). Then
The two roots of the determinant are about 1.065 and 46.93. On a ring of circumference \(2\pi\), \(k_m=m\), so the continuum equation amplifies modes two through six. The uniform mode still decays. Mode one has \(q=1\), just below the lower edge, while mode seven has \(q=49\), just above the upper edge. Both are valuable tests because a moderate numerical error in the dispersion relation could reverse their classification.
The largest real part of the two eigenvalues is \(\operatorname{Re}[\tau+\sqrt{\tau^2-4\delta}]/2\). Choose the square root with nonnegative real part. Where the discriminant is negative the real part of the square root is zero; treating a negative discriminant as an error and dropping those wavenumbers would omit damped oscillatory physics. At \(q=4\), the determinant is \(-2.52\) and the trace is \(-5.08\). The positive rate is approximately 0.4553. During one dimensionless time unit an initially pure growing eigenmode at that wavenumber is multiplied by about 1.58.
Derive what a particular spatial difference sees
Now discretise the ring with \(N\) equally spaced points of spacing \(h=L/N\). The centred second difference of a discrete Fourier mode multiplies it by \((e^{ikh}-2+e^{-ikh})/h^2\). Using the cosine half-angle identity gives a real, nonpositive factor. Compare it with the exact factor \(-k^2\). They agree to leading order at small \(kh\) but separate substantially near the grid scale.
For each sampled mode the finite grid uses \(J-q_hD\). The same algebraic determinant test applies, with a different argument. On the 32-point default grid, mode seven has \(q_h\) about 41.8 rather than 49. Its grid growth rate is positive even though its continuum rate is negative. This discrepancy survives any refinement of the time integrator on that fixed grid. The early growth has a reproducible numerical explanation and can be diagnosed without waiting for a long transient simulation.
Open full-size diagramA meaningful refinement experiment must follow a fixed physical mode as \(N\) increases. Following the highest mode of each grid instead changes its physical wavelength. Similarly, changing circumference while keeping the mode number fixed changes the wavelength and therefore the physical growth rate. The notebook exposes both controls so the two experiments can be distinguished. Large-scale modes can appear converged while the classification at the upper band edge remains sensitive to cell count.
Relate an eigenvalue to a picture of a pattern
Construct a numerical experiment in which the expected time dependence is actually known. For each of several low spatial modes, use the leading eigenvector of the two-channel finite-grid matrix and multiply by a small, controlled initial amplitude. Evolve its coefficient by its complex exponential, then take real parts to obtain real sensor signals. The resulting trace has no time-stepping error. An independently assembled full block matrix, including the periodic connection between the first and last cells, supplies another way to recover the largest growth rate. The optional OneSimulation eigensolver applies to this complete matrix directly.
A visible crest in a total field is not a single Fourier coefficient. It can move or change height through interference even when each included mode is decaying. To measure a rate compare the amplitude of one spatial Fourier component at two times. If the initial field contains both eigenvectors at that same wavenumber, the coefficient may not yet show one pure exponential. Preparing a known eigenvector or observing later, while the state remains within the linear range, makes the inference interpretable.
There is also an upper limit to what this calculation predicts. A linear mode with positive rate grows exponentially without saturation. Once its amplitude is comparable to the scale used to linearise the original response, nonlinear terms could shift the wavelength selection, mix modes or produce a bounded state. The notebook chooses small initial amplitudes and finite observation times precisely to isolate onset. It cannot infer the final pattern simply by extending the linear growth curve indefinitely.
Set a resolution requirement from the measured quantity
Near the upper band edge the question can be posed in terms of a tolerance on \(q\). A finite-grid prediction of a positive rate changes sign precisely when its effective \(q_h\) crosses the edge. If the target mode has \(q\) barely above that edge, estimate whether the leading truncation bias \(h^2q^2/12\) exceeds the distance to it. This supplies an inexpensive grid-design calculation before allocating a time integrator. Because the expansion assumes \(kh\) is small, verify the final decision with the exact sine symbol.
Away from an edge the sign can already be reliable while the predicted doubling time is inaccurate. A positive growth rate corresponds to a doubling time of \(\ln2/\mu\); relative errors are strongly amplified near neutral stability if measured against a very small rate. Record both the sign and an absolute uncertainty on the rate when comparing computations near onset. A single label such as stable or unstable does not communicate that sensitivity.
Tutorial on modes and finite domains
1. Give a short proof that equal positive diffusion coefficients cannot create an instability in this model.
Work through the solution
If \(D_u=D_v=d\), the spatial block is \(J-dqI\). Its eigenvectors remain those of the stable local system, and every eigenvalue shifts left by \(dq\). All real parts are at most minus one half. This argument works for any locally stable constant matrix with identical scalar diffusion in every channel.
2. Keep the two default diffusion coefficients but change the ring circumference to \(\pi\). Which positive continuum mode numbers grow?
Work through the solution
The allowed wavenumbers are \(k_m=2m\). The inequality becomes \(1.065<4m^2<46.93\). It admits \(m=1,2,3\), corresponding to wavenumbers 2, 4 and 6. Comparing mode numbers alone between the two rings would hide this wavelength correspondence.
3. A Fourier amplitude rises from \(2\cdot10^{-4}\) to \(8\cdot10^{-4}\) in four time units. Estimate the growth rate and describe an additional measurement needed before identifying a physical instability.
Work through the solution
A pure mode gives \(\mu=\log(4)/4\simeq0.3466\) per time unit. Confirm that the same physical wavenumber grows on refined grids and that its rate approaches the continuum dispersion calculation. A positive finite-grid rate by itself cannot distinguish a real band from the extra mode admitted by a coarse Laplacian.
Further reading · Duke University, linear stability analysis of two coupled reaction–diffusion equations
Change parameters · When diffusion destabilises a uniform state
Change one input at a time and compare the recalculated curves with the argument above. The browser evaluates this small model locally; the accompanying numerical values state its assumptions and reference checks. Reset restores the reference inputs, and the data can be downloaded as CSV.
Problem sheet 7 · Project · Verify a heat solver before interpreting its temperature
A laboratory plate can be heated internally and cooled at its boundary. Check global feasibility, the spatial error between nodes and the wavelength-dependent decay of periodic modes.
Can the thermal problem have a steady solution?
A one-dimensional bar of unit length and cross section obeys \(-u''=2\) in scaled units. Prescribe outward conductive fluxes \(q_L=0.5\), \(q_R=1.2\). Integrate the equation before solving. What physical quantity changes with time under these fluxes? Correct the right flux while keeping the left.
Work through the solution
Outward flux is \(-u'n\). Total outward flux must equal the integrated source, 2. The prescribed sum is 1.7, leaving a positive heating imbalance of 0.3. With finite heat capacity the mean temperature rises. A compatible right flux is 1.5. A steady calculation with purely Neumann data then needs a reference temperature. Use the Neumann compatibility experiment. Its left sensor reports zero rightward flux. For this comparison set \(v=u-0.5x\), which shifts the rightward flux by +0.5 at both ends. The original measurement then corresponds to the slider setting “Right flux minus 2” of −0.30, and the corrected data correspond to zero.
Fix the reference and check signs
For the compatible data, find the quadratic solution with zero spatial mean. Verify both fluxes and show which part a gradient measurement cannot recover.
Work through the solution
Integrating twice gives \(u=-x^2+0.5x+C\) because at the left \(q_L=u'(0)=0.5\). At the right \(-u'(1)=1.5\). The mean is \(-1/3+1/4+C\), so \(C=1/12\). Adding any constant leaves every flux and gradient unchanged. A measured mean supplies information absent from the differential equation.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Explain the missing inter-element curvature
Interpolate that exact quadratic linearly on uniform elements of width \(h\). Derive the peak pointwise interpolation error on one element and the jump in its piecewise-constant derivative between adjacent elements. Predict what happens when \(h\) halves. Compare the two errors with the residual and refinement example, which uses unequal sources on the two halves and reports a global energy norm.
Work through the solution
On \([a,b]\), \(u-I_hu=-(x-a)(x-b)\), which peaks at \(h^2/4\). The slope of each secant equals the exact derivative at its midpoint. Moving to the next element changes this slope by \(-2h\). Halving \(h\) quarters the peak value error and halves the jump magnitude. The adaptive experiment measures the gradient error in an energy norm. Uniformly halving all element widths would halve that norm for this quadratic. Selective refinement can give a different global ratio. Machine-small residual in the assembled linear system alone measures neither the field error nor the derivative jump.
Test an independent transient boundary condition
Now join the ends periodically. For \(u_t=u_{xx}\) on a unit ring, a sine of mode \(m\) decays at rate \((2\pi m)^2\). Derive the semi-discrete finite-difference rate and evaluate its ratio to the true rate at eight points per wavelength.
Work through the solution
A Fourier mode on the grid acquires factor \(-4\sin^2(\pi m h)/h^2\) under the centred second difference. At eight points per wavelength, the ratio is \([\sin(\pi/8)/(\pi/8)]^2\approx0.94964\). Numerical decay is about 5% too slow even with exact time integration. Compare with the modal diffusion experiment with 16 nodes and mode 2. The frequency and domain scaling differ, but the decay-rate ratio depends only on points per wavelength. Periodic and flux tests isolate distinct boundary and discretisation errors.
Problem sheet 8 · Resolve an outflow layer by fitting the numerical face flux
A dilute solute moves down a channel and diffuses against its mean flow. Fixed concentrations at the ends generate a thin downstream layer. Construct the cell flux directly from the differential equation, then ask how a solver can return nearly the right total throughput while still predicting an impossible local concentration.
Solve the physical flux problem before discretising
Let \(x\in[0,1]\), positive constant speed \(a\), and constant diffusivity \(D\). Steady conservation gives \(\partial_x J=0\) with \(J=au-Du_x\). Impose \(u(0)=1\), \(u(1)=0\). Find \(u(x)\) and the flux. Where must the sharp gradient occur when \(a/D\) is large?
Work through the solution
Constant flux turns the equation into \(u'-(a/D)u=-J/D\). Multiplication by \(e^{-ax/D}\) and integration gives a constant plus an exponential. The boundary values yield
Far upstream for large \(a/D\) the concentration stays near one and most of the flux is advective. At the downstream wall the concentration is zero, but the diffusive term carries the same positive flux. The layer thickness scale is \(D/a\), a length. Constant throughput requires convection and diffusion to trade roles across the layer.
Explore the related calculation with adjustable inputs. Change the parameters in the experiment on this same project page and compare its output with this part of the derivation.
Derive the Scharfetter–Gummel face relation
Take a segment from \(x_i\) to \(x_{i+1}\) of length \(h\) with given endpoint concentrations \(u_i,u_{i+1}\). Solve the same constant-coefficient equation across that segment and express the face flux in a form with a well-defined zero-velocity limit.
Work through the solution
Define \(P=ah/D\) and \(B(P)=P/(e^P-1)\) with \(B(0)=1\). Integrating between the endpoints gives
Solving for the common flux and using \(B(-P)=e^P B(P)\) yields
At \(P=0\) it reduces to the centred diffusive flux. For large positive \(P\), \(B(P)\) becomes small while \(B(-P)\) approaches \(P\); the advective part then uses the upstream value. Both coefficients stay positive for real \(P\), supporting monotone solutions of this one-dimensional problem.
Explore the related calculation with adjustable inputs. Change the parameters in the experiment on this same project page and compare its output with this part of the derivation.
Numerical evaluation requires more than inserting the formula literally. Near zero use \(P/\operatorname{expm1}(P)\) or the series \(1-P/2+P^2/12+\cdots\). At very large positive \(P\), use \(B(P)=P e^{-P}/(1-e^{-P})\) to avoid exponential overflow. The identity \(B(-P)=B(P)+P\) avoids a second evaluation. Equal face fluxes across adjacent cells impose local conservation: whatever leaves one control volume enters its neighbour. For constant properties and no internal source, the exact local solution on each segment matches the analytic global nodal values, even when few grid points lie within the layer.
Diagnose a nearly correct throughput with impossible concentrations
Set \(a=1\), \(D=1/24\) and use eight equal segments. Compare the penultimate nodal concentration from exponential fitting, centred advection and first-order upwinding. Why can global throughput hide the error?
Work through the solution
The cell Péclet number is three. For any two-point constant flux relation with constant coefficients the homogeneous nodal variation is \(r^i\). Exponential fitting gives \(r=e^P\); centred advection gives
upwinding gives
With these Dirichlet values the solution is \((r^N-r^i)/(r^N-1)\). At node seven the three values are approximately \(0.9502,\ 1.2000,\ 0.7500\). The centred approximation exceeds the inflow concentration and alternates around it because \(r\) is negative. Upwinding preserves the admissible interval but makes the layer broader. Exponential fitting gives the true nodal value for this local model.
Explore the related calculation with adjustable inputs. Change the parameters in the experiment on this same project page and compare its output with this part of the derivation.
For each scheme, a constant concentration transports advective flux \(au\), while its \(r^i\) homogeneous part has zero net flux. The numerical throughput consequently equals \(a r^N/(r^N-1)\). With eight cells the centred scheme predicts about \(1.00000256\), remarkably close to the true \(1.00000000004\), despite its local overshoot of twenty percent. A scale measuring total output could validate the wrong spatial solver. Report a pointwise quantity, a monotonicity check and flux conservation in addition to throughput if the concentration near the outlet matters.
Test fitted nodes and resolve the inside of a cell
Vary the number of segments and the global Péclet number in the live graph. Under which interpretation is exponential fitting exact, and how could a plotted straight line through its last two values mislead an experimenter?
Work through the solution
Under the specified homogeneous coefficients, zero sources and exact boundary data, the fitted scheme reproduces the analytic solution at every node and returns its correct constant flux. It does not make a piecewise-linear drawing between those nodes the exact local profile. With eight cells at global Péclet number 24, the midpoint of the last cell is \(1/16\) from the outlet. The exact concentration is about \(1-e^{-1.5}=0.777\); linear interpolation between \(0.9502\) and zero gives only \(0.4751\). Reconstruction inside the cell requires the exponential solution with the two endpoint values, or more resolution. Distinguish the face flux actually used in the method from a derivative estimated by visually differentiating the drawn polyline.
Explore the related calculation with adjustable inputs. Change the parameters in the experiment on this same project page and compare its output with this part of the derivation.
Try cell Péclet numbers just below and above two. The centred solution changes from a very sharp monotone profile to a sign-alternating boundary correction. The fitted flux changes continuously through the same transition. If coefficients vary significantly within a cell or a source deposits mass inside it, one needs a corresponding local model, source integration or refinement. An exact result for one constant-coefficient test helps isolate the subsequent approximation. It cannot establish accuracy for every heterogeneous transport problem.
The Sesame semiconductor solver documents exponential fitting of its carrier fluxes.
Notebook practice · When diffusion destabilises a uniform state
Spatial discretisation and field equations
Derive a discrete field problem from a continuous equation, choose appropriate boundary data and test the convergence of quantities a measurement could resolve.
- Choose the physically admissible wave in a conservative update
A discontinuous scalar flow can satisfy integral conservation in more than one way. Derive the shock speed, use a convex entropy to distinguish a compression from an expansion and build a finite-volume flux from the resulting local solution.
- Bound diffusion error by balancing a reconstructed flux
A temperature field from a finite-element calculation looks smooth. Reconstruct a heat flux which exactly balances the source, then derive an upper bound for the true energy error without knowing the exact temperature.
- A Fourier Poisson solver and the trouble caused by unresolved products
In a periodic medium the constant part of a source decides whether a Poisson problem has any solution. Derive the Fourier solver, separate spectral and finite-difference symbols, and see how a nonlinear product can inject a false low-frequency source.
- How much of an outgoing wave reflects from the numerical boundary?
A finite grid truncates an effectively open medium. Derive an exact one-dimensional radiation condition, predict the angular reflection of its two-dimensional extension and design a pulse experiment that separates boundary reflection from interior dispersion.
- Can a stable finite-element heat step turn a cold node negative?
Start a conducting rod with one positive temperature pulse. Assemble the heat capacity from first principles and determine when an explicit step respects both decay and the sign of every temperature.
- Solving two-dimensional diffusion one direction at a time
Derive a second-order alternating-direction step, identify the boundary data required halfway through it and distinguish splitting error from mesh and time errors.
- Following the error from one reference triangle to an entire mesh
Derive a first-order energy error estimate and a second-order displacement estimate for a conforming linear triangular discretisation. Track the assumption on element shape at the point where it enters the proof.
- Which waves are allowed to enter a numerical boundary?
Diagonalise linear acoustics, impose one physical condition per incoming wave and compare diffusive and dispersive transport schemes on the same spatial Fourier mode.
Spatial discretisation and field equations · 1. Choose the physically admissible wave in a conservative update
A discontinuous scalar flow can satisfy integral conservation in more than one way. Derive the shock speed, use a convex entropy to distinguish a compression from an expansion and build a finite-volume flux from the resulting local solution.
Integrate across a moving discontinuity
Consider inviscid Burgers' equation \(u_t+(u^2/2)_x=0\). Where \(u\) is smooth its characteristics move at speed \(u\). For left state \(u_L>u_R\), faster left characteristics catch slower right ones and the profile steepens. If discontinuity position is \(x=st\), integrate the conservation law across a narrow moving control volume. The storage change from the moving boundary gives \(s(u_R-u_L)=f(u_R)-f(u_L)\), so for unequal states \(s=(u_L+u_R)/2\). The value is a conservation-law jump speed; applying the pointwise product \(u\,u_x\) across a discontinuity without defining it could predict another speed.
The same jump calculation formally allows \(u_L<u_R\), although a smooth monotone connection then spreads. To identify the physical weak solution, add a small positive viscosity \(\nu u_{xx}\) and consider its limiting dissipation. For convex entropy \(\eta=u^2/2\) with entropy flux \(q=u^3/3\), multiplication of the viscous equation by \(u\) gives
As viscosity vanishes the entropy production is nonpositive in distributions. Across a sharp jump the coefficient is
where brackets mean right minus left. It is negative for a compression shock and positive for an expansion shock. Thus the latter satisfies mass conservation but violates this entropy criterion.
Construct the rarefaction from its self-similar coordinate
For a left-to-right increase seek \(u(x,t)=U(\xi)\) with \(\xi=x/t\). Substituting into the smooth equation gives \((U-\xi)U'=0\), so each region is constant or \(U=\xi\). Matching both states yields \(u_L\) for \(\xi<u_L\), \(\xi\) for \(u_L\le\xi\le u_R\), and \(u_R\) beyond. This continuous fan is the physically selected expansion. With \(u_L=-1,u_R=1\), the origin lies inside the fan and \(u(0,t)=0\). A stationary expansion jump would misleadingly carry flux \(1/2\) across that interface rather than the physical zero.
In a finite-volume scheme cell averages are updated by shared interface fluxes:
Solve the local Riemann problem between the piecewise-constant left and right cell states and take \(F=f(U(0))\). For a compression use the left state if \(s>0\) and the right if \(s<0\); either flux agrees for a stationary shock. For an expansion reaching across zero take zero; if the expansion moves wholly right use its left state, and if wholly left use its right. These cases give the scalar Godunov flux. The update telescopes internally because both neighbouring cells use exactly the same physical interface flux.
Distinguish shock location from smoothness and numerical thickness
A first-order Godunov discretisation under its CFL restriction is monotone and avoids spurious oscillations, but a moving discontinuity generally spreads over several cells. A centred pointwise difference may look sharper for smooth data while producing oscillations or the wrong propagation under discontinuous data. Test shock speeds from integrated cell mass or a consistent location reconstruction, compare fan areas and measure \(L^1\) error under refinement. The pointwise maximum error right at a jump can remain large even as the location and integral error converge. A visually thin front is not by itself an accuracy certificate.
For data \(u_L=1,u_R=-0.5\) the shock moves right at 0.25. At \(t=0.25\) it lies at \(x=0.0625\). In the interval \([-1,1]\) with unchanged boundary states, the total mass begins at 0.5 and grows by \([f(1)-f(-0.5)]t=(0.5-0.125)0.25=0.09375\), so the exact integral is 0.59375. A conservative numerical calculation can achieve this integral essentially to roundoff while retaining a visibly smeared shock. Conservation, entropy selection and resolved spatial profile are three independent questions.
Switch between a shock and a transonic fan
The experiment solves the finite-volume update on \([-1,1]\) with constant exterior states, a time step chosen for maximum CFL 0.8 and output time 0.25. Compare the conservative cell averages with the exact self-similar profile. Reverse both initial states to turn a compression into an expansion, then put the fan across zero. Increasing cell count changes numerical thickness, while the mass should follow the boundary flux difference at every resolution. Equal left and right states are a separate constant-preservation test.
Infer shock position from an integral measurement
A blurred profile does not require an arbitrary definition of its centre. Suppose the plateau values on \([-L,L]\) are measured reliably and a single discontinuity lies at \(X\). Its integrated state is \(M=(L+X)u_L+(L-X)u_R\). The equivalent sharp-interface position is therefore
With \(L=1,\ u_L=1,\ u_R=-1/2\), a cell-sum reading \(M=0.59375\) gives \(X=0.0625\). A mass uncertainty of \(0.003\) gives a position uncertainty of \(0.002\) in the same coordinates. The inference becomes ill-conditioned as the plateau contrast tends to zero.
This provides a mesh-independent diagnostic when numerical viscosity smears the jump. Track both an area-based position and a measure of thickness, for example the distance between the two intermediate levels one-quarter and three-quarters across the jump. A conservative solver may retain a highly accurate area-based position while thickness changes strongly under refinement. In a rarefaction the same scalar area exists, but two real moving edges delimit a resolved fan. Replacing the fan by one jump would throw away precisely the information the entropy condition supplied.
Tutorial · compare conservation and entropy
Calculate one update next to a moving shock
With states 1 and \(-0.5\), take \(\Delta t/\Delta x=0.5\). Find the interfacial flux and the new values in the two cells adjacent to the discontinuity, assuming homogeneous neighbours farther out.
Work through the solution
The shock speed is positive, so Godunov flux at the jump is \(f(1)=0.5\). The adjacent left cell sees equal incoming and outgoing fluxes and stays 1. The adjacent right cell sees incoming 0.5 and outgoing 0.125, so becomes
This is exactly the average associated with movement of the shock through one eighth of that right cell: \(0.125(1)+0.875(-0.5)=-0.3125\).
Check a conservative expansion jump
For \(-1\to1\), show that a stationary discontinuity satisfies mass conservation but give its entropy violation. Which profile should occupy \(x=0.10\) at \(t=0.25\)?
Work through the solution
Both end fluxes equal 0.5, so the formal discontinuity speed is zero. Its entropy coefficient is \((1-(-1))^3/12=2/3>0\), contradicting dissipation. The rarefaction has \(\xi=x/t=0.4\) inside its fan, hence \(u=0.4\) there. A scheme retaining a stationary sharp expansion jump can pass a mass check and still fail this physical verification.
Set a stable step and predict a conserved integral
On 100 uniform cells in \([-1,1]\) take \(u_L=-0.25,u_R=0.75\). What step gives maximum CFL 0.75? What mass is expected at time 0.20?
Work through the solution
Here \(\Delta x=0.02\) and maximum speed is 0.75, giving \(\Delta t=0.020\). Initial mass is \(0.5\). Boundary flux difference is \(0.03125-0.28125=-0.25\); over time 0.20 the mass falls to 0.45. Both fan edges are still far from the domain ends. For longer runs boundary data and outgoing-wave treatment would alter this budget.
Further reading
Spatial discretisation and field equations · 2. Bound diffusion error by balancing a reconstructed flux
A temperature field from a finite-element calculation looks smooth. Reconstruct a heat flux which exactly balances the source, then derive an upper bound for the true energy error without knowing the exact temperature.
Identify the natural error measure in a diffusion problem
Consider \(-\nabla\cdot(k\nabla u)=f\) on a bounded domain, with homogeneous Dirichlet temperature for clarity and strictly positive scalar conductivity \(k(\mathbf x)\) bounded above and below. The weak form is \(\int k\nabla u\cdot\nabla w=\int f w\) for every test \(w\) vanishing on the boundary. A conforming approximate temperature \(v\) satisfies the prescribed boundary trace but may not solve the equation. Its energy error \(\|\nabla(u-v)\|_k^2=\int k|\nabla(u-v)|^2\) weights local gradient errors according to their physical conductivity. This differs from pointwise temperature error, total dissipation error or the absolute error of one designated sensor.
Define true heat flux \(q=-k\nabla u\). It obeys \(\nabla\cdot q=f\). Suppose a reconstructed flux \(\sigma\) obeys the same divergence exactly and has the prescribed normal flux on any Neumann boundary, with normal component continuous across interior mesh faces. Such fluxes belong naturally to a space often written \(H(\mathrm{div})\). Conforming temperature and equilibrated flux are separate requirements: a continuous piecewise-linear temperature gives generally discontinuous normal gradient flux across faces, even if all global nodal equations were solved accurately.
Prove an upper bound by cancelling a cross term
Take the weighted constitutive defect \(\sigma+k\nabla v=(\sigma-q)+k\nabla(v-u)\). Expand its squared \(k^{-1}\) norm. The cross term is \(2\int(\sigma-q)\cdot\nabla(v-u)\). Integrating by parts gives a volume term proportional to \(\nabla\cdot(\sigma-q)=0\) and a boundary term zero where \(v-u=0\) or the normal flux difference is prescribed zero. Interior normal continuity prevents an extra jump term. Hence
The left side can be calculated from the approximation and reconstruction. It bounds the unknown energy error from above, with equality precisely when the reconstructed flux equals the true flux. A divergence-compatible but inaccurate \(\sigma\) still certifies an upper bound, albeit possibly a loose one. This identity is an instance of the Prager–Synge hypercircle principle. With approximated data or inexact equilibration, extra data oscillation and residual terms must be bounded before calling an indicator a guaranteed bound.
Background · How does a nonzero flux imbalance enter the certificate?
Take heat flux \(q=-k\nabla u\), so that \(\nabla\cdot q=f\). Suppose a reconstructed flux \(\hat q\) leaves a source residual \(r=f-\nabla\cdot\hat q\), and the approximate and exact temperatures agree on the entire Dirichlet boundary. Testing the residual equation with their difference \(e=u-u_h\) gives
With \(k\geq k_{\min}>0\) and a Poincaré constant \(C_P\) such that \(\|e\|\le C_P\|\nabla e\|\), the energy norm is bounded by \(\|k^{-1/2}(\hat q+k\nabla u_h)\|+C_P\|r\|/\sqrt{k_{\min}}\). The second term is the price of imbalance. If source data have been projected onto simpler functions during reconstruction, include their residual against the actual source before calling the result a bound.
Carry out the entire construction on two elements
On \([0,1]\) let \(k=1,\ f=2,\ u(0)=u(1)=0\). The exact \(u=x(1-x)\) is available for checking although unnecessary for the estimator. The conforming piecewise-linear interpolant on two half-elements has slopes \(+0.5,-0.5\). Any flux \(\sigma(x)=2x+C\) exactly balances the source. Choose \(C\) to minimise \(\int(\sigma+v')^2dx\). Its derivative is \(2\int(2x+C+v')dx=2(1+C)\), since \(v(1)-v(0)=0\). Thus \(C=-1\), giving \(\sigma=2x-1=q\). The estimator is \(\sqrt{1/12}=0.288675\): on each half interval the defect is a linear ramp from \(-0.5\) to \(+0.5\) or its translated equivalent. Direct integration of \((u'-v')^2\) confirms equality.
If instead choose \(C=-0.8\), source equilibrium is still exact but the flux carries a uniform 0.2 offset. Its squared error contribution is 0.04, giving bound \(\sqrt{1/12+0.04}=0.3512\). Choosing an equilibrated flux means satisfying local balance; optimising its closeness to the constitutive flux sharpens the estimate. The true temperature error is unchanged in both comparisons. In more dimensions mixed finite elements or local face-flux reconstructions enforce shared normal flux degrees of freedom; local least-squares choices can improve sharpness without requiring a global exact solution.
Use element contributions without confusing local and global bounds
The squared estimator splits as \(\sum_K\int_K k^{-1}|\sigma+k\nabla v|^2\). Large element contributions can guide refinement and give a reproducible stopping rule for global energy error. The exact orthogonality proof, however, integrated over the full domain. Boundary terms between elements may fail to vanish on one element individually, so one local contribution need not be a strict independent upper bound on that element's actual error. For a particular output of interest, e.g. a mean temperature in a small sensor region, use the dual problem or a proven continuous inequality to translate energy uncertainty into output uncertainty.
Vary an equilibrated flux while holding the solution fixed
The source and exact quadratic temperature are those of the worked one-dimensional example. The plot compares the exact flux, the raw elementwise flux from the continuous linear temperature and a reconstructed flux with the correct divergence and a freely chosen constant offset. Changing this constant is permitted because the original problem specifies boundary temperatures. The mean energy-error contribution from an offset appears in quadrature with the true temperature-gradient error, exactly as in the derived identity. For two elements and offset 0.20 the bound is about 0.3512 while the actual energy error is 0.2887.
Increase the number of cells with the offset held fixed. The raw staircase becomes more accurate, but the reconstruction bound eventually plateaus near the absolute offset because the reconstructed flux still contains its deliberate uniform error. Set the offset to zero to recover the sharp certificate on each mesh. Notice that a constant flux offset preserves the source balance in this Dirichlet test; it would generally violate a specified Neumann flux at a boundary. A valid estimator depends as much on the boundary conditions as on the differential equation.
Tutorial · verify an error certificate rather than a residual plot
Predict refinement on a uniform mesh
Use the same quadratic exact solution and \(N\) equal elements. Find the energy error of the nodal interpolant and verify the two-element value.
Work through the solution
On each interval \(v'\) is the average of the linear exact derivative \(1-2x\). The derivative difference is a line of slope \(-2\) centred at the midpoint. Its squared integral is
Summing \(N\) terms gives error \(h/\sqrt3\). At \(h=1/2\) this equals \(1/\sqrt{12}\). Halving the element size halves the energy error even though the nodal temperature error for this interpolation is exactly zero at the nodes.
Diagnose a spuriously perfect estimator
An engineer chooses \(\sigma=-k\nabla v\) directly and gets a zero constitutive defect. Why does this not prove \(v=u\) for the two-element example?
Work through the solution
This piecewise-constant flux has zero derivative inside each element and a jump at the middle node. It fails the required divergence equation \(f=2\) as a distributed source and fails normal continuity. The missing volume and interface cross terms invalidate the orthogonality argument. A zero defect certifies a true solution only alongside both primal admissibility and flux equilibrium with the stated boundary conditions.
Bound the error of a mean temperature
On the unit interval with zero endpoint error, use \(\|w\|_2\le\|w'\|_2/\pi\) to bound the domain-mean error from the sharp two-element certificate. Compare with direct integration.
Work through the solution
Cauchy–Schwarz on a unit-length domain gives
The exact integral of \(u\) is \(1/6\); the triangular interpolant has area \(1/8\), giving actual mean error \(1/24=0.04167\), within the bound. An error certificate for the gradient can yield a conservative output bound through an independently justified inequality; its units and domain constants cannot simply be omitted.
Further reading
Spatial discretisation and field equations · 3. A Fourier Poisson solver and the trouble caused by unresolved products
In a periodic medium the constant part of a source decides whether a Poisson problem has any solution. Derive the Fourier solver, separate spectral and finite-difference symbols, and see how a nonlinear product can inject a false low-frequency source.
Find compatibility and gauge before dividing by a wave number
On a periodic interval of length \(2\pi\), solve \(-u''=f\). Integrating over one period gives \(0=\int f\) because periodic derivative values agree at the ends. This is an existence condition. If a solution exists, adding a constant changes neither field gradient nor source, so specify a mean \(u_0\) separately to fix uniqueness. These two roles sometimes get conflated in numerical code that simply sets the Fourier coefficient at zero to zero. Setting \(u_0=0\) fixes a gauge; deleting nonzero \(f_0\) removes a physical mean source and changes an incompatible model. Check the measured source mean before applying a projected solve.
For \(f(x)=\sum_k f_ke^{ikx}\), take \(u_k=f_k/k^2\) for \(k\ne0\). For a length \(L\) in physical units replace \(k\) by \(2\pi j/L\). A compatible source \(f=\cos3x+0.2\sin x\) gives mean-zero \(u=\cos3x/9+0.2\sin x\). Higher spatial frequencies are smoothed by the inverse Laplacian; data noise at low but nonzero wavenumber can affect the inferred field more strongly than visually rapid fluctuations of equal source amplitude. A compatible constant reference level of potential cannot be inferred from this equation even with noiseless source data.
Compare an exact spectral solve with a discrete operator
On \(N\) equispaced nodes, an FFT diagonalises any periodic translation-invariant discrete convolution, but the diagonal symbol depends on the operator being solved. A spectral second derivative uses \(k^2\) for \(-u''\), while a second-order periodic difference stencil uses \(\lambda_h(k)=4\sin^2(kh/2)/h^2\), \(h=2\pi/N\). The same FFT can invert either symbol. Verify a solver by applying the matching discrete operator back to its result. A Fourier result with tiny residual for the finite-difference stencil is a precise solution of that stencil; it does not thereby reproduce the continuum Fourier amplitude exactly.
At \(N=16,k=4\), \(kh/2=\pi/4\), hence \(\lambda_h=2/h^2=12.97\), compared with continuum \(k^2=16\). A unit cosine source has spectral potential amplitude 0.0625; the finite-difference inverse gives approximately 0.0771. Both can pass a discrete residual at machine precision in their appropriate systems. At fixed physical mode the symbols approach one another as \(N\) increases; at mode number constantly near the Nyquist limit their relative discrepancy need not vanish. A convergence test keeping \(k/N\) fixed follows different physical sources at each refinement.
Identify aliased modes before applying the inverse
For \(N\) samples, Fourier modes with indices differing by an integer multiple of \(N\) coincide at all nodes. Suppose a source includes \(v^2\), where \(v=\cos(5x)\) on a 12-point grid. Squaring exactly yields \([1+\cos(10x)]/2\). But sampled \(\cos10x=\cos2x\), so the grid reports an apparent low \(k=2\) component. Subtracting the known mean gives a compatible source, but the resulting potential amplitude becomes \(0.5/2^2=0.125\) at the wrong spatial frequency rather than \(0.5/10^2=0.005\) at the true one. The inverse Laplacian magnifies the false low-mode contribution, transforming a sampling error into a large field error.
To obtain the product projected on a retained Fourier band, zero-pad the input Fourier coefficients on a sufficiently enlarged grid, transform to space, multiply there, transform back and discard unretained output modes. For modes \(|k|\le K\), a quadratic product extends to \(2K\). To ensure none of its high modes folds back into the retained range, choose multiplication grid size strictly greater than \(3K\), or handle endpoint/Nyquist modes explicitly. This is the usual three-halves padding rule relative to a base grid around \(2K\). Different FFT normalisations require scaling when padding and truncating. Simply padding already multiplied samples cannot recover frequency information that has already aliased.
For a deliberately filtered small problem one can instead drop the top third of the spectrum on a fixed grid before nonlinear multiplication, retaining only \(|k|<N/3\). This avoids erroneous feedback into the retained modes but also discards legitimate high-frequency information. Choosing a finer physical grid can be preferable when the physical quantity of interest depends on those modes. Dealiasing corrects a numerical representation of the chosen projected equations; it does not supply a physical closure for unresolved turbulence, interfaces or material fluctuations.
Follow one unresolved harmonic through the Poisson inverse
The simulation multiplies a cosine of mode m by itself, removes its exact mean and inverts the periodic Poisson operator. The continuum curve retains the true product mode 2m. The unpadded curve uses whichever harmonic the coarse point samples represent, while the third curve shows the correctly projected solution restricted to the original resolvable Fourier band. At 12 samples and m equal to 5, coarse multiplication creates a false mode two whose potential amplitude is 25 times the desired continuum amplitude. The resolved-band projection correctly eliminates that harmonic rather than inventing a low mode.
Increase N until the true product is representable. The three answers then agree, including the phase of the spatial variation. The control limits the actual input frequency to a representable non-Nyquist input and reports the mode used, so changing the grid cannot silently inject an impossible input. A projected curve equal to zero means none of this particular product survives the retained band. It does not mean the continuum product or the underlying fine-scale field vanishes.
Tutorial · verify mean source, discrete response and nonlinear products
Detect an impossible boundary-value problem
A periodic source has \(f(x)=0.03+\sin x\). A program reports \(u=\sin x\) and a machine-small residual after dropping the zero Fourier mode. Evaluate the actual residual and explain its interpretation.
Work through the solution
For the reported solution \(-u''=\sin x\), so the original pointwise residual \(-u''-f=-0.03\) everywhere and its integral is \(-0.06\pi\). There is no periodic solution to the original equation. The programme exactly solved the mean-subtracted problem. An external sink or a physically justified zero-mean correction could make such a model appropriate, but the removed source must be stated and checked.
Predict the grid error of a low physical mode
For \(k=1\), expand \(\lambda_h(k)\) and find the leading relative error in the finite-difference solution amplitude for a fixed unit cosine source.
Work through the solution
Using \(\sin^2 z=z^2-z^4/3+\cdots\) gives
Inversion yields
The discrete potential amplitude is too large to leading order. Refining at the same \(k\) by halving \(h\) should reduce the amplitude error by roughly four. This statement differs from finding the residual of the already solved stencil.
Choose a padding size from the desired output band
Input modes occupy \(|k|\le5\), and only output modes \(|k|\le5\) of their quadratic product will be kept. Compare multiplication grids with 14 and 16 points.
Work through the solution
With 14 points a possible product \(k=10\) aliases to \(-4\), contaminating the retained range. With 16 points all modes \(6,\ldots,10\) which wrap do so outside \([-5,5]\); for example 10 wraps to \(-6\). Thus 16 is sufficient for retained coefficients. It is not sufficient to represent and report the complete \(k=10\) output wave itself, which needs a larger bandwidth. Distinguish accuracy of a projected nonlinear evolution from recovery of every generated physical harmonic.
Further reading
Spatial discretisation and field equations · 4. How much of an outgoing wave reflects from the numerical boundary?
A finite grid truncates an effectively open medium. Derive an exact one-dimensional radiation condition, predict the angular reflection of its two-dimensional extension and design a pulse experiment that separates boundary reflection from interior dispersion.
Factor the one-dimensional wave equation
For a constant wave speed \(c>0\),
A right-moving waveform \(F(x-ct)\) satisfies \(u_t+c u_x=0\) and a left-moving waveform satisfies \(u_t-c u_x=0\). At the right boundary impose \(u_t+c u_x=0\) to transmit a purely outgoing right-moving wave; at the left boundary reverse the normal sign. This exact radiation condition requires no knowledge of \(F\) for the constant-coefficient 1D medium. A Dirichlet end instead forces a reflected amplitude minus the incident one, while a Neumann end reflects with the same sign. Both have unit reflected energy for an ideal undamped wave.
A separate energetic argument tests the sign. The interior energy \(E=\tfrac12\int(u_t^2+c^2u_x^2)dx\) has derivative \(dE/dt=c^2[u_tu_x]_{\rm left}^{\rm right}\). At a transmitting right end \(u_x=-u_t/c\), giving outward energy loss \(-c u_t^2\). Imposing the opposite sign there would permit energy injection. A dissipative boundary need not absorb perfectly: it can still reflect some of the incoming wave. The energy identity tests passivity, while a pulse-amplitude experiment tests reflection separately. An initially localised pulse that has not yet reached any boundary is a useful independent check of the interior solver.
Predict reflection as the incidence direction changes
For a flat boundary normal to \(+x\) in two dimensions, the local condition \(u_t+c u_x=0\) is exact only for normal incidence. Consider incident wave \(e^{i(k_xx+k_yy-\omega t)}\) and reflected wave of amplitude \(R\) with \(k_x\) reversed. Use \(\omega=c\sqrt{k_x^2+k_y^2}\) and place the boundary at \(x=0\). Substitution into the condition gives \((-\omega+ck_x)+R(-\omega-ck_x)=0\), hence
where \(\theta\) is measured from the outward normal. The reflected normal-energy fraction is \(|R|^2\) because incident and reflected magnitudes and normal speed factors match. Normal incidence gives zero. At \(60^\circ\), \(R=-1/3\) and power reflection \(1/9\); at grazing incidence its magnitude approaches one. An unspecified claim of a “nonreflecting boundary” has no definite quantitative meaning without frequency, angle, medium and discretisation.
An ideal exterior transparent condition can be expressed after transforming in tangential direction and time: \(\partial_x\hat u=ik_x\hat u\) with \(k_x=\sqrt{(\omega/c)^2-k_y^2}\) on the outgoing or decaying branch. The square root shows why a single local first derivative cannot cover all tangential frequencies exactly. Expanding the square root near normal incidence motivates higher-order absorbing boundary conditions; other methods use a carefully matched absorbing layer. The present first-order formula provides a baseline against which such alternatives can be tested. An evanescent component with imaginary normal wavenumber requires the decaying branch; interpreting it as a propagating beam with a real incidence angle would be incorrect.
Measure boundary error independently of grid dispersion
An interior finite-difference solver usually has a numerical dispersion relation \(\omega_h(k_x,k_y)\). A discrete version of the continuum boundary condition need not be exactly matched even for a strongly resolved normally incident wave, particularly if boundary and interior stencils have different dispersion errors. To isolate the two effects, first propagate the same pulse on a much longer or periodic domain until it passes the observation probe and before any distant return. Record that reference. Then repeat with the open boundary placed closer and compare at the same probe over the predicted return window. Project signals onto spatial directions or separate incident and reflected time windows to estimate amplitude and energy.
For a probe distance \(D\) from a flat boundary and a narrow incident beam at angle \(\theta\), normal group speed is \(c\cos\theta\). The time between incident and reflected peaks measured on a normal coordinate is roughly \(2D/(c\cos\theta)\), provided the probe or array also samples the reflected beam's tangential position. A point probe on an oblique pencil beam need not see both pulses at all; an extended plane-wave excitation or a probe array is more suitable for estimating the stated reflection coefficient. Run a sequence of grid refinements at fixed physical angle and wavelength. Reflection approaching the analytical \(|R|\) indicates continuum boundary-model error; reflection shrinking toward zero at normal incidence indicates discretisation mismatch.
Measure a boundary reflection across incidence angles
The plotted energy fractions follow directly by matching an incoming and a reflected plane wave at a flat boundary. One curve uses the physically correct wave speed in the first-order condition; the other lets the specified boundary speed differ from the interior. Use the angle slider to inspect the signed amplitude as well as its squared magnitude. At matched speed and sixty degrees the amplitude is minus one third and the reflected energy is about 11.11 percent. At normal incidence the matched boundary absorbs the incident plane wave completely.
Choose a boundary speed larger than the interior speed. There is then an oblique angle at which the mismatch exactly compensates the projected normal phase in this local equation. It obeys cosine of the angle equal to the reciprocal speed ratio. For a ratio 1.25 this is about 36.87 degrees. Matching this one direction sacrifices perfect normal incidence; it is not an omnidirectional improvement. The graph concerns the continuous condition. An actual spatial discretisation can add reflection through numerical dispersion, which the longer-domain pulse comparison in this unit is designed to detect.
Tutorial · identify the return signal
Determine the admissible incidence angle for one-percent reflected energy
Solve \(|R|^2\le0.01\) for a real outgoing incidence angle \(0\le\theta<90^\circ\).
Work through the solution
The amplitude criterion is \((1-\cos\theta)/(1+\cos\theta)\le0.1\), so
This gives \(\theta\lesssim35.1^\circ\). Requiring one-percent amplitude instead would impose a stricter angle. A specification should state whether it concerns a field amplitude or a quadratic energy measurement.
Calculate reflection from an incorrectly tuned 1D boundary
The physical medium has speed \(c\) but the implemented condition uses \(u_t+c_bu_x=0\) with \(c_b=1.20c\). Find the normally reflected amplitude and energy fraction.
Work through the solution
The right-travelling dispersion gives
Repeating the boundary substitution yields
with energy reflection 0.00826. Its phase sign differs from the negative reflection arising for oblique incidence with a correctly tuned speed. A reflected waveform's sign can thus help diagnose a mismatch rather than reporting only its energy.
Design a time window to catch a weak return
A plane pulse propagates at 200 m/s and a line of probes is 3.0 m inside the boundary. Estimate normal-incidence and \(60^\circ\) return delays. Which comparisons are needed when a 2% amplitude is measured at normal incidence?
Work through the solution
The delays are
The continuum boundary predicts zero at normal incidence, so check interior numerical dispersion, boundary stencil, angular spread of the finite-width excitation, signal extraction and any physical material change near the boundary. A larger reference domain and refinement at fixed wavelength distinguish numerical return from pulse tails. A 2% amplitude corresponds to \(0.04\%\) reflected energy under matching impedances, not 2% energy.
Further reading
Spatial discretisation and field equations · 5. Can a stable finite-element heat step turn a cold node negative?
Start a conducting rod with one positive temperature pulse. Assemble the heat capacity from first principles and determine when an explicit step respects both decay and the sign of every temperature.
Integrate the heat equation against a hat function
Take a uniform rod of length one with the two endpoint temperatures held at zero. With constant diffusivity \(\kappa>0\) the evolution is \(u_t=\kappa u_{xx}\). Approximate \(u(x,t)\) as a linear combination of continuous piecewise-linear hat functions. Multiply by an interior hat and integrate. Integration by parts transfers one spatial derivative onto each hat. The boundary term vanishes. The nodal temperature vector satisfies
On an element of length \(h\) the two hats are \(1-x/h\) and \(x/h\) in local coordinates. Integrating their products gives diagonal entries \(h/3\) and off-diagonal entries \(h/6\) in the element mass matrix. Their constant derivatives give diagonal stiffness \(\kappa/h\) and off-diagonal stiffness \(-\kappa/h\). After assembly and imposing Dirichlet values, the interior mass has diagonal \(4h/6\) and neighbouring entries \(h/6\). The stiffness has diagonal \(2\kappa/h\) and neighbours \(-\kappa/h\).
Forward Euler advances with \(G=I-\Delta t M^{-1}K\). On an eigenvector of \(K\phi=\lambda M\phi\) it multiplies the amplitude by \(1-\Delta t\lambda\). A bound \(\Delta t\lambda_{\max}\leq2\) therefore ensures no growth in the mass norm. Preserving nonnegative temperatures for every nonnegative initial vector requires every entry of \(G\) to be nonnegative. Each column is the response to a single positive nodal impulse, so the latter condition can be tested directly.
One alternative assigns half of each element's total heat capacity to each endpoint, before removing boundary degrees of freedom. Each interior mass then equals \(h\) and the explicit stencil has weights \(r,1-2r,r\), with \(r=\kappa\Delta t/h^2\). These coefficients are all nonnegative for \(0\leq r\leq 1/2\). The first and last interior equations also couple to the fixed zero boundary temperatures.
Compute the remote temperature after one update
With three interior nodes, \(h=1/4\), initially set the left interior node to 1 K above the boundary reference and both others to zero. Inverting the consistent mass in this three-by-three system gives the first column of \((h^2/\kappa)M^{-1}K\) as \((51,-36,9)/14\). At \(r=0.1\) the interior temperatures after one step become \((0.63571,0.25714,-0.06429)\) K. The cold node two edges away immediately drops below the lower reference.
The largest dimensionless eigenvalue is about 7.9223. The chosen step gives \(r\lambda_{\max}h^2/\kappa\approx0.7922\), comfortably inside the linear stability interval. Lumping instead gives \((0.8,0.1,0)\) K. The negative consistent-mass entry shrinks linearly when the step shrinks. For this impulse its sign persists for every positive first step. With OneSimulation installed locally, the notebook also constructs a physical line mesh and obtains the mass and stiffness by integrating its hat functions at mapped quadrature points. Compare the assembled result against the explicit tridiagonal entries. The experiment shows why reducing the time step can satisfy a stability test without restoring a discrete maximum principle.
Open full-size diagram
Open full-size diagramExercise · keep the lumped temperatures nonnegative
Suppose \(h=0.02\) m and \(\kappa=8\times10^{-5}\) m²/s. Find the greatest time step allowed by nonnegative weights. What stencil results at that step?
Work through the solution
The condition gives \(\Delta t=h^2/(2\kappa)=2.5\) s. The central coefficient vanishes and each adjacent value receives weight one half. At the first interior node the fixed boundary value supplies one of these two terms. A step slightly above this threshold gives a negative central coefficient and can drive an isolated positive impulse below zero.
Exercise · derive the largest mode on successively finer meshes
An interior sine wave has neighbouring sum \(2\cos(\theta)\) times its own nodal value. Use this fact to find the limiting stability condition for forward Euler with consistent mass as the number of uniform elements grows.
Work through the solution
The mass eigenvalue is \(h(2+\cos\theta)/3\) and the stiffness eigenvalue is \(2\kappa(1-\cos\theta)/h\). Their ratio, multiplied by \(h^2/\kappa\), is \(6(1-\cos\theta)/(2+\cos\theta)\). The largest allowed angle tends to \(\pi\), giving 12. The limiting stable step therefore has \(r\leq1/6\). A positivity test still inspects the entries of the update matrix separately.
Change parameters · Explore this notebook model
Change one input at a time and compare the recalculated curves with the argument above. The browser evaluates this small model locally; the accompanying numerical values state its assumptions and reference checks. Reset restores the reference inputs, and the data can be downloaded as CSV.
Spatial discretisation and field equations · 6. Solving two-dimensional diffusion one direction at a time
Derive a second-order alternating-direction step, identify the boundary data required halfway through it and distinguish splitting error from mesh and time errors.
Factor the two-dimensional heat operator
For \(u_t=\kappa(u_{xx}+u_{yy})\) on a rectangle, first impose homogeneous Dirichlet data. Centred second differences on a Cartesian mesh give \(\dot U=(X+Y)U\), where \(X,Y\) are the directional diffusion matrices. For constant diffusivity and these boundaries the Kronecker factors commute and are symmetric negative definite. Put \(s=h/2\). Multiplying out a factored Crank–Nicolson step introduces \(s^2XY\) on both sides:
Applied to a smooth solution the added defect is \(s^2XY(U^{n+1}-U^n)=O(h^3)\) at fixed mesh. The Peaceman–Rachford realisation uses line solves
For a shared eigenmode with directional eigenvalues \(\lambda_x,\lambda_y\le0\), the amplification factor is the product of their midpoint factors. Each has modulus at most one and the product matches the exponential through order two. This argument establishes unconditional stability for the separable case. For highly damped modes a midpoint factor can change sign. Stability alone does not guarantee monotonicity or accurate damping.
Give the intermediate grid a mathematically consistent boundary
An intermediate variable solves an algebraic factor equation. It has no general obligation to equal the physical wall data at the midpoint time. For inhomogeneous boundaries choose a smooth lifting \(w\) whose trace equals the specified boundary values at all times, and evolve \(v=u-w\) with zero trace and forcing \(f+\kappa\Delta w-w_t\). For \(u=a(t)x\) with prescribed trace on all sides, \(w=a(t)x\) and \(f=a'(t)x\) give identically zero lifted field. A nonzero computed field in this manufactured case isolates a boundary or source inconsistency.
For a smooth lifted source \(g\), add \(s g(t_n+s)\) to both line-equation right sides. Expansion of the first stage and substitution into the second yields \(h g+h^2(X+Y)g/2\) through second order, along with the midpoint approximation to the source time variation. Mixing time levels at the wall can instead inject a first-order defect. Check that spatial derivatives of the lifted source stay resolved when taking a simultaneous time–space limit.
OneSimulation experiment · Propagate one heat mode in two directions
Double the spatial resolution while holding the final time fixed. Keep the grid-dependent reference in the comparison.
Download the executable notebook · Python source
Adjust the heat field and rotate its surface. Take initial data \(\sin(\pi x)\sin(q\pi y)\) on the unit square with zero wall values and \(\kappa=1\). Its directional grid eigenvalues are \(\lambda_x=-4\sin^2(\pi\Delta x/2)/\Delta x^2\) and \(\lambda_y=-4\sin^2(q\pi\Delta x/2)/\Delta x^2\). Each time step multiplies its amplitude by
The browser evaluates \(G^N\), exactly the mode reduction of the two matrix solves in the OneSimulation notebook. The rotatable surface shows the numerical field; its vertical coordinate is temperature, so this remains a two-dimensional spatial problem. The plot compares an antinode slice with both \(e^{(\lambda_x+\lambda_y)t}\) and the continuum amplitude \(e^{-\pi^2(1+q^2)t}\). First double the number of time steps on one fixed mesh, then refine the mesh. Choose a higher vertical mode and very few steps to see stable but inaccurate damping, sometimes with a reversed sign. A vertical reference from −1 to +1 keeps amplitude loss visible as the field cools.
"""Measure the temporal order of an ADI heat step against an exact grid mode."""
import matplotlib.pyplot as plt
import numpy as np
from onesim.numerics.linear.matrices.dense_linear_algebra import solve_dense
m = 9
spacing = 1/(m+1)
d = (np.diag(-2*np.ones(m)) + np.diag(np.ones(m-1), 1) + np.diag(np.ones(m-1), -1))/spacing**2
sine = np.sin(np.pi*spacing*np.arange(1, m+1))
initial = np.outer(sine, sine)
decay = -4*np.sin(np.pi*spacing/2)**2/spacing**2
end = 0.1
ref = initial*np.exp(2*decay*end)
steps, errors = np.array([2, 4, 8, 16, 32]), []
for count in steps:
plus, minus = np.eye(m) + end*d/(2*count), np.eye(m) - end*d/(2*count)
state = initial.copy()
for _ in range(count):
half = solve_dense(minus, state @ plus)
state = solve_dense(minus, (plus @ half).T).T
errors.append(np.max(abs(state-ref)))
orders = np.log2(np.array(errors[:-1])/errors[1:])
print(f"Finest-grid temporal order: {orders[-1]:.4f}")
assert abs(orders[-1]-2) < 0.01
fig, ax = plt.subplots(figsize=(7, 4), layout="constrained")
ax.loglog(end/steps, errors, "o-", label="ADI")
ax.loglog(end/steps, errors[-1]*(steps[-1]/steps)**2, "--", label="Quadratic reference")
ax.set(xlabel="Time step", ylabel="Maximum error relative to the spatially discrete mode")
ax.legend()
fig.savefig("numerics-adi-heat.png", dpi=170)
Output from the reference run
Finest-grid temporal order: 2.0003

Measure transport, time and splitting independently
A time-dependent transport–reaction problem can have noncommuting operators even on a periodic grid. Let \(Au=-c u_x,\ Bu=-k(x)u\). Direct differentiation gives \((AB-BA)u=c k'(x)u\). Expanding a product \(e^{hB}e^{hA}\) through \(h^2\) and subtracting \(e^{h(A+B)}\) leaves \(h^2(BA-AB)u/2\). Reversing the order reverses this leading defect. The symmetric composition \(e^{hA/2}e^{hB}e^{hA/2}\) cancels it, giving second-order global convergence for sufficiently smooth data and compatible boundaries.
An independent solution follows characteristics: \(u(x,t)=u_0(x-ct)\exp[-\int_0^t k(x-c(t-s))\,ds]\). For \(k=k_0+k_1\sin x\), the integral is \(k_0t+(k_1/c)[\cos(x-ct)-\cos x]\). Compare the split method first to a tightly integrated unsplit system on the same mesh, then to this continuum formula. Halve time at fixed mesh and halve the mesh at a suitably small time step. A single combined refinement cannot identify which contribution dominates.
How expensive is this factorisation?
On an \(m\)-by-\(m\) grid each half-step contains \(m\) tridiagonal systems of length \(m\). A tridiagonal factorisation and substitution lead to \(O(m^2)\) work per step. The small reference notebook deliberately uses the OneSimulation dense solver for each block of right-hand sides so the matrices can be inspected directly.
Tutorial on damping and noncommutation
Calculate the amplification of a strongly anisotropic mode
Work through the solution
With \(s\lambda_x=-10\) and \(s\lambda_y=-0.1\), the factors are \(-9/11\) and \(9/11\). Their product is \(-81/121\). The exact one-step decay is \(e^{-20.2}\), which is much smaller. Halve the time step until damping agrees with the resolution required.
Design a test where reversing the split should change nothing
Work through the solution
A constant reaction rate has \(k'=0\), so advection and reaction commute for periodic boundaries. With exact component updates the two orders agree at any time step. Change \(k\) to a sinusoid and use the order difference to expose the commutator.
Spatial discretisation and field equations · 7. Following the error from one reference triangle to an entire mesh
Derive a first-order energy error estimate and a second-order displacement estimate for a conforming linear triangular discretisation. Track the assumption on element shape at the point where it enters the proof.
Remove everything a linear element can reproduce
Let \(\widehat K\) be a fixed triangle and \(\widehat I\) its affine nodal interpolant. In two dimensions point evaluation is continuous on \(H^2(\widehat K)\), so \(\widehat I:H^2\to H^1\) is bounded. Choose an affine \(p\) to match the means of \(\nabla u\) and of \(u\) on the triangle. Apply the Poincaré inequality first to the two components of \(\nabla(u-p)\), then to \(u-p\). This bounds the whole \(H^2\) norm of \(u-p\) by a constant times the \(L^2\) norm of the second derivatives. Since \((I-\widehat I)p=0\),
This argument is the affine case of polynomial approximation by a seminorm. No constant in it depends on the eventual mesh. Choosing nodal values would require extra care for rougher solutions for which point evaluation is undefined.
Transform derivatives and area separately
Let \(F(\xi)=B\xi+b\) map the reference triangle onto \(K\). Physical gradients are \(B^{-T}\) times reference gradients. Pulling back second derivatives produces two factors of \(B\). The square-root determinant factors from integrating and undoing the map cancel in the resulting estimate:
A shape-regular family has uniformly bounded \(\|B\|\|B^{-1}\|\) and element diameter comparable to \(\|B\|\). Thus the right side is \(Ch_K|u|_{H^2(K)}\). For a triangle with legs \(h\) and \(h^2\) the general bound gives order one for its coefficient, since \(\|B^{-1}\|\simeq h^{-2}\). This shows where the guarantee is lost. Some thin triangles and specially oriented solutions still interpolate accurately.
Use Galerkin orthogonality to turn approximation into a PDE estimate
For homogeneous Dirichlet diffusion with \(0<\kappa_{\min}\le\kappa(x)\le\kappa_{\max}\), set \(a(v,w)=\int\kappa\nabla v\cdot\nabla w\). The conforming Galerkin solution satisfies \(a(u-u_h,v_h)=0\). Write \(e=u-u_h\). Then \(\|e\|_a^2=a(e,u-I_hu)\le\|e\|_a\|u-I_hu\|_a\). Summing squared local bounds gives \(\|e\|_a\le Ch\sqrt{\kappa_{\max}}|u|_{H^2}\). Here \(u\in H^2\), boundary conformity and accurate assembly are substantive assumptions.
For the mean-square error solve the dual problem \(a(v,z)=(v,e)\) with the same boundary conditions. If it satisfies the regularity estimate \(\|z\|_{H^2}\le C_{\rm reg}\|e\|_{L^2}\), then
Divide by \(\|e\|_{L^2}\) to obtain the extra power of \(h\). A reentrant corner or a coefficient interface can obstruct this regularity. Use the actual energy or output norm in the convergence study.
Why can a bad cell evade an affine patch test?
Every nonsingular triangle, including a very thin one, exactly reproduces an affine function. Such a patch tests assembly and transformation consistency. Curved test functions in several orientations are needed to expose geometry-dependent interpolation errors.

Tutorial on local and global accuracy
Compute the interpolation error on a right reference triangle
Work through the solution
For \(u=x^2\) on vertices \((0,0),(h,0),(0,h)\), \(I_Ku=h x\). The squared energy error for unit diffusion is \(\int_0^h(2x-h)^2(h-x)\,dx=h^4/6\). On a family of similar cells the local energy error scales like \(h^2\); the sum of squared errors over \(O(h^{-2})\) cells scales like \(h^2\).
Choose a mesh test for a collapsing angle
Work through the solution
Compare a uniformly refined mesh to one containing triangles with \(B\) singular values \(h,h^2\). Record the largest \(\|B\|\|B^{-1}\|\), solution and energy errors, and compare to the local scaled bounds. Growth of a bound alone does not prove a particular solution diverges. Rotate the test Hessian to probe whether the poor direction couples to curvature.
Brenner and Scott · finite element approximation
Change parameters · Following the error from one reference triangle to an entire mesh
Change one input at a time and compare the recalculated curves with the argument above. The browser evaluates this small model locally; the accompanying numerical values state its assumptions and reference checks. Reset restores the reference inputs, and the data can be downloaded as CSV.
Open this calculation with adjustable inputs
Download the executed OneSimulation notebook · Python source
The notebook reproduces the reference case and exposes the mesh or geometry parameters. Its saved output below comes from the actual OneSimulation solver.
"""Inspect shape-dependent interpolation error with a OneSimulation dense solve."""
import argparse
import matplotlib.pyplot as plt
import numpy as np
from onesim.numerics.linear.matrices.dense_linear_algebra import solve_dense
def experiment(base=0.5, ratio=0.25):
if base <= 0 or ratio <= 0:
raise ValueError("Base and altitude/base ratio must be positive")
altitude = base * ratio
vertices = np.array([[0., 0.], [base, 0.], [base/2, altitude]])
# The affine interpolation coefficients reproduce the three nodal values.
vandermonde = np.column_stack((np.ones(3), vertices))
coefficients = solve_dense(vandermonde, vertices[:, 0]**2)
expected = np.array([0., base, -base**2/(4*altitude)])
np.testing.assert_allclose(coefficients, expected, atol=2e-14)
gradient_error = np.sqrt(base*altitude/2 * (base**2/6 + base**4/(16*altitude**2)))
print(f"Affine coefficients: {coefficients}")
print(f"L2 norm of gradient error: {gradient_error:.8f}")
barycentric = np.array([(i/30, j/30) for i in range(31) for j in range(31-i)])
points = np.column_stack((base*(barycentric[:, 0]+barycentric[:, 1]/2), altitude*barycentric[:, 1]))
exact = points[:, 0]**2
linear = coefficients[0] + points @ coefficients[1:]
fig = plt.figure(figsize=(10, 4.4), layout="constrained")
ax = fig.add_subplot(121, projection="3d")
ax.plot_trisurf(points[:, 0], points[:, 1], exact, color="#a6c8be", alpha=.8)
for fraction in np.linspace(0, 1, 9):
y = altitude*fraction
x = np.linspace(base*fraction/2, base*(1-fraction/2), 40)
ax.plot(x, np.full_like(x, y), coefficients[0]+coefficients[1]*x+coefficients[2]*y,
color="#ad491d", lw=1)
ax.set(xlabel="x", ylabel="y", zlabel="Scalar field u", title="Exact surface and affine interpolant")
error = fig.add_subplot(122)
ratios = np.geomspace(.02, 1, 100)
error.loglog(ratios, base/(4*ratios), label="Spurious transverse gradient")
error.scatter(ratio, abs(coefficients[2]), color="#ad491d")
error.set(xlabel="Altitude / base", ylabel="Magnitude of transverse gradient")
error.legend()
fig.savefig("complete-numerics-triangle.png", dpi=170)
return coefficients, gradient_error
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base", type=float, default=.5)
parser.add_argument("--ratio", type=float, default=.25)
args, _ = parser.parse_known_args()
experiment(args.base, args.ratio)
plt.show()
Affine coefficients: [ 0. 0.5 -0.5] L2 norm of gradient error: 0.09547033

Spatial discretisation and field equations · 8. Which waves are allowed to enter a numerical boundary?
Diagonalise linear acoustics, impose one physical condition per incoming wave and compare diffusive and dispersive transport schemes on the same spatial Fourier mode.
Separate acoustic waves by their directions
For small perturbations in a uniform fluid, \(p_t+\rho c^2v_x=0,\ v_t+p_x/\rho=0\) with density \(\rho>0\), speed \(c>0\). Add and subtract \(\rho c\) times the second equation. The combinations \(w_\pm=p\pm\rho c v\) satisfy \(\partial_t w_\pm\pm c\,\partial_x w_\pm=0\). Reconstruct \(p=(w_++w_-)/2,\ v=(w_+-w_-)/(2\rho c)\). At the left boundary \(w_+\) enters and \(w_-\) leaves. These roles exchange at the right boundary.
For a rigid wall \(v=0\), set the incoming characteristic equal to the outgoing one. The reflected pressure has the same sign. At a pressure-release boundary \(p=0\), it has opposite sign. Prescribing \(p\) and \(v\) independently at the same boundary generally overspecifies a first-order system. For a diagonalizable hyperbolic matrix \(A=R\Lambda R^{-1}\) the same counting follows from \(R^{-1}u\), subject to independent boundary conditions on incoming components. Zero-speed or glancing modes require separate analysis.
Derive one amplitude and phase experiment for three methods
For scalar right-going \(u_t+a u_x=0\), set \(\nu=ah/\Delta x\). First-order upwind uses the upstream difference. Lax–Friedrichs replaces the central value by the average of its neighbours before taking the centred first derivative. Lax–Wendroff expands time to second order and uses \(u_{tt}=a^2u_{xx}\). With Fourier angle \(\theta=k\Delta x\), the three amplification factors are
G_W=1-i\nu\sin\theta+\nu^2(\cos\theta-1).
For \(0\le\nu\le1\) these are stable in the periodic discrete \(L^2\) norm. For the last factor direct expansion gives \(|G_W|^2=1-4\nu^2(1-\nu^2)\sin^4(\theta/2)\). The exact factor \(e^{-i\nu\theta}\) has modulus one. At \(\nu=1/2,\theta=\pi/2\), upwind gives \(0.5-0.5i\), Lax–Friedrichs gives \(-0.5i\) and Lax–Wendroff gives \(0.75-0.5i\). Their magnitudes and arguments distinguish loss of contrast from arrival-time error.
Transfer the calculation to both members of the system
On a uniform grid update \(w_+\) by a right-going scheme and \(w_-\) by its mirrored left-going counterpart. For first-order upwind the outgoing stencil at either wall uses only interior data. Supply the incoming value using the physical relation. For centred and second-order stencils, ghost values or one-sided closures must also approximate derivatives at the boundary with a compatible accuracy and stability. A periodic amplification test alone cannot certify them.
Why can a second-order scheme create negative overshoots?
In Lax–Wendroff the downstream coefficient \((\nu^2-\nu)/2\) is negative for \(0<\nu<1\). At a step discontinuity the update can leave the interval spanned by neighbouring data. Its Fourier stability bound controls a norm and does not imply a maximum principle.

Tutorial on waves in an acoustic tube
Calculate one update next to a marked step
Work through the solution
Take \(\nu=1/2\) and \(u_{j-1}=u_j=0,\ u_{j+1}=1\). Upwind gives zero, Lax–Friedrichs gives \(1/4\), Lax–Wendroff gives \(-1/8\). The exact right-going step has not reached this upstream cell centre.
Infer the reflected wave from a non-ideal termination
Work through the solution
At the right boundary impose \(p=Zv\). Substituting the characteristic pair gives \(w_-=(Z-\rho c)w_+/(Z+\rho c)\). A matched termination \(Z=\rho c\) transmits the wave with zero reflection. Verify the rigid and pressure-release limits before using this relation in ghost cells.
LeVeque · advection equations and hyperbolic systems
Change parameters · Which waves are allowed to enter a numerical boundary?
Change one input at a time and compare the recalculated curves with the argument above. The browser evaluates this small model locally; the accompanying numerical values state its assumptions and reference checks. Reset restores the reference inputs, and the data can be downloaded as CSV.
Boundary data, uniqueness and singular sources
Derive the continuous problem before assembling a discrete row. Test what happens to uniqueness, source flux and interface voltage under a change of boundary data.
- Vector calculus through flux, circulation and singular sources
- When do boundary measurements determine a unique electrostatic field?
- Green functions, the Poisson kernel and what a small electrode can influence
- Rectangular geometries, orthogonality and sources that drive individual modes
- Cylindrical geometry, coaxial boundaries and Bessel spectra
- A converged field solver can still give the wrong voltage
- Measure the capacitance of a continuously graded dielectric
- Is a computed screening layer resolved?
- What can a mesh measure about a point charge?
Heat, momentum and wave transport
Test the same spatial method on diffusion, a propagating pulse and an elastic mode. Compare dissipation, dispersion and boundary residuals on a common footing.
- How a moving wall sends momentum into a liquid
- Critical depth and the hydraulic jump
- Thermal diffusion and transient surface cooling
- A moving boundary in a freezing layer
- How a longitudinal pulse reflects from a change in rod section
- Why the frequencies of a bending beam are not equally spaced
- How a magnetic field relaxes into a finite conductor
- Posing an electromagnetic evolution problem
- Measure the phase speed of a numerical electromagnetic wave
- Action density, stress waves and the boundary that reflects them
- From binary collisions to the Boltzmann equation
- Transport coefficients from equilibrium fluctuations
Applied study
Discretise a boundary-value problem and separate mesh error from solver and sampling errors.
Replace a continuum balance by nodal equations
Suppose a scalar diffuses along a unit interval, with a fixed value at each end. The steady balance is \(-u''=f\) for constant unit diffusivity. At equally spaced interior nodes \(x_i=ih\), approximate the derivative at each face by the difference between its neighbouring values divided by \(h\). Subtracting the outgoing and incoming diffusive fluxes and dividing by cell width gives
The endpoints are known, leaving \(N-1\) interior unknowns for \(N\) intervals. Each interior flux appears once with each sign in neighbouring balances. Summing balances therefore leaves the net boundary flux and the total source. With variable diffusivity \(D\), multiply each face gradient by its face value of \(D\) before taking the difference.
Find the error made by a single stencil
Insert the exact values \(u(x_i-h)\) and \(u(x_i+h)\), expand both in Taylor series and add them. Odd terms cancel. The central second difference satisfies \(\delta_{xx}u=u''+h^2u^{(4)}/12+O(h^4)\) for sufficiently smooth \(u\). This local consistency calculation predicts the scale of the defect when the exact solution is inserted in the discrete equations.
Write the discrete problem \(A_hu_h=f_h\) and define \(\tau_h=A_hu_\star-f_h\) using exact nodal values \(u_\star\). Then \(A_h(u_\star-u_h)=\tau_h\). A stability bound on \(A_h^{-1}\), uniform in mesh size in the chosen norm, turns second-order consistency into second-order solution error. A tight iterative solve reduces the residual of \(A_hu_h=f_h\), but leaves \(\tau_h\) in place.
Use an exact sine mode to predict the discrete amplitude
Prescribe \(u(0)=u(1)=0\) and \(f(x)=\pi^2\sin(\pi x)\). The exact solution is
For its grid samples \(s_i=\sin(\pi ih)\), the sine addition formula yields
with \(\lambda_h=4\sin^2(\pi h/2)/h^2\). The right-hand side is \(\pi^2s\), so the discrete solution has the same nodal shape and amplitude \(\pi^2/\lambda_h\).
With four intervals, \(\lambda_h=64\sin^2(\pi/8)=9.3726\) and the numerical midspan value is 1.0530. The exact value is 1. The sign makes sense: the discrete stiffness of this mode is below \(\pi^2\), so the same load produces a larger amplitude. Expansion gives \(\pi^2/\lambda_h=1+\pi^2h^2/12+O(h^4)\), predicting a fourfold error reduction on refinement.
Problem class
Test a polynomial before trusting the mesh
Keep the homogeneous end values and choose \(u_\star=x(1-x)\). Derive \(f\), then predict the nodal error for any uniform mesh in exact arithmetic. Would this make a good test for measuring convergence order?
Show the calculation
Since \(u_\star''=-2\), use \(f=2\). The centred second difference of any quadratic equals its exact second derivative. The nodal vector therefore solves the discrete equations exactly. It is a useful stencil consistency check, but its zero leading error prevents a meaningful order measurement from a ratio of errors.
Manufacture a source for variable diffusion
On the unit square let \(D(x)=1+x\), \(u_\star=\sin(ax)\sin(ay)\), and \(a=m\pi\) for positive integer \(m\), using metre coordinates. What forcing makes \(-\nabla\cdot(D\nabla u)+2u=f\) hold with zero boundary values?
Show the calculation
Apply the product rule,
Here \(\Delta u_\star=-2a^2u_\star\) and \(D'=1\). Thus \(f=[2(1+x)a^2+2]u_\star-a\cos(ax)\sin(ay)\). Each boundary has a zero sine factor. Omitting \(D'u_x\) would produce a continuous modelling error that persists even when the mesh is refined.
OneSimulation laboratory
Measure spatial convergence on a known field
Compare recorded OneSimulation runs on this page. To test your own inputs, download the Python model and run the model in an activated OneSimulation environment.
The script solves the steady equation \(-\nabla\!\cdot[(1+x)\nabla u]+2u=f\) on the unit square by conservative flux differences and Jacobi-preconditioned CG. Set \(u=\sin(m\pi x)\sin(m\pi y)\) and obtain the source by substitution. The boundary values are zero on all four sides. Compare the maximum error at grid nodes with the solver’s relative residual. Refine both axes together, then raise the sine mode on the same 48-cell mesh to see how wavelength affects the error. Download the Python experiment · OneSimulation reaction–diffusion refinement study.
python partial-differential-equations.py
python partial-differential-equations.py --cells 48
python partial-differential-equations.py --cells 96
python partial-differential-equations.py --cells 48 --mode 2
| Cells per axis, mode | Interior unknowns | Max. nodal error | Relative residual |
|---|---|---|---|
| 24, 1 | 529 | 1.33345 × 10⁻³ | 9.79 × 10⁻¹¹ |
| 48, 1 | 2,209 | 3.33763 × 10⁻⁴ | 7.14 × 10⁻¹¹ |
| 96, 1 | 9,025 | 8.34283 × 10⁻⁵ | 4.21 × 10⁻¹¹ |
| 48, 2 | 2,209 | 1.41546 × 10⁻³ | 8.89 × 10⁻¹¹ |

At mode one the error falls by factors close to four while the number of interior unknowns roughly quadruples. On the same 48-cell mesh, mode two has half as many intervals per wavelength and a larger error. Both modes have small algebraic residuals. Mesh convergence is a property of the resolved field and its discretisation.
Change parameters · Change the laboratory inputs
Change one input at a time and compare the recalculated curves with the argument above. The browser evaluates this small model locally; the accompanying numerical values state its assumptions and reference checks. Reset restores the reference inputs, and the data can be downloaded as CSV.
Problem sheet 3 · Predict the error before making a finer grid
Notation and assumptions
Read each defining equation with its assumptions and units, then follow the link to the argument that gives the equation its meaning.
Compatibility condition
For minus the Laplacian of u equal to f with pure Neumann data, this integral condition is required. A constant still has to be fixed separately.
Derivation · Pure flux boundaries, compatibility and the missing constant
Conservative face flux
Use the same face flux with opposite orientations in neighbouring cells. Interior contributions then cancel in the global balance.
Courant number
For scalar advection this compares a transported distance with a cell width. An admissible range depends on the spatial method and time integrator jointly.
Numerical dispersion
A discretised wave can retain its amplitude and still propagate at the wrong speed. Compare phase and group errors over the actual resolved wavelengths.
Derivation · Why two finite-element wave solvers propagate the same mode at different speeds
Observed convergence order
Errors must refer to the same observable and norm. Cancellation, singular boundaries and a reference solution of insufficient accuracy can distort the result.
Weak form
Integration by parts lowers the derivative requirement. Essential and natural boundary data enter the discrete system differently.
Further reading
Compare stability and consistency for diffusion and advection using the same mesh. Use the accompanying examples to identify which discretisations preserve qualitative features of a solution. Randall J. LeVeque · Finite Difference Methods for Ordinary and Partial Differential Equations
Chapters 11–13 develop diffusion, advection and two-dimensional problems. Compare the largest operator eigenvalues before choosing an explicit time step. Driscoll and Braun · Fundamentals of Numerical Computation

