Algorithm Search⌘K

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
Properties
conservativedeterministicexplicitnot monotonenot tvd
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 Ut+F(U)x=0U_t + F(U)_x = 0, 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 FF with Jacobian A(U)=F′(U)A(U) = F'(U), grid values UjU_j at MM points xjx_j with spacing Δx\Delta x, a time step Δt\Delta t and a number of steps KK, approximate the solution of the hyperbolic conservation law Ut+F(U)x=0U_t + F(U)_x = 0 at time KΔtK\Delta t. The Courant number is ν=ΔtΔxmax⁡∣λp(U)∣\nu = \frac{\Delta t}{\Delta x}\max|\lambda_p(U)|, with λp\lambda_p the eigenvalues of AA. The boundary gives one ghost value on each side: periodic, or transmissive (a copy of the end value).

The algorithm

  1. MACCORMACK(U, Δx, Δt, K, F)
  2. 1for n ← 1 to K do
  3. 2for j ← 1 to M do U*_j ← U_j - (Δt/Δx)(F(U_(j+1)) - F(U_j)) ▷ predictor: forward difference
  4. 3for 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
  5. 4return U

Line L2 also computes the predictor at the left ghost point, because line L3 needs U0∗U^*_0. Line L3 can overwrite UjU_j in place, because it reads only its own old value UjU_j. The two lines together are a conservative scheme with the face flux

Hj+1/2=12(F(Uj+1)+F(Uj∗)),Ujn+1=Ujn−ΔtΔx(Hj+1/2−Hj−1/2).H_{j+1/2} = \tfrac12\big(F(U_{j+1}) + F(U^*_j)\big), \qquad U_j^{n+1} = U_j^n - \frac{\Delta t}{\Delta x}\big(H_{j+1/2} - H_{j-1/2}\big).

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 ut+ux=0u_t + u_x = 0 on 6 periodic points with Δx=1\Delta x = 1, Δt=12\Delta t = \frac12 (Courant number 12\frac12) and u=(1,1,1,0,0,0)u = (1, 1, 1, 0, 0, 0). The predictor is uj∗=uj−12(uj+1−uj)u^*_j = u_j - \frac12(u_{j+1} - u_j), which gives u∗=(1,1,32,0,0,−12)u^* = (1, 1, \frac32, 0, 0, -\frac12). The corrector gives

unew=(58, 1, 98, 38, 0, −18).u^{\text{new}} = \big(\tfrac58,\ 1,\ \tfrac98,\ \tfrac38,\ 0,\ -\tfrac18\big).

For example u3new=12(1+32)−14(32−1)=98u^{\text{new}}_3 = \frac12(1 + \frac32) - \frac14(\frac32 - 1) = \frac98. The Lax-Wendroff formula uj−ν2(uj+1−uj−1)+ν22(uj+1−2uj+uj−1)u_j - \frac{\nu}{2}(u_{j+1} - u_{j-1}) + \frac{\nu^2}{2}(u_{j+1} - 2u_j + u_{j-1}) gives the same six numbers. The sum is still 3, so the scheme conserves. But 98>1\frac98 > 1 and −18<0-\frac18 < 0, and the total variation grows from 2 to 52\frac52. This is the overshoot at a jump.

Second order on smooth data (measurement, with the code on this page). L1L^1 errors at t=0.3t = 0.3 for Burgers' equation with u0=0.5+0.25sin⁡2πxu_0 = 0.5 + 0.25\sin 2\pi x (smooth until t=2/π≈0.64t = 2/\pi \approx 0.64), and at t=0.25t = 0.25 for an Euler density wave ρ=1+0.2sin⁡2π(x−t)\rho = 1 + 0.2\sin 2\pi(x - t), u=1u = 1, p=1p = 1:

MM 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 Δx\Delta x is order 2.

Sod's shock tube (measurement). On 100 points in [0,1][0, 1] with transmissive ends, the plain scheme with Δt/Δx=0.2\Delta t/\Delta x = 0.2 gives a negative pressure next to the initial jump after 10 steps, and the run fails. With Δt/Δx=0.45\Delta t/\Delta x = 0.45 (Courant number about 0.99 for the fastest wave) it reaches t=0.2t = 0.2, but the pressure falls to 0.0871 below the right state 0.1, and the velocity overshoots to 0.9405 against the exact u∗=0.92745u^* = 0.92745. With the constant artificial viscosity 0.05 (Uj+1−2Uj+Uj−1)0.05\,(U_{j+1} - 2U_j + U_{j-1}) added after each step and Δt/Δx=0.4\Delta t/\Delta x = 0.4, the pressure stays positive, and the shock is at x=0.845x = 0.845 against the exact 0.5+1.75216×0.2=0.85040.5 + 1.75216 \times 0.2 = 0.8504, 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 F(U)=AUF(U) = AU with a constant matrix, one step equals the Lax-Wendroff method. A Taylor expansion shows that the local truncation error is O(Δx2)O(\Delta x^2) for smooth solutions at a fixed ratio Δt/Δx\Delta t/\Delta x. For linear advection, the amplification factor is g(θ)=1−iνsin⁡θ−ν2(1−cos⁡θ)g(\theta) = 1 - i\nu\sin\theta - \nu^2(1 - \cos\theta) with ∣g∣2=1−ν2(1−ν2)(1−cos⁡θ)2|g|^2 = 1 - \nu^2(1 - \nu^2)(1 - \cos\theta)^2, so the scheme is stable exactly when ∣ν∣≤1|\nu| \le 1. The coefficient of uj+1u_{j+1} is negative for 0<ν<10 < \nu < 1, 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 Ut+F(U)x=0U_t + F(U)_x = 0 with a smooth flux FF and Jacobian A(U)=F′(U)A(U) = F'(U). The grid has spacing Δx\Delta x, the time step is Δt\Delta t, and λ=Δt/Δx\lambda = \Delta t/\Delta x. One step of MACCORMACK computes, for every cell jj,

Uj∗=Uj−λ(F(Uj+1)−F(Uj))(line L2),Ujnew=12(Uj+Uj∗)−λ2(F(Uj∗)−F(Uj−1∗))(line L3).U^*_j = U_j - \lambda\big(F(U_{j+1}) - F(U_j)\big) \quad \text{(line L2)}, \qquad U^{\text{new}}_j = \tfrac12(U_j + U^*_j) - \tfrac{\lambda}{2}\big(F(U^*_j) - F(U^*_{j-1})\big) \quad \text{(line L3)}.

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 KK. Each step evaluates FF at 2M2M states (plus the ghost states) and does O(M)O(M) further arithmetic.

Lemma 1 (conservation form). Let Hj+1/2=12(F(Uj+1)+F(Uj∗))H_{j+1/2} = \frac12\big(F(U_{j+1}) + F(U^*_j)\big). Then Ujnew=Uj−λ(Hj+1/2−Hj−1/2)U^{\text{new}}_j = U_j - \lambda(H_{j+1/2} - H_{j-1/2}), and H(V,V)=F(V)H(V, V) = F(V) when all the arguments are equal to VV.

Proof. Insert Uj∗U^*_j in the first term of line L3:

Ujnew=Uj−λ2(F(Uj+1)−F(Uj))−λ2(F(Uj∗)−F(Uj−1∗))=Uj−λ(F(Uj+1)+F(Uj∗)2−F(Uj)+F(Uj−1∗)2).U^{\text{new}}_j = U_j - \tfrac{\lambda}{2}\big(F(U_{j+1}) - F(U_j)\big) - \tfrac{\lambda}{2}\big(F(U^*_j) - F(U^*_{j-1})\big) = U_j - \lambda\Big(\tfrac{F(U_{j+1}) + F(U^*_j)}{2} - \tfrac{F(U_j) + F(U^*_{j-1})}{2}\Big).

If Uj=Uj+1=VU_j = U_{j+1} = V, then Uj∗=VU^*_j = V and Hj+1/2=F(V)H_{j+1/2} = F(V). □\square

So with periodic boundaries ∑jUjnew=∑jUj\sum_jU^{\text{new}}_j = \sum_jU_j exactly, and by the Lax-Wendroff theorem, if the scheme converges boundedly almost everywhere as Δx→0\Delta x \to 0 with fixed λ\lambda, 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 F(U)=AUF(U) = AU with a constant matrix AA, one step equals the Lax-Wendroff method:

Ujnew=Uj−λ2A(Uj+1−Uj−1)+λ22A2(Uj+1−2Uj+Uj−1).U^{\text{new}}_j = U_j - \tfrac{\lambda}{2}A(U_{j+1} - U_{j-1}) + \tfrac{\lambda^2}{2}A^2(U_{j+1} - 2U_j + U_{j-1}).

Proof. Write δ+Vj=Vj+1−Vj\delta_+V_j = V_{j+1} - V_j and δ−Vj=Vj−Vj−1\delta_-V_j = V_j - V_{j-1}, which commute. Then U∗=U−λAδ+UU^* = U - \lambda A\delta_+U and δ−U∗=δ−U−λAδ−δ+U\delta_-U^* = \delta_-U - \lambda A\delta_-\delta_+U. So

Unew=U−λ2Aδ+U−λ2Aδ−U+λ22A2δ−δ+U,U^{\text{new}} = U - \tfrac{\lambda}{2}A\delta_+U - \tfrac{\lambda}{2}A\delta_-U + \tfrac{\lambda^2}{2}A^2\delta_-\delta_+U,

and δ++δ−\delta_+ + \delta_- is the central difference Uj+1−Uj−1U_{j+1} - U_{j-1}, while δ−δ+Uj=Uj+1−2Uj+Uj−1\delta_-\delta_+U_j = U_{j+1} - 2U_j + U_{j-1}. □\square

Theorem 1 (second order). Let uu be a smooth solution and λ\lambda fixed. Insert Uj=u(xj,tn)U_j = u(x_j, t_n) in one step. Then Ujnew=u(xj,tn+Δt)+O(Δx3)U^{\text{new}}_j = u(x_j, t_n + \Delta t) + O(\Delta x^3), so the local truncation error is O(Δx2)O(\Delta x^2).

Proof. Write k=Δtk = \Delta t, h=Δxh = \Delta x, D±D_\pm for the divided differences δ±/h\delta_\pm/h, and a=A(u)a = A(u). The predictor is the smooth grid function u∗=u−kD+F(u)u^* = u - kD_+F(u), so F(u∗)=F(u)−k a D+F(u)+O(k2)F(u^*) = F(u) - k\,a\,D_+F(u) + O(k^2), where the remainder is a smooth function of xx. Then D−D_- of the remainder is also O(k2)O(k^2), and

Unew=u−k2(D++D−)F(u)+k22D−(a D+F(u))+O(k3).U^{\text{new}} = u - \tfrac{k}{2}(D_+ + D_-)F(u) + \tfrac{k^2}{2}D_-\big(a\,D_+F(u)\big) + O(k^3).

Here 12(D++D−)F=Fx+O(h2)\frac12(D_+ + D_-)F = F_x + O(h^2) and D−(aD+F)=(aFx)x+O(h)D_-(aD_+F) = (aF_x)_x + O(h). The exact solution satisfies ut=−Fxu_t = -F_x and utt=−(Ft)x=−(aut)x=(aFx)xu_{tt} = -(F_t)_x = -(a u_t)_x = (aF_x)_x, so u(tn+k)=u−kFx+k22(aFx)x+O(k3)u(t_n + k) = u - kF_x + \frac{k^2}{2}(aF_x)_x + O(k^3). The difference is O(kh2)+O(k2h)+O(k3)=O(h3)O(kh^2) + O(k^2h) + O(k^3) = O(h^3) for fixed λ\lambda. □\square

Theorem 2 (linear stability). For ut+aux=0u_t + au_x = 0 with ν=aλ\nu = a\lambda on a periodic grid, the amplification factor is g(θ)=1−iνsin⁡θ−ν2(1−cos⁡θ)g(\theta) = 1 - i\nu\sin\theta - \nu^2(1 - \cos\theta), and ∣g(θ)∣≤1|g(\theta)| \le 1 for all θ\theta if and only if ∣ν∣≤1|\nu| \le 1.

Proof. By Lemma 2, insert Uj=eijθU_j = e^{ij\theta} in the Lax-Wendroff formula. With s=1−cos⁡θ∈[0,2]s = 1 - \cos\theta \in [0, 2] and sin⁡2θ=s(2−s)\sin^2\theta = s(2 - s),

∣g∣2=(1−ν2s)2+ν2s(2−s)=1−ν2(1−ν2)s2.|g|^2 = (1 - \nu^2s)^2 + \nu^2s(2 - s) = 1 - \nu^2(1 - \nu^2)s^2.

This is at most 1 for all ss exactly when ν2≤1\nu^2 \le 1. By the Lax equivalence theorem, the scheme then converges for this linear problem. □\square

Theorem 3 (not monotone, not TVD). For 0<ν<10 < \nu < 1 the scheme for linear advection is not monotone, and it can increase the total variation.

Proof. By Lemma 2, Ujnew=ν(1+ν)2Uj−1+(1−ν2)Uj−ν(1−ν)2Uj+1U^{\text{new}}_j = \frac{\nu(1 + \nu)}{2}U_{j-1} + (1 - \nu^2)U_j - \frac{\nu(1 - \nu)}{2}U_{j+1}, and the last coefficient is negative. So raising Uj+1U_{j+1} lowers UjnewU^{\text{new}}_j. A concrete case: with ν=12\nu = \frac12 and periodic data (1,1,1,0,0,0)(1, 1, 1, 0, 0, 0), one step gives (58,1,98,38,0,−18)(\frac58, 1, \frac98, \frac38, 0, -\frac18). The new values leave the range [0,1][0, 1], and the total variation grows from 22 to 52\frac52. □\square

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. ■\blacksquare

Complexity

Theorem: each step evaluates the flux at the MM grid values and at the MM predicted values, plus the ghost points, and does O(M)O(M) further arithmetic. So KK steps cost O(KM)O(KM) time. The memory is the solution and one predictor array, O(M)O(M). For a fixed final time TT, the CFL condition gives K≥Tmax⁡∣λp∣/ΔxK \ge T\max|\lambda_p|/\Delta x, so K=Θ(M)K = \Theta(M) and the total cost is Θ(M2)\Theta(M^2) 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 ∣ν∣≤1|\nu| \le 1 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 ∣u∣+c|u| + c, 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.

maccormack_method.pyI0RawGitHub
# 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

  1. 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
  2. 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)
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
  • a full proof of evaluations.worst
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example