Algorithmintro
MacCormack method
Also called MacCormack scheme.
A two-step predictor-corrector with forward then backward differences, second order and equal to Lax-Wendroff on linear problems.
- Time
- O(K M) worst
- Space
- O(M) extra
- Counts
- evaluations 2 K (M + 2) worst
- Where
- K = the number of time steps; M = the number of grid points
- Model
- Real RAM
- Properties
- conservativedeterministicexplicitnot monotonenot tvd
- Evidence
- Proof sketchCode in 1 languages
- Origin
- R. W. MacCormack, 1969
The MacCormack method moves a quantity such as density, momentum or energy along a 1D grid by one time step in two passes. The predictor pass makes a first guess from the flux differences to the right of each point. The corrector pass uses the flux differences of that guess to the left, and averages the result with the old value. It is a finite difference scheme for a conservation law , second order in space and time, and for a linear flux it gives the same numbers as the Lax-Wendroff method. The unconditionally stable MacCormack method of fluid animation has the same name but is a different scheme: it traces semi-Lagrangian advection forward and back and corrects with half the error. Compared with that graphics scheme, this one is written in conservation form, so it keeps the total mass, momentum and energy exactly and moves shocks at the correct speed, but it is explicit and is stable only when the Courant number is at most 1. It is not TVD, and without added viscosity it oscillates at shocks.
In plain words
Think of a row of points along a tube, each with an amount of gas. To advance one time step, first look to the right of each point: compare what flows through the right neighbour with what flows through the point itself, and make a first guess of the new amount. Then look to the left: do the same comparison on the guesses, against the left neighbour. The new amount is the average of the old amount and the corrected guess. Each pass alone is crude and leans to one side. Together the two leanings cancel, and the result is accurate for smooth flow. All the changes are written as flows through the gaps between points, so nothing is lost or created. At a sudden jump the method makes small ripples, so it needs some extra smoothing there.
The problem
Given a flux with Jacobian , grid values at points with spacing , a time step and a number of steps , approximate the solution of the hyperbolic conservation law at time . The Courant number is , with the eigenvalues of . The boundary gives one ghost value on each side: periodic, or transmissive (a copy of the end value).
The algorithm
MACCORMACK(U, Δx, Δt, K, F)- 1
for n ← 1 to K do - 2
for j ← 1 to M do U*_j ← U_j - (Δt/Δx)(F(U_(j+1)) - F(U_j)) ▷ predictor: forward difference - 3
for j ← 1 to M do U_j ← (U_j + U*_j)/2 - (Δt/(2Δx))(F(U*_j) - F(U*_(j-1))) ▷ corrector: backward difference - 4
return U
Line L2 also computes the predictor at the left ghost point, because line L3 needs . Line L3 can overwrite in place, because it reads only its own old value . The two lines together are a conservative scheme with the face flux
The order of the two differences can be swapped (backward then forward). Many codes alternate the order from step to step, so that the one-sided bias does not build up.
Example
One step by hand. Take on 6 periodic points with , (Courant number ) and . The predictor is , which gives . The corrector gives
For example . The Lax-Wendroff formula gives the same six numbers. The sum is still 3, so the scheme conserves. But and , and the total variation grows from 2 to . This is the overshoot at a jump.
Second order on smooth data (measurement, with the code on this page). errors at for Burgers' equation with (smooth until ), and at for an Euler density wave , , :
| Burgers error | ratio | Euler density error | ratio | |
|---|---|---|---|---|
| 40 | 9.861e-4 | 7.939e-4 | ||
| 80 | 2.517e-4 | 3.92 | 1.987e-4 | 3.99 |
| 160 | 6.326e-5 | 3.98 | 4.970e-5 | 4.00 |
| 320 | 1.586e-5 | 3.99 | 1.243e-5 | 4.00 |
A ratio of 4 per halving of is order 2.
Sod's shock tube (measurement). On 100 points in with transmissive ends, the plain scheme with gives a negative pressure next to the initial jump after 10 steps, and the run fails. With (Courant number about 0.99 for the fastest wave) it reaches , but the pressure falls to 0.0871 below the right state 0.1, and the velocity overshoots to 0.9405 against the exact . With the constant artificial viscosity added after each step and , the pressure stays positive, and the shock is at against the exact , within one grid spacing.
Correctness
The proof is in proofs/correctness.md. Theorem: the scheme has the conservative form above with a consistent face flux, so with periodic boundaries the sum of the values does not change. For with a constant matrix, one step equals the Lax-Wendroff method. A Taylor expansion shows that the local truncation error is for smooth solutions at a fixed ratio . For linear advection, the amplification factor is with , so the scheme is stable exactly when . The coefficient of is negative for , so the scheme is not monotone. By the Lax-Wendroff theorem, if the scheme converges, the limit is a weak solution. Nothing guarantees that it converges at shocks, or that the limit is the entropy solution.
Proof: MacCormack's scheme is conservative, consistent and second order, and it is not monotonefull
Setting. The law is with a smooth flux and Jacobian . The grid has spacing , the time step is , and . One step of MACCORMACK computes, for every cell ,
The neighbours of the end cells come from the boundary condition (periodic or transmissive ghost cells).
Termination. The loop of line L1 runs the given number of steps . Each step evaluates at states (plus the ghost states) and does further arithmetic.
Lemma 1 (conservation form). Let . Then , and when all the arguments are equal to .
Proof. Insert in the first term of line L3:
If , then and .
So with periodic boundaries exactly, and by the Lax-Wendroff theorem, if the scheme converges boundedly almost everywhere as with fixed , the limit is a weak solution, so its shocks move at the Rankine-Hugoniot speed. The theorem does not say that the scheme converges, or that the limit is the entropy solution.
Lemma 2 (linear systems). If with a constant matrix , one step equals the Lax-Wendroff method:
Proof. Write and , which commute. Then and . So
and is the central difference , while .
Theorem 1 (second order). Let be a smooth solution and fixed. Insert in one step. Then , so the local truncation error is .
Proof. Write , , for the divided differences , and . The predictor is the smooth grid function , so , where the remainder is a smooth function of . Then of the remainder is also , and
Here and . The exact solution satisfies and , so . The difference is for fixed .
Theorem 2 (linear stability). For with on a periodic grid, the amplification factor is , and for all if and only if .
Proof. By Lemma 2, insert in the Lax-Wendroff formula. With and ,
This is at most 1 for all exactly when . By the Lax equivalence theorem, the scheme then converges for this linear problem.
Theorem 3 (not monotone, not TVD). For the scheme for linear advection is not monotone, and it can increase the total variation.
Proof. By Lemma 2, , and the last coefficient is negative. So raising lowers . A concrete case: with and periodic data , one step gives . The new values leave the range , and the total variation grows from to .
Theorem 3 agrees with Godunov's order barrier: a linear scheme that is second order cannot be monotone. For a nonlinear flux the scheme is also not TVD; near a shock it gives oscillations unless viscosity is added.
Complexity
Theorem: each step evaluates the flux at the grid values and at the predicted values, plus the ghost points, and does further arithmetic. So steps cost time. The memory is the solution and one predictor array, . For a fixed final time , the CFL condition gives , so and the total cost is in 1D.
Properties
- Conservative and consistent. Shocks, if they are captured, move at the Rankine-Hugoniot speed.
- Second order in space and time for smooth solutions.
- Equal to Lax-Wendroff for linear constant-coefficient systems. For a nonlinear flux it is a different scheme, and it needs no Jacobian matrix.
- Stable for in the linear analysis.
- Not monotone and not TVD. By Godunov's order barrier, a linear second-order scheme cannot be monotone.
- Not symmetric. The forward predictor and the backward corrector give a one-sided bias; the results depend on the direction of the waves.
Variants and improvements
- Swapped or alternating order. Backward predictor and forward corrector, or an alternation from step to step.
- Artificial viscosity. A second-difference term, often scaled by a pressure switch, damps the oscillations at shocks. A constant coefficient makes the scheme first order.
- TVD and flux-corrected forms. Adding a limited dissipation term gives a TVD MacCormack scheme. See flux limiter methods and total variation diminishing.
- Multidimensional and viscous flows. Directional splitting, or the unsplit form with predictor and corrector in each direction. MacCormack's later implicit and hybrid versions are for the compressible Navier-Stokes equations.
- Graphics. The unconditionally stable MacCormack method is a semi-Lagrangian advection scheme, not this one.
When to use it
Use it for smooth compressible flows, for teaching, and for problems where shocks are weak and a little artificial viscosity is acceptable. It is simple, it needs only flux evaluations, and it is second order. For strong shocks use a Godunov-type scheme with a limiter, such as the MUSCL scheme or a WENO scheme with SSP Runge-Kutta time steps.
Pitfalls
- No dissipation at shocks. The plain scheme oscillates at shocks and can give negative pressure or density. Add artificial viscosity or a limiter.
- The time step. The Courant number uses the fastest wave speed , which can grow during the run. Compute it at every step.
- Point values, not cell averages. The scheme is written for point values on a grid. As a finite volume scheme it has the same form, but the initial data and the errors must then use cell averages.
- The boundary. The predictor at the last point uses a neighbour outside the grid, and the corrector at the first point uses a predictor outside it. Both need ghost values.
- The graphics name. Do not confuse it with the unconditionally stable MacCormack method of fluid animation.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maccormack-method/. The authors are listed in prov/6EZVM9.jsonl.
"""MacCormack's predictor-corrector scheme for U_t + F(U)_x = 0 on a uniform grid.
Each grid value is a state: a number for a scalar law, or a tuple for a system.
The arithmetic is generic, so Fraction data give exact results. The boundary is
periodic or transmissive (one ghost cell that copies the end value).
"""
def _as_tuple(v):
return tuple(v) if isinstance(v, (tuple, list)) else (v,)
def _extend(u: list, bc: str) -> list:
if bc == "periodic":
return [u[-1]] + u + [u[0]]
if bc == "transmissive":
return [u[0]] + u + [u[-1]]
raise ValueError("bc must be 'periodic' or 'transmissive'")
def _predict(ext: list, flux, lam):
f = [flux(v) for v in ext]
# predictor: forward difference, for the ghost cell on the left and the M cells
pred = [tuple(a - lam * (b - c) for a, b, c in zip(ext[i], f[i + 1], f[i])) for i in range(len(ext) - 1)]
return f, pred
def maccormack_step(u: list, flux, lam, bc: str = "periodic") -> list:
"""One step with lam = dt / dx. States and fluxes are tuples of equal length."""
ext = _extend(u, bc)
f, pred = _predict(ext, flux, lam) # @line L2
fp = [flux(v) for v in pred]
# corrector: backward difference on the predicted values, then the average
return [
tuple((a + b) / 2 - lam * (c - d) / 2 for a, b, c, d in zip(ext[i], pred[i], fp[i], fp[i - 1])) # @line L3
for i in range(1, len(ext) - 1)
]
def numerical_flux(u: list, flux, lam, bc: str = "periodic") -> list:
"""The M + 1 face fluxes H = (F(U_right) + F(U*_left)) / 2. H[j] is on the left face of cell j and H[M] on the right end."""
ext = _extend(u, bc)
f, pred = _predict(ext, flux, lam)
return [tuple((b + c) / 2 for b, c in zip(f[i + 1], flux(pred[i]))) for i in range(len(ext) - 1)]
def maccormack(u0: list, flux, dx, dt, steps: int, bc: str = "periodic", visc=0) -> list:
"""Run the given number of steps. Scalar data and a scalar flux are accepted and returned as scalars.
visc > 0 adds visc * (U_(j+1) - 2 U_j + U_(j-1)) of the old values after each step, a constant
artificial viscosity in conservation form. It damps the oscillations at shocks and makes the scheme
first order. visc = 0 is the plain scheme.
"""
scalar = not isinstance(u0[0], (tuple, list))
u = [_as_tuple(v) for v in u0]
vflux = (lambda v: (flux(v[0]),)) if scalar else (lambda v: _as_tuple(flux(v)))
lam = dt / dx
for _ in range(steps): # @line L1
new = maccormack_step(u, vflux, lam, bc)
if visc:
e = _extend(u, bc)
new = [tuple(a + visc * (b - 2 * c + d) for a, b, c, d in zip(new[j], e[j + 2], e[j + 1], e[j])) for j in range(len(u))]
u = new
return [v[0] for v in u] if scalar else u # @line L4
test_maccormack_method.py 141 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maccormack-method/. The authors are listed in prov/6EZVM9.jsonl.
import cmath
import math
import random
from fractions import Fraction as Fr
from maccormack_method import maccormack, maccormack_step, numerical_flux
G = 1.4
def lax_wendroff_advection(u, nu):
"""Independent oracle: the Lax-Wendroff scheme for u_t + a u_x = 0 with nu = a dt / dx, periodic."""
m = len(u)
return [
u[j] - nu / 2 * (u[(j + 1) % m] - u[j - 1]) + nu * nu / 2 * (u[(j + 1) % m] - 2 * u[j] + u[j - 1])
for j in range(m)
]
def total_variation(u):
return sum(abs(u[j] - u[j - 1]) for j in range(len(u)))
def euler_flux(w):
rho, mom, e = w
u = mom / rho
p = (G - 1) * (e - mom * u / 2)
return (mom, mom * u + p, u * (e + p))
def test_equals_lax_wendroff_on_linear_advection() -> None:
rng = random.Random(3)
for a, lam in ((Fr(1), Fr(1, 2)), (Fr(-1, 2), Fr(3, 4)), (Fr(2), Fr(2, 5))):
u = [Fr(rng.randint(-9, 9), rng.randint(1, 5)) for _ in range(11)]
v = list(u)
for _ in range(5):
v = lax_wendroff_advection(v, a * lam)
assert maccormack(u, lambda x: a * x, Fr(1), lam, 5) == v
def test_hand_example_overshoots() -> None:
u = [Fr(1)] * 3 + [Fr(0)] * 3
v = maccormack(u, lambda x: x, Fr(1), Fr(1, 2), 1)
assert v == [Fr(5, 8), Fr(1), Fr(9, 8), Fr(3, 8), Fr(0), Fr(-1, 8)]
assert total_variation(u) == 2 and total_variation(v) == Fr(5, 2)
def test_courant_number_one_is_an_exact_shift() -> None:
u = [Fr(k * k % 7) for k in range(9)]
assert maccormack(u, lambda x: x, Fr(1), Fr(1), 1) == [u[j - 1] for j in range(9)]
def test_amplification_factor() -> None:
m, k = 16, 3
theta = 2 * math.pi * k / m
for nu in (0.3, 0.8, 1.0, 1.1):
u = [cmath.exp(1j * j * theta) for j in range(m)]
v = maccormack(u, lambda x: nu * x, 1.0, 1.0, 1)
g = 1 - 1j * nu * math.sin(theta) - nu * nu * (1 - math.cos(theta))
assert all(abs(v[j] - g * u[j]) < 1e-12 for j in range(m))
assert (abs(g) <= 1 + 1e-12) == (nu <= 1)
def test_conservation_form_is_exact() -> None:
rng = random.Random(5)
lam = Fr(1, 3)
for bc in ("periodic", "transmissive"):
u = [(Fr(rng.randint(-6, 6), 4),) for _ in range(9)]
flux = lambda v: (v[0] * v[0] / 2,)
new = maccormack_step(u, flux, lam, bc)
h = numerical_flux(u, flux, lam, bc)
assert all(new[j][0] == u[j][0] - lam * (h[j + 1][0] - h[j][0]) for j in range(9))
if bc == "periodic":
assert sum(v[0] for v in new) == sum(v[0] for v in u)
def burgers_exact(x, t):
u0 = lambda y: 0.5 + 0.25 * math.sin(2 * math.pi * y)
du0 = lambda y: 0.5 * math.pi * math.cos(2 * math.pi * y)
u = u0(x)
for _ in range(30):
u -= (u - u0(x - u * t)) / (1 + du0(x - u * t) * t)
return u
def test_second_order_on_smooth_burgers() -> None:
t, errs = 0.3, []
for m in (40, 80, 160):
dx = 1 / m
n = round(t / (0.4 * dx))
u = maccormack([0.5 + 0.25 * math.sin(2 * math.pi * j * dx) for j in range(m)], lambda v: v * v / 2, dx, t / n, n)
errs.append(dx * sum(abs(u[j] - burgers_exact(j * dx, t)) for j in range(m)))
assert errs[0] / errs[1] > 3.7 and errs[1] / errs[2] > 3.8
def test_second_order_on_an_euler_density_wave() -> None:
t, errs = 0.25, []
for m in (40, 80, 160):
dx = 1 / m
n = round(t / (0.4 * dx / 2.2))
w = []
for j in range(m):
rho = 1 + 0.2 * math.sin(2 * math.pi * j * dx)
w.append((rho, rho, 1 / (G - 1) + rho / 2))
w = maccormack(w, euler_flux, dx, t / n, n)
errs.append(dx * sum(abs(w[j][0] - 1 - 0.2 * math.sin(2 * math.pi * (j * dx - t))) for j in range(m)))
assert errs[0] / errs[1] > 3.8 and errs[1] / errs[2] > 3.9
def sod(m):
w = []
for j in range(m):
rho, p = (1.0, 1.0) if (j + 0.5) / m < 0.5 else (0.125, 0.1)
w.append((rho, 0.0, p / (G - 1)))
return w
def pressures(w):
return [(G - 1) * (e - mom * mom / (2 * rho)) for rho, mom, e in w]
def test_sod_without_viscosity_loses_positivity() -> None:
m = 100
w = sod(m)
for _ in range(10):
w = maccormack(w, euler_flux, 1 / m, 0.2 / m, 1, bc="transmissive")
assert min(pressures(w)) < 0
def test_sod_with_viscosity_puts_the_shock_in_the_right_place() -> None:
m, lam, t = 100, 0.4, 0.2
n = round(t / (lam / m))
w = maccormack(sod(m), euler_flux, 1 / m, t / n, n, bc="transmissive", visc=0.05)
assert min(pressures(w)) > 0
# The exact shock is at 0.5 + 1.75216 t, between rho = 0.26557 and rho = 0.125.
mid = (0.26557 + 0.125) / 2
cross = next((j + 0.5) / m for j in range(m - 1, 0, -1) if w[j][0] > mid)
assert abs(cross - (0.5 + 1.75216 * t)) < 3 / m
History
MacCormack (1969) introduced the predictor-corrector scheme in an AIAA paper on hypervelocity impact cratering; the Journal of Spacecraft and Rockets reprinted the paper in 2003. The scheme is a variant of the two-step Lax-Wendroff schemes of the 1960s that needs no Jacobian. It was a standard method for compressible flow computation in aerodynamics in the 1970s and 1980s, before Godunov-type upwind schemes replaced it for flows with strong shocks.
References
- R. W. MacCormack, The effect of viscosity in hypervelocity impact cratering, Journal of Spacecraft and Rockets 40 (2003) 757-763, a reprint of AIAA Paper 69-354 (1969), the predictor-corrector difference scheme
- Randall J. LeVeque, Finite Volume Methods for Hyperbolic Problems, Cambridge University Press, 2002, Section 6.1 (the Lax-Wendroff method), Section 12.9 (the importance of conservation form), Section 12.10 (the Lax-Wendroff theorem)
- P. D. Lax and B. Wendroff, Systems of conservation laws, Communications on Pure and Applied Mathematics 13 (1960) 217-237, the limit of a convergent conservative scheme is a weak solution
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 6EZVM9 Edit this page History Report an error Markdown