Pour dye into a river and watch a blob of it drift downstream. It moves, it twists, it gets stretched into a long streak, but in water it never gets bigger or smaller in total area. Now watch smoke pour out of a chimney: right at the top of the stack, new gas is appearing, and the flow spreads out from it. The first flow merely moves fluid around. The second has a source. In 2.6 Vector Fields, Flow Lines & Streamlines you learned to draw velocity fields and follow particles through them. This lesson introduces the first of the two derivatives that describe what a field does locally: the divergence, which measures how much a flow spreads out (or piles up) at each point. The second, the curl, comes next.
Divergence is not an academic curiosity for us. The single most expensive step in a Stam-style fluid solver, the pressure projection, exists to make the divergence of the velocity field zero in every grid cell. By the end of this lesson you’ll know exactly what that number is, how to compute it on a grid, and why it equals the trace you met in 1.8 The Matrix Exponential: From Hops to Flows.
Transcript
- In a fluid, every point has a velocity. Today we ask a simple question about that velocity field: at a given point, is fluid being created, destroyed, or just passing through?
- Here is a velocity field that spreads outward from the origin. Drop an imaginary box into the flow. The walls don't block anything; they just let us count.
- Only the part of the velocity perpendicular to a wall carries fluid through it. Green arrows show fluid leaving, red arrows show fluid entering.
- Slide the box away from the center. Some fluid now enters on one side, but more leaves on the other. The net outflow per area stays the same: this field is a source everywhere.
- Compare a uniform wind. Fluid enters on the left and leaves on the right at exactly the same rate. Net outflow is zero: nothing is created, it just passes through.
- A subtler case. Every arrow points right, so nothing visibly spreads out. But the flow speeds up as it goes, so more leaves on the right than enters on the left.
- Divergence is exactly this number: net outflow from a tiny box, divided by the box's size, in the limit as the box shrinks to a point.
- Let's turn that into a formula. Take a small box of width delta x and height delta y, centered at the point x, y, in a field with components P and Q.
- Through the right wall, the outflow rate is the horizontal velocity P times the wall's length, delta y. On the left wall, outward means the negative x direction, so the outflow is minus P times delta y.
- Add them. The difference of P across the box is, by a first order Taylor expansion, the partial derivative of P with respect to x, times delta x. The two side walls together contribute d P d x times the area.
- The top and bottom walls work the same way with Q and y, giving d Q d y times the area.
- Divide by the area and let the box shrink. The divergence of F is d P d x plus d Q d y. Each term measures how fast one velocity component grows along its own direction.
- In three dimensions the box has six faces, and one more term appears: d R d z. The notation nabla dot F reminds you of the recipe: a dot product of the del operator with the field.
- Let's compute a few. For the source x comma y, d P d x is one and d Q d y is one, so the divergence is two, at every point.
- A vortex, a shear flow and a saddle all have divergence zero. They swirl, slide and stretch the fluid, but they never compress it or create it. Fields like these are called divergence free, or incompressible.
- Because divergence is a number at every point, we can paint it as a heat map. Here is a field that pushes outward from the center but fades with distance. Red means positive divergence, blue means negative.
- The center is a source. But look at the blue ring: the arrows there still point outward! They are slowing down, so more fluid arrives than leaves. Divergence is about how the flow changes, not which way the arrows point.
- Divergence connects straight back to module one. For a linear field u equals A x, the divergence is a plus d, the trace of A. Here the trace is zero.
- Let a blob of fluid ride the flow. It gets stretched one way and squeezed the other, but its area never changes. Divergence free means area preserving.
- Now a spiral with trace zero point seven. The blob grows, and its area is multiplied by e to the t times the trace, exactly the determinant of e to the A t from lesson one point eight. Divergence is the relative rate at which a fluid parcel's area grows.
- How does a simulator compute divergence? A grid based fluid solver chops space into cells. On a staggered, or MAC, grid, pressure lives at the cell center and each velocity component lives on the faces it pushes fluid through.
- Then the discrete divergence is just the flux box again: outflow through the right face minus inflow through the left, plus top minus bottom, divided by the cell size h.
- This is the quantity an incompressible solver obsesses over. The projection step in Stam's stable fluids solves for a pressure that drives this number to zero in every single cell.
- Finally, a preview of the most important equation in fluid dynamics. Fill the box with fluid of density rho. The mass inside is rho times the volume.
- Mass can only change by flowing through the walls. The mass flux is rho times u, so the net mass outflow is the divergence of rho u times the volume.
- Divide by the volume and you get the continuity equation: d rho d t plus the divergence of rho u equals zero. If the density never changes, it reduces to divergence of u equals zero, the incompressibility condition.
- To recap: divergence is net outflow per unit volume. Positive means a source, negative a sink, and zero means the flow preserves volume, which is what incompressible solvers enforce.
- Divergence measures how a flow spreads. Next time we measure how it spins: the curl.
Flux through a wall
Before we can count what leaves a box, we need to know how fast fluid crosses a single wall.
Picture a short straight wall segment of length sitting in a flow with velocity . The wall is imaginary: fluid passes straight through it. Let be the unit vector perpendicular to the wall, pointing to the side we call “out”. Split the velocity into a part along the wall and a part along . Fluid sliding along the wall never crosses it. Only the normal component carries fluid across. In time , the fluid that crosses fills a thin parallelogram of base and height , so
In 3D the wall is a patch of area and the rate is , a volume per unit time. This rate is called the flux through the wall. It is positive when fluid leaves through the wall and negative when fluid enters. If the velocity varies along the wall, add up the contributions of small pieces. That sum becomes the flux integral of 2.9 Line Integrals, Circulation & Flux, but for a tiny wall the velocity is nearly constant and the simple product is enough.
Net outflow from a tiny box
Now surround a point with a small box and add the fluxes through all of its walls, each with its own outward normal. The total is the net outflow:
- Net outflow : more fluid leaves than enters. Something inside is producing fluid. The point is a source.
- Net outflow : more enters than leaves. Fluid is accumulating or being destroyed. The point is a sink.
- Net outflow : whatever comes in goes out. The fluid just passes through.
Bigger boxes catch more flux, so to get a number that describes the point rather than the box, divide by the box’s area (volume in 3D) and let the box shrink:
This definition doesn’t depend on coordinates or on the box being square. Any small shape gives the same limit. That is what makes divergence a physical quantity and not an artifact of how we set up axes.
Deriving the formula
Let in 2D and take a rectangle of width and height centered at .
Right wall. Its outward normal is , so . The wall has length , and its midpoint is , so the outflow is approximately .
Left wall. Here outward means , so the outflow is . If is positive, fluid is entering on the left, which counts against the net outflow.
The two side walls together give
A first-order Taylor expansion (2.4 Taylor Series in One and Several Variables) gives . Subtracting, the terms cancel and the even-order error terms cancel too, leaving
Top and bottom. Exactly the same argument with and gives plus higher-order terms.
Add all four walls, divide by the area , and let the box shrink:
for , where a box has six faces and the -faces contribute the last term. The notation is a mnemonic: with the “del” operator , the divergence is a dot product of with .
Read the formula term by term. asks: does the -velocity grow as you move in the direction? If it does, more fluid leaves through the right face than enters through the left. Note what doesn’t appear: and . Those mixed terms describe sliding and rotation, which move fluid along walls instead of through them. They belong to the curl (2.8 Curl & Vorticity).
Worked examples
Example 1: the linear source
Find the divergence of , and check it against the flux through a circle.
and , so at every point. Every point is a source of the same strength.
Check with the definition, using a circle of radius centered at the origin instead of a box. On the circle the outward normal is , so . That’s constant around the circle, whose length is , so the net outflow is . Dividing by the area gives exactly . ✓ The shape of the region didn’t matter.
Example 2: a fading source
Find the divergence of , where .
By the product and chain rules,
and likewise . So
It’s positive for (a source region) and negative for , even though every arrow points outward. Out there the outflow rate through a circle, (circumference times speed), is decreasing with , so fluid arriving from inside exceeds fluid leaving to the outside. (Slowing down alone isn’t enough: the speed already drops for , but the circles are also growing longer, and that keeps the divergence positive until .) This is the default field in the explorer below.
Example 3: a 3D field
Find for , and find where it vanishes.
, and . So . It’s zero on the plane and on the plane . Above with , the field is a sink.
Things to try:
- With the Gaussian source, drag the box from the center outward. The readout flips from source to sink at radius , where the heatmap changes from red to blue. At radius 2, look at the wall arrows: the red inflow arrows on the inner wall are longer than the green outflow arrows on the outer wall.
- Press Shrink box → 0 anywhere. Flux ÷ area approaches at the center. For a big box the two disagree, because flux ÷ area is really the average divergence over the box.
- Switch to Vortex, Shear and Saddle. The heatmap goes blank and the net outflow is zero wherever you put the box, even though the saddle visibly stretches the fluid.
- Press Advect the box for the saddle (area ratio stays 1), then for the source (area ratio , because ) and the linear spiral (). That’s the next section.
Sources, sinks and incompressible flow
In a real fluid, mass isn’t created or destroyed. So what does a “source” mean physically? Three things:
- Compressible flow. A gas can expand. Hot air rising from a fire, or air leaving the high-pressure region in front of a wing at high Mach number, has positive divergence where it expands and negative where it compresses. The density changes to compensate (see the continuity equation below).
- Modeling idealizations. A pipe outlet, a jet nozzle, a drain, or a chimney top is too small to resolve, so we model it as a point source or sink that injects or removes fluid.
- Zero, almost everywhere. For liquids, and for air at low speeds (below roughly a third of the speed of sound), density barely changes, and the velocity field satisfies
A field with zero divergence is called divergence-free, solenoidal, or incompressible. It can swirl, shear and stretch, but every bit of fluid that enters a region must leave it.
Divergence is a trace: the area-change law
Zoom in on a smooth velocity field near a point . By linearization (2.2 Linearization, the Chain Rule & the Jacobian),
is the Jacobian of the velocity, which fluid dynamicists call the velocity gradient tensor. Its diagonal entries are exactly the two terms in the divergence:
Now recall what you proved in 1.8 The Matrix Exponential: From Hops to Flows. The flow of the linear field is , and it multiplies areas by . The constant part only translates the parcel and doesn’t change its area. So a tiny parcel of fluid near has area
That’s why the “Advect the box” button in the sim gives an area ratio of exactly 1 for every divergence-free preset, and for the linear spiral , whose trace is .
Divergence on a grid
A simulator never sees a formula, only numbers at grid points. There are two common ways to store a 2D velocity field, and each has its own discrete divergence.
Collocated grid. Both components and live at the same grid points with spacing . Replace each partial derivative with a central difference:
This is second-order accurate (error , from the Taylor expansion), but it has a famous flaw: it never compares a point with its immediate neighbors. A velocity field that alternates from point to point has zero discrete divergence, so a solver that enforces this version lets “checkerboard” noise survive.
Staggered (MAC) grid. The Marker-and-Cell grid of Harlow and Welch (1965) puts pressure at cell centers and each velocity component on the cell faces it pushes fluid through. lives on the left and right faces, on the bottom and top faces. The discrete divergence of cell is then
Look closely. Multiply by the cell area and you get : this is exactly the net outflow through the four faces of the cell, the flux box from the start of the lesson with . The MAC divergence isn’t an approximation bolted on afterwards. It’s the definition of divergence applied to one grid cell. This also makes it compact (each cell only sees its own faces), so the checkerboard problem disappears.
Worked example: one MAC cell
A cell with has face velocities , , , . Is it divergence-free?
Yes. Fluid speeds up in (more leaves on the right), but fluid also enters through both the bottom face (moving up) and the top face (moving down), and the two effects exactly balance.
Numerics: flux ÷ area really converges
Here’s a direct check of the definition. The cell below computes the net outflow through square boxes of shrinking size around a point, using a fine midpoint rule on each wall, and compares flux ÷ area with the formula. SymPy computes the exact divergence.
The error drops by a factor of about 4 each time the box halves: second-order convergence. That’s no accident. Flux ÷ area is the average of the divergence over the box (that’s the divergence theorem of 2.10 Green, Stokes & the Divergence Theorem), and the average of a smooth function over a symmetric box differs from its center value by . The same reasoning tells you the MAC divergence is a second-order approximation at the cell center.
The next cell checks the area-change law by advecting a polygon with RK4 and measuring its area with the shoelace formula.
Try changing to have trace zero, say : the blob stretches into a long sliver, but the area ratio stays at .
Exercise: discrete divergence
The stream-function test is worth a second look. Any field built as , is divergence-free in the continuum, because by Clairaut’s theorem (2.1 Functions of Several Variables & Partial Derivatives). When you build and from differences of on the MAC grid, the discrete divergence cancels exactly, term by term, down to rounding error. Staggered grids preserve this identity, which is one reason they’re so popular for incompressible flow.
The continuity equation (preview)
Divergence earns its place in physics through conservation of mass. Let be the density (mass per volume) and the velocity. The mass flux, meaning mass crossing a wall per unit area per unit time, is , by the same argument as before with “fluid” replaced by “mass”.
Take a small fixed box of volume . Its mass is . Mass can’t be created, so the only way it changes is by flowing through the walls:
Divide by :
This is the continuity equation, the first of the governing equations of fluid dynamics. Expanding with the product rule gives
The left side is the material derivative from 2.2 Linearization, the Chain Rule & the Jacobian: the rate of change of density felt by a parcel riding the flow. So a parcel’s density stays constant exactly when . That’s the precise meaning of “incompressible”. It also matches the area law: if a parcel’s volume grows at relative rate while its mass is fixed, its density must fall at that same relative rate. You’ll derive the continuity equation rigorously with the divergence theorem in 2.10 Green, Stokes & the Divergence Theorem and put it to work in 11.2 Conservation of Mass: The Continuity Equation.
Problems
Compute :
- , and describe where it’s a source and where it’s a sink.
Show worked solution
- . A uniform weak source. (It’s the linear field with trace .)
- . Zero only at the origin, positive everywhere else.
- . Divergence-free.
- . It’s a source on the side of the plane where , a sink on the other side, and divergence-free on the plane itself.
Let and let be the unit square .
- Compute the flux through each of the four sides of , and the net outflow.
- Compute and compare.
- For a small square of side centered at , compute the net outflow exactly and show that net outflow ÷ area equals for every .
Show worked solution
- Right side (, ): , so the flux is . Left side (, ): , so the flux is . Top (, ): , so the flux is . Bottom (, ): , so the flux is . Net outflow .
- , and . The same number! This is the divergence theorem (2.10 Green, Stokes & the Divergence Theorem): adding up divergence over a region gives the total outflow through its boundary.
- The side walls give . The top and bottom give . The net outflow is , and dividing by the area gives exactly. (In general there’s an error. Here it vanishes because is linear, so its box average equals its center value.)
- Find the constant that makes divergence-free.
- Show that for any smooth function , the field is divergence-free.
- Find a stream function for the field in part 1.
Show worked solution
- , which vanishes for all only if .
- by Clairaut’s theorem (mixed partials of a smooth function are equal).
- We need . Integrating in gives . Then must equal , so . Hence (plus any constant). Check: ✓ and ✓. Every 2D incompressible field has a stream function like this, and the streamlines are its level curves.
A 2D gas expands uniformly with velocity , where is constant, and its density is the same at every point.
- Use the continuity equation to find given .
- Check your answer using the area-change law: how does the area of a parcel grow, and what must happen to its density?
- Repeat part 1 in 3D with .
Show worked solution
- Since doesn’t depend on position, and . Continuity gives , so .
- , so parcel areas grow like . (Directly: each length scales by , since particles move as .) A parcel’s mass is fixed, so its density must fall like . ✓
- In 3D, , so : volumes grow like . This is the “Hubble flow” of a uniformly expanding universe, in which density thins out as the cube of the scale factor.
Key Takeaways
- Flux through a small wall is (normal velocity) × (wall size). Only the component of perpendicular to the wall carries fluid across.
- Divergence is net outflow per unit area or volume from a shrinking region: positive at a source, negative at a sink. In coordinates, , derived by Taylor-expanding the flux through a box.
- Divergence measures how the field changes, not where it points. Accelerating parallel flow has positive divergence, and an outward flow that decelerates fast enough has negative divergence.
- , the trace of the velocity gradient. A parcel’s area or volume changes at relative rate , the local version of .
- Incompressible flow means : parcels deform but keep their volume. Fields of the form are automatically incompressible.
- On a MAC grid, the discrete divergence of a cell is literally its net face flux divided by its area. Stam’s projection step drives it to zero in every cell, and that solve dominates the cost of the simulation.
- Mass conservation in a box gives the continuity equation . With constant density it reduces to .