Module contents
Lesson 8 of 27Advanced 115 min

Finite differences II: hyperbolic equations, CFL and finite volumes

Study transport and nonlinear conservation laws through characteristics, CFL, numerical diffusion and dispersion, conservative finite volumes and TVD-limited Godunov methods.

After this lesson you can

  • State CFL as a necessary domain-of-dependence condition and apply it to choose Δt.
  • Derive modified equations for upwind and Lax–Wendroff and predict numerical diffusion or dispersion.
  • Formulate a conservative finite-volume scheme and solve Burgers Riemann problems.
  • Explain Godunov's theorem and construct a TVD-limited MUSCL scheme.
  • Simulate traffic and shallow-water shocks and rarefactions with mass conservation.

Before you start

Information travels

A disturbance in a channel, a traffic front or a pressure wave does not instantly affect the whole domain. Propagation speeds determine which data can influence a solution. Increasing arithmetic precision cannot fix a mesh that cannot transmit that information in one step. Start from the transport equation ut+aux=0u_t+a u_x=0 with a>0a>0: the characteristic ending at (x,t)(x,t) comes from x−atx-at and carries the value of uu unchanged.

InteractiveCharacteristic and numerical cone

Blue: three-point stencil dependence; red: characteristic.

0.7
Maximum absolute value after 20 steps0.987
The blue region represents dependence of a three-point stencil over one unit of time; the red line is the physical characteristic. Change the Courant number. The right panel applies 20 periodic upwind steps to a square wave: above 1 growing oscillations appear.

The CFL condition requires the numerical domain of dependence to contain the physical one under refinement for a local scheme to converge for general data. For a stencil reaching one cell per step and advection at speed aa, this requires ∣a∣Δt/Δx≤1|a|\Delta t/\Delta x\le1. It is necessary, not sufficient: unstable schemes can satisfy it. Von Neumann stability analyzes mode amplification for linear schemes with constant coefficients; it does not prove absence of oscillations near a shock.

Three approximations to the same translation

With ν=aΔt/Δx\nu=a\Delta t/\Delta x, upwind for a>0a>0 uses

ujn+1=ujn−ν(ujn−uj−1n).u_j^{n+1}=u_j^n-\nu(u_j^n-u_{j-1}^n).

It is a convex combination of uju_j and uj−1u_{j-1} if 0≤ν≤10\le\nu\le1: it creates no new extrema in that step. Lax–Friedrichs replaces the central value with the neighbor average; Lax–Wendroff adds the centered second-order correction,

ujn+1=ujn−ν2(uj+1n−uj−1n)+ν22(uj+1n−2ujn+uj−1n).u_j^{n+1}=u_j^n-\frac{\nu}{2}(u_{j+1}^n-u_{j-1}^n) +\frac{\nu^2}{2}(u_{j+1}^n-2u_j^n+u_{j-1}^n).

For constant advection all three are stable in the corresponding CFL range, but their errors differ. The upwind and Lax–Wendroff family shows the diffusion–dispersion trade-off that matters when transporting an edge.

Lax–Friedrichs writes ujn+1=(uj−1n+uj+1n)/2−ν(uj+1n−uj−1n)/2u_j^{n+1}=(u_{j-1}^n+u_{j+1}^n)/2-\nu(u_{j+1}^n-u_{j-1}^n)/2. For a mode eijθe^{ij\theta}, the respective amplification factors of upwind, Lax–Friedrichs and Lax–Wendroff are

GU=1−ν(1−e−iθ),GLF=cos⁡θ−iνsin⁡θ,GLW=1−iνsin⁡θ+ν2(cos⁡θ−1).G_{\mathrm U}=1-\nu(1-e^{-i\theta}),\quad G_{\mathrm{LF}}=\cos\theta-i\nu\sin\theta,\quad G_{\mathrm{LW}}=1-i\nu\sin\theta+\nu^2(\cos\theta-1).

Requiring ∣G∣≤1|G|\le1 for every θ\theta gives 0≤ν≤10\le\nu\le1 for this upwind scheme and ∣ν∣≤1|\nu|\le1 for the other two. Magnitude measures amplification, but the argument of GG measures phase displacement: a magnitude bound does not prevent frequencies traveling at different speeds. Beam–Warming is another second-order scheme, biased toward the inflow side; it can also oscillate at jumps.

InteractiveA transported square wave
  • Numerical
  • Exact averages
120
Minimum0.000
Maximum0.953
Revolutions0.84
Compare upwind, Lax–Wendroff, Beam–Warming and MUSCL. The discontinuous reference consists of exact cell averages of the periodic translation; observe minima and maxima as steps increase. Change the limiter in MUSCL.

The modified equation explains these signatures. For a smooth solution and Δt\Delta t proportional to Δx\Delta x, Taylor expansion and ut=−auxu_t=-au_x, utt=a2uxxu_{tt}=a^2u_{xx} give, for upwind,

ut+aux=aΔx2(1−ν)uxx+O(Δx2).u_t+a u_x=\frac{a\Delta x}{2}(1-\nu)u_{xx}+\bigO(\Delta x^2).

The positive coefficient in 0<ν<10<\nu<1 acts as numerical viscosity. For Lax–Wendroff the leading term is aΔx2(ν2−1)uxxx/6a\Delta x^2(\nu^2-1)u_{xxx}/6, dispersive in character. The expansion assumes smoothness and is not a pointwise proof at a discontinuity: there it helps interpret trends, not guarantee a bound. Truncation error and consistency are insufficient without stability; the Lax equivalence theorem concerns well-posed linear problems under its hypotheses.

To recover viscosity without memorizing it, substitute ujn+1=u+Δtut+12Δt2utt+⋯u_j^{n+1}=u+\Delta t u_t+\tfrac12\Delta t^2u_{tt}+\cdots and uj−1n=u−Δxux+12Δx2uxx+⋯u_{j-1}^n=u-\Delta x u_x+\tfrac12\Delta x^2u_{xx}+\cdots into upwind. After dividing by Δt\Delta t this leaves ut+aux=(aΔx−a2Δt)uxx/2+⋯u_t+au_x=(a\Delta x-a^2\Delta t)u_{xx}/2+\cdots. The factor a2Δta^2\Delta t comes from the time expansion and explains why leading viscosity vanishes when ν=1\nu=1: then the scheme copies exactly one cell to the right per step for this equation.

Dispersion affects phase: components of different frequencies no longer travel at the same speed. A square wave can therefore develop overshoots even if ∣G∣≤1|G|\le1. Stability prevents unlimited mode growth in the analyzed norm; it does not turn update coefficients into positive weights. A visual result within the physical range is a useful check, but not a proof of monotonicity for all inputs.

Shocks, entropy and traffic

For a law ut+f(u)x=0u_t+f(u)_x=0, integrating across a moving front gives the Rankine–Hugoniot condition s(uR−uL)=f(uR)−f(uL)s(u_R-u_L)=f(u_R)-f(u_L). In Burgers f(u)=u2/2f(u)=u^2/2, so s=(uL+uR)/2s=(u_L+u_R)/2 when states differ. For an initial jump at x=0x=0, characteristics have speed f′(u)=uf'(u)=u: if uL>uRu_L>u_R they converge and the shock satisfies uL>s>uRu_L>s>u_R. If uL<uRu_L<u_R, they separate and a rarefaction appears with u=x/tu=x/t between both speeds.

A weak solution may not be unique. The entropy condition selects the admissible solution; for convex Burgers the shock above satisfies the Lax condition and an expansion shock does not. Derivations and examples in the Clawpack Riemann book show why jump sign changes the pattern. Form uuxuu_x is equivalent to (u2/2)x(u^2/2)_x only when uu is sufficiently smooth: a nonconservative discretization can converge to a front with incorrect speed.

The jump rule follows by tracking an interval enclosing the front and letting its width tend to zero. Mass change from interval movement balances the difference of fluxes at its endpoints. In example uL=2u_L=2, uR=0u_R=0, left flux is 2 and right flux 0: the front moves at speed 1, between characteristic speeds 2 and 0. Reversing states would give an expansion shock also satisfying algebraic balance, but not entropy; balance is necessary and does not alone select the physical solution.

In LWR traffic, ρt+[ρ(1−ρ)]x=0\rho_t+[\rho(1-\rho)]_x=0 uses density normalized between 0 and 1. The flux is concave and characteristic speed is 1−2ρ1-2\rho. Unlike Burgers, an upward density jump produces a shock. In the figure compare a Riemann jump or draw a profile: extended characteristic lines cease to describe a classical solution when they cross.

InteractiveTraffic jam and characteristics
  • Godunov, averages
  • Riemann, point value

Lines are characteristics extended from the initial profile; after crossing they do not represent a classical solution. The numerical curve uses finite volumes.

Initial state
0.20
0.80
60
Time0.200
Regimeshock
In Riemann mode change densities and compare Godunov averages with the exact point value. In profile mode drag the five densities and observe characteristics drawn from the initial state crossing; the numerical curve continues as a conservative solution.

One flux per face, one mass

The finite-volume method evolves the average uˉj\bar u_j in each cell. Integrating balance in it and approximating face fluxes gives

uˉjn+1=uˉjn−ΔtΔx(Fj+1/2−Fj−1/2).\bar u_j^{n+1}=\bar u_j^n-\frac{\Delta t}{\Delta x}(F_{j+1/2}-F_{j-1/2}).

Summing over cells cancels interior fluxes exactly: only boundary fluxes remain. In a periodic domain the sum of averages is conserved up to rounding. This identity holds regardless of solution smoothness; it is why neighboring cells share one flux evaluation.

On a mesh of NN cells, multiply each update by Δx\Delta x and sum: Mn+1−Mn=−Δt(FN+1/2−F1/2)M^{n+1}-M^n=-\Delta t(F_{N+1/2}-F_{1/2}). Each cell need not conserve its own mass; mass is exchanged with neighbors. For free outflow, the two boundary fluxes may differ and mass must change according to that formula. For periodic boundaries, both faces represent the same interface and their fluxes agree. A check imposing constant mass with an open boundary could reject a correct simulation.

The Godunov flux solves the Riemann problem formed by states on both sides and evaluates ff at the interface. For Burgers, a rarefaction crossing zero has zero flux; an approximation always choosing an outer state can select a non-entropic shock. Rusanov uses a bound α\alpha on characteristic speeds:

FR(uL,uR)=f(uL)+f(uR)2−α2(uR−uL).F_{\mathrm R}(u_L,u_R)=\frac{f(u_L)+f(u_R)}2-\frac{\alpha}{2}(u_R-u_L).

HLL uses two bounds sL≤0≤sRs_L\le0\le s_R and approximates all waves by an intermediate state:

FHLL=sRf(uL)−sLf(uR)+sLsR(uR−uL)sR−sL.F_{\mathrm{HLL}}=\frac{s_R f(u_L)-s_L f(u_R)+s_Ls_R(u_R-u_L)}{s_R-s_L}.

If both speeds have the same sign, use the inflow-side flux. Bounds must cover relevant waves; evaluating only endpoints is not a guarantee for every nonconvex flux. The Lax–Wendroff theorem for conservative consistent schemes states, under convergence and its boundedness hypotheses, that the limit satisfies the weak law. It does not itself guarantee convergence or select entropy.

High resolution without pretending linearity

Godunov’s theorem says a linear monotone translation scheme in the scalar case, except exact integer translations, cannot be higher than first order. To see the obstacle, write a monotone update as combination ∑kckuj−k\sum_k c_k u_{j-k} with ck≥0c_k\ge0 and ∑kck=1\sum_kc_k=1. Second order would require ∑kck=ν\sum kc_k=\nu and ∑k2ck=ν2\sum k^2c_k=\nu^2. The variance of those weights would be zero, so weight can occur only at k=νk=\nu; if 0<ν<10<\nu<1, no integer index satisfies this. The guided proof revisits each assumption.

MUSCL reconstructs linear states per cell and applies a nonlinear slope limiter. The TVD limiter reduces slope near an extremum or discontinuity; minmod is more diffusive, while MC and superbee are other choices. SSP-RK3 combines Euler steps in a way that preserves a convex property when each Euler step satisfies it under the appropriate CFL. TVD does not mean every reconstruction, flux, step or system automatically preserves positivity: check assumptions and extreme states.

For example, with differences d−=uˉj−uˉj−1d_- = \bar u_j-\bar u_{j-1} and d+=uˉj+1−uˉjd_+=\bar u_{j+1}-\bar u_j, minmod returns zero if signs differ and otherwise the smaller magnitude with that sign. Reconstructed traces are uj+1/2−=uˉj+σj/2u_{j+1/2}^- = \bar u_j+\sigma_j/2 and uj−1/2+=uˉj−σj/2u_{j-1/2}^+ = \bar u_j-\sigma_j/2. Each interface flux uses the trace of its left cell and right cell. With L(u)L(u) the conservative derivative, SSP-RK3 computes u(1)=un+ΔtL(un)u^{(1)}=u^n+\Delta tL(u^n), u(2)=34un+14[u(1)+ΔtL(u(1))]u^{(2)}=\tfrac34u^n+\tfrac14[u^{(1)}+\Delta tL(u^{(1)})] and un+1=13un+23[u(2)+ΔtL(u(2))]u^{n+1}=\tfrac13u^n+\tfrac23[u^{(2)}+\Delta tL(u^{(2)})]. Each sum preserves periodic mass because every evaluation of LL sums to zero.

Discrete total variation on a periodic mesh is TV⁡(u)=∑j∣uj+1−uj∣\operatorname{TV}(u)=\sum_j|u_{j+1}-u_j|. A TVD update satisfies TV⁡(un+1)≤TV⁡(un)\operatorname{TV}(u^{n+1})\le\operatorname{TV}(u^n) under its analysis hypotheses. A limiter reduces slope at extrema to avoid oscillations, and that reduction can also lower local order there. The square-wave comparison reveals sharpness and possible overshoots; sine refinement in the lab also examines a smooth case, with a different metric and question.

A system: dam break

For shallow water without friction or topography, U=(h,hu)\vb U=(h,hu) and F(U)=(hu,hu2+gh2/2)\vb F(\vb U)=(hu,hu^2+gh^2/2). Characteristic speeds are u±ghu\pm\sqrt{gh} if h>0h>0. The initial height jump produces waves that can include a shock and rarefaction; HLL and Rusanov replace exact resolution with approximate fluxes. The figure’s reflective walls have zero mass flux, so total mass should remain constant; there is no dry-bed or friction model here.

InteractiveDam break with two fluxes
  • Height
  • Initial height

Shallow-water model, gravity 1; first-order finite volumes and reflective walls.

2.0
1.0
0.10
Numerical flux
Initial mass1.500000
Final mass1.500000
Steps46
Change both heights and choose Rusanov or HLL. The implementation uses first-order finite volumes, a step adapted to wave speed and reflective walls. Compare the profile and initial and final mass readouts.

The example keeps initial heights positive and uses CFL 0.35. Mass conservation does not prove exact shock position or method validity near a dry shore. For real systems, verify positivity, balance with topography and boundary conditions. Clawpack offers more complete solvers and Riemann problems; the interactive is a reduced deterministic model, not a run of that library.

In this demonstration HLL speeds are estimated from endpoints uL±ghLu_L\pm\sqrt{gh_L} and uR±ghRu_R\pm\sqrt{gh_R}. This is a particular choice for these states, not proof those estimates bound all intermediate waves in every problem. For other states, especially near dryness, choose and verify appropriate bounds and positivity treatment.

Lab: conservative solver from scratch

The implementation below uses scalar cell averages, limited reconstruction, Rusanov by default, optional Godunov flux and SSP-RK3. max_speed must supply a valid bound on characteristic speed across the state interval. The scalar solver supports periodic or free-outflow boundaries; the auxiliary HLL flux accepts vector states and wave bounds. For other boundary conditions or diffusion, construct and verify an adapter rather than assuming the solver implements them.

[ ]Finite-volume coreBrowser
"""Volúmenes finitos escalares 1D: MUSCL, Rusanov o Godunov, SSP-RK3.

Las entradas son medias de celda. `speed(u)` debe acotar la velocidad
característica en el intervalo relevante de estados; para un flujo no
convexo, usar una cota global válida, no solo el valor en el estado.
"""
import numpy as np


def minmod(a, b):
    return np.where(a*b > 0, np.sign(a)*np.minimum(np.abs(a), np.abs(b)), 0.0)


def slope_limited(left, u, right, limiter):
    dl, dr = u-left, right-u
    if limiter == 'first':
        return np.zeros_like(u)
    if limiter == 'minmod':
        return minmod(dl, dr)
    if limiter == 'mc':
        return minmod((dl+dr)/2, minmod(2*dl,2*dr))
    if limiter == 'superbee':
        p, q = minmod(2*dl,dr), minmod(dl,2*dr)
        return np.where(np.abs(p)>=np.abs(q),p,q)
    raise ValueError('limitador desconocido')


def godunov_burgers(left, right):
    """Flujo exacto para f(u)=u²/2: choque o rarefacción de entropía."""
    left, right = np.asarray(left), np.asarray(right)
    fl, fr = left*left/2, right*right/2
    rare = np.where(left >= 0, fl, np.where(right <= 0, fr, 0.0))
    shock = np.where((left+right)/2 >= 0, fl, fr)
    return np.where(left <= right, rare, shock)


def godunov_lwr(left, right):
    """Flujo exacto para f(rho)=rho(1-rho), con rho en [0,1]."""
    left, right = np.asarray(left), np.asarray(right)
    fl, fr = left*(1-left), right*(1-right)
    increasing_interval = np.minimum(fl,fr)
    decreasing_interval = np.where((right<=.5)&(left>=.5), .25, np.maximum(fl,fr))
    return np.where(left <= right, increasing_interval, decreasing_interval)


def hll_flux(left, right, flux, s_left, s_right):
    """Flujo HLL para estados vectoriales (..., nvar) y cotas de ondas (...)."""
    left=np.asarray(left,dtype=float); right=np.asarray(right,dtype=float)
    sl=np.asarray(s_left,dtype=float)[...,None]; sr=np.asarray(s_right,dtype=float)[...,None]
    if np.any(sl>sr):
        raise ValueError('las cotas de ondas deben estar ordenadas')
    fl,fr=flux(left),flux(right)
    den=np.where(sr-sl>0,sr-sl,1.0)
    middle=(sr*fl-sl*fr+sl*sr*(right-left))/den
    return np.where(sl>=0,fl,np.where(sr<=0,fr,middle))


def fv_rhs(u, dx, flux, speed, limiter='mc', bc='periodic', numerical_flux=None):
    """Derivada semidiscreta conservativa. Frontera periódica o salida libre."""
    u=np.asarray(u,dtype=float)
    if u.ndim != 1 or len(u)<3 or dx<=0:
        raise ValueError('u debe ser vector de al menos tres celdas y dx positivo')
    if bc not in ('periodic','outflow'):
        raise ValueError('frontera desconocida')
    left=np.roll(u,1); right=np.roll(u,-1)
    if bc == 'outflow':
        left[0]=u[0]; right[-1]=u[-1]
    slope=slope_limited(left,u,right,limiter)
    L=np.empty(len(u)+1); R=np.empty(len(u)+1)
    L[1:-1]=u[:-1]+slope[:-1]/2; R[1:-1]=u[1:]-slope[1:]/2
    if bc == 'periodic':
        L[0]=L[-1]=u[-1]+slope[-1]/2
        R[0]=R[-1]=u[0]-slope[0]/2
    else:
        L[0]=R[0]=u[0]; L[-1]=R[-1]=u[-1]
    if numerical_flux is None:
        alpha=np.maximum(np.asarray(speed(L)),np.asarray(speed(R)))
        faces=(flux(L)+flux(R))/2-alpha*(R-L)/2
    else:
        faces=numerical_flux(L,R)
    return -(faces[1:]-faces[:-1])/dx


def solve_fv(u0, dx, tf, flux, max_speed, cfl=.4, limiter='mc', bc='periodic', numerical_flux=None):
    """SSP-RK3 hasta tf; devuelve (medias finales, metadatos).

    `max_speed` puede devolver un escalar o un vector no negativo. La masa
    cambia por los flujos de frontera en salida libre, y se conserva en
    periódico. El CFL se recalcula en cada paso completo.
    """
    if not np.isfinite(tf) or not np.isfinite(dx) or not 0<cfl<=.5 or tf<0 or dx<=0:
        raise ValueError('se requiere 0 < cfl <= 0.5 y tf >= 0')
    u=np.asarray(u0,dtype=float).copy(); t=0.0; steps=0
    if u.ndim != 1 or len(u)<3 or not np.all(np.isfinite(u)):
        raise ValueError('u debe contener al menos tres valores finitos')
    initial_mass=float(dx*np.sum(u))
    while t < tf:
        speeds=np.asarray(max_speed(u),dtype=float)
        if not np.all(np.isfinite(speeds)) or np.any(speeds<0):
            raise ValueError('velocidad característica inválida')
        a=float(np.max(speeds))
        dt=min(tf-t,cfl*dx/a) if a>0 else tf-t
        L=lambda z: fv_rhs(z,dx,flux,max_speed,limiter,bc,numerical_flux)
        u1=u+dt*L(u)
        u2=.75*u+.25*(u1+dt*L(u1))
        u=u/3+(2/3)*(u2+dt*L(u2))
        t+=dt; steps+=1
    return u, {'time':t,'steps':steps,'initial_mass':initial_mass,'final_mass':float(dx*np.sum(u))}

The first check uses a periodic Burgers square wave. Mass is computed before and after; the extrema check applies to this case and CFL, not an arbitrary flux universally.

[ ]Conservation and extrema in BurgersBrowser
import numpy as np
n=200; dx=1/n; x=(np.arange(n)+.5)*dx
u0=np.where(x<.5,1.,0.)
burgers=lambda u:u*u/2
speed=lambda u:np.abs(u)
u,meta=solve_fv(u0,dx,.2,burgers,speed,cfl=.4,limiter='mc',numerical_flux=godunov_burgers)
print('masa inicial y final:', meta['initial_mass'], meta['final_mass'])
print('mínimo y máximo:', u.min(),u.max(), 'pasos:',meta['steps'])

Now compare a Burgers shock and rarefaction with their Riemann solutions before boundaries influence them. Error L1L^1 integrates average error; for the exact solution a fine quadrature is used inside each cell, so a shock is not compared only at the cell center.

[ ]L1 convergence for a Riemann problemBrowser
def exact_burgers(x,t,L,R):
    z=x/t
    if L>R: return np.where(z<(L+R)/2,L,R)
    return np.where(z<L,L,np.where(z>R,R,z))
def riemann_error(n,L,R):
    dx=2/n; x=-1+(np.arange(n)+.5)*dx; t=.2
    initial=np.where(x<0,L,R)
    numerical,_=solve_fv(initial,dx,t,burgers,speed,cfl=.4,limiter='mc',bc='outflow',numerical_flux=godunov_burgers)
    sub=(np.arange(40)+.5)/40-.5
    truth=exact_burgers(x[:,None]+dx*sub[None,:],t,L,R).mean(axis=1)
    return dx*np.sum(np.abs(numerical-truth))
for case in [(1.,0.),(-1.,1.)]:
    errors=[riemann_error(n,*case) for n in (100,200,400)]
    print('estados',case,'errores L1',np.round(errors,7))

Refinement near a shock need not give global second order in L1L^1, and error L∞L^\infty near a discontinuity is not a suitable measure of pointwise convergence. In a smooth region away from fronts, reconstruction accuracy can be studied separately. For traffic replace the flux and its Riemann solution with f(ρ)=ρ(1−ρ)f(\rho)=\rho(1-\rho) and godunov_lwr, keeping ρ∈[0,1]\rho\in[0,1].

For shock 1→01\to0, exact position at t=0.2t=0.2 is x=0.1x=0.1. Now separate error in a fixed window around that position and its complement. This partition is spatial, not an estimate of pointwise order; outside the window the exact solution in this case is constant.

[ ]Error near and far from the shockBrowser
for n in (100,200,400):
    dx=2/n; x=-1+(np.arange(n)+.5)*dx; t=.2
    initial=np.where(x<0,1.,0.)
    numerical,_=solve_fv(initial,dx,t,burgers,speed,cfl=.4,limiter='mc',bc='outflow',numerical_flux=godunov_burgers)
    sub=(np.arange(40)+.5)/40-.5
    truth=exact_burgers(x[:,None]+dx*sub[None,:],t,1.,0.).mean(axis=1)
    near=np.abs(x-.1)<.1
    print(n,'L1 cerca:',dx*np.abs(numerical-truth)[near].sum(),'L1 lejos:',dx*np.abs(numerical-truth)[~near].sum())
[ ]Refinement for a smooth waveBrowser
errors=[]
for n in (50,100,200):
    dx=1/n; x=(np.arange(n)+.5)*dx
    initial=np.sin(2*np.pi*x)*np.sinc(dx)
    numerical,_=solve_fv(initial,dx,.1,lambda z:z,lambda z:np.ones_like(z),limiter='mc')
    truth=np.sin(2*np.pi*(x-.1))*np.sinc(dx)
    errors.append(np.mean(np.abs(numerical-truth)))
print('errores medios:',errors)
print('razones de refinamiento:',errors[0]/errors[1],errors[1]/errors[2])

Here the solution is smooth across the periodic domain; observed refinement factors are evidence for these meshes and this case, not a uniform guarantee at discontinuities. Factor np.sinc(dx) converts sine values into exact cell averages.

[ ]Traffic shock and flux conservationBrowser
n=200; dx=2/n; x=-1+(np.arange(n)+.5)*dx
rho0=np.where(x<0,.2,.8)
rho,traffic_meta=solve_fv(rho0,dx,.1,lambda z:z*(1-z),lambda z:np.ones_like(z),bc='outflow',numerical_flux=godunov_lwr)
print('choque teórico:',1-.2-.8,'rango:',rho.min(),rho.max())
print('masa inicial y final:',traffic_meta['initial_mass'],traffic_meta['final_mass'])

The two exterior fluxes in this case are equal, so mass changes only by rounding. At a general outflow boundary mass can vary: that change must match the flux balance, not be forced to zero.

[ ]Traffic rarefaction versus RiemannBrowser
left,right=.8,.2; t=.1
rho0=np.where(x<0,left,right)
rho,_=solve_fv(rho0,dx,t,lambda z:z*(1-z),lambda z:np.ones_like(z),bc='outflow',numerical_flux=godunov_lwr)
sub=(np.arange(40)+.5)/40-.5
z=(x[:,None]+dx*sub[None,:])/t
truth=np.where(z<1-2*left,left,np.where(z>1-2*right,right,(1-z)/2)).mean(axis=1)
print('error L1 de rarefacción:',dx*np.abs(rho-truth).sum())

The last cell implements a first-order shallow-water step with reflective walls. It compares Rusanov and HLL with the same heights and checks mass. It does not use the scalar solver for a vector state: it reuses the HLL formula and makes the system adapter explicit.

[ ]Shallow water: Rusanov and HLLBrowser
def shallow_flux(U):
    h,m=U[...,0],U[...,1]
    return np.stack((m,m*m/h+h*h/2),axis=-1)
def dam_run(method, n=100, end=.1):
    dx=1/n
    U=np.column_stack((np.where(np.arange(n)<n//2,2.,1.),np.zeros(n)))
    mass0=dx*U[:,0].sum(); t=0.
    while t<end:
        vel=U[:,1]/U[:,0]; c=np.sqrt(U[:,0])
        dt=min(end-t,.35*dx/np.max(np.abs(vel)+c))
        ghost_l=np.array([U[0,0],-U[0,1]])
        ghost_r=np.array([U[-1,0],-U[-1,1]])
        L=np.vstack((ghost_l,U)); R=np.vstack((U,ghost_r))
        vl=L[:,1]/L[:,0]; vr=R[:,1]/R[:,0]
        cl=np.sqrt(L[:,0]); cr=np.sqrt(R[:,0])
        if method=='HLL':
            F=hll_flux(L,R,shallow_flux,np.minimum(vl-cl,vr-cr),np.maximum(vl+cl,vr+cr))
        else:
            a=np.maximum(np.abs(vl)+cl,np.abs(vr)+cr)[:,None]
            F=(shallow_flux(L)+shallow_flux(R)-a*(R-L))/2
        U=U-dt/dx*(F[1:]-F[:-1]); t+=dt
        assert np.all(U[:,0]>0)
    return mass0,dx*U[:,0].sum(),U[:,0].min()
for name in ['Rusanov','HLL']:
    print(name,dam_run(name))

Exercises

ProofNumerical viscosity
Prove: Obtain the leading diffusive term of upwind for positive a and ν=aΔt/Δx.
0
Expand in Taylor series around (x_j,t_n) and assume a smooth solution.

Step 1 of 3. Which time term appears in the expansion?

NumericRankine–Hugoniot speed
For Burgers with left state 2 and right state 0, what is the shock speed?
CodeA conservative step
Implement muscl_step(u, flux, max_speed, dx, dt, limiter): one periodic scalar MUSCL step with Rusanov flux and SSP-RK3. u contains cell averages, flux and max_speed are vectorized functions and limiter is 'minmod' or 'mc'. Tests use a stable CFL.
import numpy as np
def muscl_step(u, flux, max_speed, dx, dt, limiter):
  pass
Shift+Enter to run
QuizIncorrect speed
Why can a nonconservative discretization of uu_x produce an incorrect shock speed?
ProofThe order barrier
Prove: Prove that a linear monotone translation scheme is not second order when 0<ν<1.
0
Write the update as a sum of shifted values with nonnegative weights c_k summing to one.

Step 1 of 3. What moment conditions does second order impose?

Closing

Key idea
CFL limits numerical propagation, conservation fixes shock balance and entropy selects the admissible solution. High resolution requires controlling oscillations without losing those properties.

Before trusting a figure, check mass and boundary fluxes, recalculate wave speed as time advances and compare with a Riemann solution. Linear stability alone does not guarantee monotonicity, positivity or correct shock speed.