---
title: "Lab: flux, divergence and curl in code"
heading: Checking Gauss, Stokes and Biot–Savart numerically
eyebrow: A9 · Lesson 39 · Lab: flux, divergence and curl
xp: 60
---

::: hook
The divergence and Stokes theorems connect what happens inside a region to what crosses or circles its boundary. In this lab you'll test them numerically: derivatives of a field on a grid, the flux of a point charge through spheres that do and don't contain it, the flux out of a cube computed both ways, the magnetic field of a current loop summed segment by segment, and the circulation of a wire's field around loops that do and don't enclose it.
:::

::: play
- The field is that of a line source at the origin, $\frac{(x, y)}{x^2 + y^2}$, a two-dimensional point charge.
- Its flux through any closed curve is $2\pi$ if the curve encloses the source and zero if it doesn't. The readout applies that to a circle of radius $R$ centered at distance $d$ from the source.
- Slide $d$ past $R$: the flux drops from $2\pi$ to zero at once, however close the curve still is.
:::

```sim plot
view: flow
x: x = -3..3
y: y = -3..3
slider: R = 0.5..2 step 0.1 = 1
slider: d = 0..2.5 step 0.1 = 0.5
dx: x/(x^2 + y^2)
dy: y/(x^2 + y^2)
start: 0.3, 0.1 | forward
start: -0.2, 0.3 | forward
start: 0.1, -0.3 | forward
grid: 14
readout: flux through the circle = 2*pi*step(R - d) | digits: 4
```

::: predict
## A point charge sits just outside a closed sphere. What is the net electric flux through the sphere?

- [ ] Half of $q/\varepsilon_0$, since it's so close
- [x] Zero
- [ ] $q/\varepsilon_0$
- [ ] It depends on how close it is

::: reveal
Zero. Every field line that enters the sphere on the near side leaves on the far side. The field is strong on the near side and weak on the far side, but the near-side patch it crosses is seen at a steep angle and the far-side patch is larger, and the two cancel exactly. Only enclosed charge produces net flux.
:::
:::

::: nameit
## Derivatives on a grid

`np.gradient(F, h, axis=k)` estimates $\frac{\partial F}{\partial x_k}$ by central differences in the interior. Divergence and curl come from combining them:

```python
div = np.gradient(Fx, h, axis=0) + np.gradient(Fy, h, axis=1)
curl_z = np.gradient(Fy, h, axis=0) - np.gradient(Fx, h, axis=1)
```

(with arrays indexed `[i, j]` for $x_i$, $y_j$).

## Flux through a sphere

On a grid of $(\theta, \varphi)$ angles, the outward normal is $\hat{\mathbf n} = (\sin\theta\cos\varphi, \sin\theta\sin\varphi, \cos\theta)$ and $dA = a^2\sin\theta\,d\theta\,d\varphi$. Sum $\mathbf F\cdot\hat{\mathbf n}\,dA$ over the cells.

## Biot–Savart

A current loop's field is the sum over short segments $d\mathbf l$:

$$\mathbf B = \frac{\mu_0I}{4\pi}\sum\frac{d\mathbf l\times\mathbf r}{|\mathbf r|^3}$$

with $\mathbf r$ from each segment to the field point. On the axis of a circular loop of radius $R$, the exact result is $B_z = \frac{\mu_0IR^2}{2(R^2 + z^2)^{3/2}}$.
:::

::: example
## Check the divergence theorem for $\mathbf F = (x^2y, yz, zx)$ on the unit cube.

::: solution
1. **Divergence.**
   $$\nabla\cdot\mathbf F = 2xy + z + x$$
2. **Integrate it over the cube.**
   $$2 \cdot \tfrac12 \cdot \tfrac12 + \tfrac12 + \tfrac12 = 1.5$$
3. **Flux through the far faces.** At $x = 1$, $F_x = y$, giving $\frac12$; at $y = 1$, $F_y = z$, giving $\frac12$; at $z = 1$, $F_z = x$, giving $\frac12$.
4. **Flux through the near faces.** The three faces through the origin have zero normal component.
5. **Compare.** The total flux is 1.5, matching.

**Answer:** both sides give 1.5.
:::
:::

::: example
## Find the field on the axis of a 5 cm loop carrying 1 A, 3 cm from its center.

::: solution
1. **On-axis field of a loop.**
   $$\begin{aligned} B_z &= \frac{\mu_0IR^2}{2(R^2 + z^2)^{3/2}} \\ &= \frac{4\pi \times 10^{-7} \times 0.0025}{2(0.0034)^{3/2}} \\ &= 7.92\ \text{µT} \end{aligned}$$
2. **Check numerically.** Summing Biot–Savart over 2000 segments of the loop gives the same to thirteen digits: on the axis the sum is a symmetric average, and it converges very fast.

**Answer:** the field is 7.92 µT along the axis.
:::
:::

::: check
given: I = 1 | 5; R = 2 | 5; z = 2 | 3
answer: 4*pi*1e-7*I*(R/100)^2/(2*((R/100)^2 + (z/100)^2)^1.5)*1e6
unit: µT
tolerance: 0.5%

## A loop of radius {R} cm carries {I} A. What is the field on its axis, {z} cm from the center?

::: right
Right. $\frac{\mu_0IR^2}{2(R^2 + z^2)^{3/2}}$ = {answer}.
:::

::: misses
- [4*pi*1e-7*I/(2*R/100)*1e6] That's the field at the center; away from the loop it's weaker.
- [any] Not yet. Use the on-axis formula.
:::
:::

::: check
given: q = 1..20 int
answer: q*1e-9/(6*8.854e-12)
unit: V·m
tolerance: 0.5%

## A {q} nC charge sits at the center of a cube. What is the flux through one face?

::: right
Right. By symmetry each of the six faces gets a sixth of $q/\varepsilon_0$: {answer}.
:::

::: misses
- [q*1e-9/8.854e-12] That's the total through all six faces.
- [any] Not yet. Gauss's law gives the total; symmetry splits it.
:::
:::

::: check
kind: python

## On a 101 × 101 grid over $[0, 1]^2$, compute the divergence and the curl's $z$ component of $\mathbf F = (x^2, xy)$ with `np.gradient`. Set `err_div` and `err_curl` to the largest differences from the exact $3x$ and $y$ at interior points.

```python starter
import numpy as np

err_div = err_curl = 1.0
print(err_div, err_curl)
```

```python solution
import numpy as np

x = np.linspace(0, 1, 101)
h = x[1] - x[0]
X, Y = np.meshgrid(x, x, indexing="ij")
Fx, Fy = X**2, X * Y
div = np.gradient(Fx, h, axis=0) + np.gradient(Fy, h, axis=1)
curl = np.gradient(Fy, h, axis=0) - np.gradient(Fx, h, axis=1)
err_div = np.max(np.abs(div - 3 * X)[1:-1, 1:-1])
err_curl = np.max(np.abs(curl - Y)[1:-1, 1:-1])
print(err_div, err_curl)
```

```python tests
assert err_div < 1e-9 and err_curl < 1e-9, f"Central differences are exact for quadratics in the interior; got {err_div}, {err_curl}."
```

::: right
Right. For a quadratic field, central differences are exact apart from rounding.
:::
:::

::: check
kind: python

## Write `flux(c, a, n=400)` returning the flux of $\frac{\mathbf r}{|\mathbf r|^3}$ (a point charge at the origin) through a sphere of radius `a` centered at `c`, with a midpoint grid of `n` × `2n` angles. Set `f1, f2, f3` for spheres of radius 1 centered at $(0, 0, 0)$, $(0.3, 0, 0)$ and $(2, 0, 0)$.

```python starter
import numpy as np

def flux(c, a, n=400):
    return 0.0

f1, f2, f3 = flux([0, 0, 0], 1), flux([0.3, 0, 0], 1), flux([2, 0, 0], 1)
print(f1, f2, f3)
```

```python solution
import numpy as np

def flux(c, a, n=400):
    th = (np.arange(n) + 0.5) * np.pi / n
    ph = (np.arange(2 * n) + 0.5) * np.pi / n
    T, P = np.meshgrid(th, ph, indexing="ij")
    nrm = np.stack([np.sin(T) * np.cos(P), np.sin(T) * np.sin(P), np.cos(T)], axis=-1)
    pos = np.array(c) + a * nrm
    r = np.linalg.norm(pos, axis=-1)[..., None]
    E = pos / r**3
    return np.sum((E * nrm).sum(axis=-1) * a * a * np.sin(T)) * (np.pi / n)**2

f1, f2, f3 = flux([0, 0, 0], 1), flux([0.3, 0, 0], 1), flux([2, 0, 0], 1)
print(f1, f2, f3)
```

```python tests
import math
assert abs(f1 - 4 * math.pi) < 1e-3 and abs(f2 - 4 * math.pi) < 1e-3, f"Any sphere around the charge gives 4 pi; got {f1}, {f2}."
assert abs(f3) < 1e-3, f"A sphere not containing the charge gives zero; got {f3}."
```

::: right
Right. $4\pi$ whether the charge is centered or not, zero when it's outside: Gauss's law, computed.
:::
:::

::: check
kind: python

## Check the divergence theorem for $\mathbf F = (x^2y, yz, zx)$ on the unit cube: compute the volume integral of $\nabla\cdot\mathbf F$ with a 100³ midpoint grid and the outward flux through the six faces with 100² midpoint grids. Set `vol` and `surf`.

```python starter
import numpy as np

vol = surf = 0.0
print(vol, surf)
```

```python solution
import numpy as np

n = 100
c = (np.arange(n) + 0.5) / n
X, Y, Z = np.meshgrid(c, c, c, indexing="ij")
vol = np.sum(2 * X * Y + Z + X) / n**3
U, V = np.meshgrid(c, c, indexing="ij")
F = lambda x, y, z: (x * x * y, y * z, z * x)
surf = 0.0
surf += np.sum(F(1, U, V)[0] - F(0, U, V)[0]) / n**2
surf += np.sum(F(U, 1, V)[1] - F(U, 0, V)[1]) / n**2
surf += np.sum(F(U, V, 1)[2] - F(U, V, 0)[2]) / n**2
print(vol, surf)
```

```python tests
assert abs(vol - 1.5) < 1e-9 and abs(surf - 1.5) < 1e-9, f"Both sides should be 1.5; got {vol}, {surf}."
```

::: right
Right. The inside and the boundary agree, and for this polynomial field the midpoint rule is exact.
:::
:::

::: check
kind: python

## Sum Biot–Savart over 2000 segments of a loop of radius 5 cm carrying 1 A to get $B_z$ at 3 cm along the axis. Set `Bz` and `formula`.

```python starter
import numpy as np

Bz = formula = 0.0
print(Bz, formula)
```

```python solution
import numpy as np

R, I, z0, N = 0.05, 1.0, 0.03, 2000
ph = np.arange(N) * 2 * np.pi / N
dphi = 2 * np.pi / N
pts = np.stack([R * np.cos(ph), R * np.sin(ph), 0 * ph], axis=1)
dl = np.stack([-R * np.sin(ph), R * np.cos(ph), 0 * ph], axis=1) * dphi
r = np.array([0, 0, z0]) - pts
B = 1e-7 * I * np.cross(dl, r) / np.linalg.norm(r, axis=1)[:, None]**3
Bz = B.sum(axis=0)[2]
formula = 4e-7 * np.pi * I * R**2 / (2 * (R**2 + z0**2)**1.5)
print(Bz, formula)
```

```python tests
assert abs(formula - 7.9232e-6) < 1e-9, f"The on-axis formula gives 7.923 uT; got {formula}."
assert abs(Bz - formula) < 1e-12, f"The Biot-Savart sum should match the formula; got {Bz}."
```

::: right
Right. The segment sum matches the formula to about 13 digits, and the same code works for loops of any shape.
:::
:::

::: check
kind: python

## A long wire along $z$ carries 2 A, with $\mathbf B = \frac{\mu_0I}{2\pi}\frac{(-y, x)}{x^2 + y^2}$. Compute the circulation of $\mathbf B$ around the square with corners $(\pm1, \pm1)$ (enclosing the wire) and around the square from $(2, 2)$ to $(3, 3)$ (not enclosing it), 4000 midpoint segments per side. Set `c1` and `c2`.

```python starter
import numpy as np

c1 = c2 = 0.0
print(c1, c2)
```

```python solution
import numpy as np

mu0, I = 4e-7 * np.pi, 2.0

def B(x, y):
    k = mu0 * I / (2 * np.pi) / (x * x + y * y)
    return -k * y, k * x

def circ(x0, y0, x1, y1, n=4000):
    corners = [(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)]
    total = 0.0
    for (ax, ay), (bx, by) in zip(corners[:-1], corners[1:]):
        s = (np.arange(n) + 0.5) / n
        mx, my = ax + (bx - ax) * s, ay + (by - ay) * s
        bxv, byv = B(mx, my)
        total += np.sum(bxv * (bx - ax) / n + byv * (by - ay) / n)
    return total

c1 = circ(-1, -1, 1, 1)
c2 = circ(2, 2, 3, 3)
print(c1, c2)
```

```python tests
import math
assert abs(c1 - 4e-7 * math.pi * 2) < 1e-11, f"Around the wire the circulation is mu0 I = 2.513e-6; got {c1}."
assert abs(c2) < 1e-11, f"A loop not around the wire gives zero; got {c2}."
```

::: right
Right. Ampère's law: the circulation counts only the current threading the loop, whatever the loop's shape.
:::
:::

::: explain
## A field's flux through a closed surface is zero. Does that mean the field is zero inside?

::: model
No. Zero net flux only means that as much flux leaves as enters, so the total divergence inside, or the enclosed source, is zero. A uniform field passes straight through any closed surface with zero net flux, and the field of a charge outside the surface does too, though both are nonzero everywhere inside. Even with charges inside, positive and negative ones can cancel in the total. Gauss's law constrains the total source, not the field's value at any point; to get the field itself you also need symmetry, as in the textbook Gauss's-law problems, or a full solution of the field equations.
:::
:::

::: practice

::: check
given: I = 0.1..10; R = 1..20; z = 0..20
answer: 4*pi*1e-7*I*(R/100)^2/(2*((R/100)^2 + (z/100)^2)^1.5)*1e6
unit: µT
tolerance: 0.5%

## On-axis field in µT, loop of {R} cm, {I} A, at {z} cm?

::: misses
- [any] $\frac{\mu_0IR^2}{2(R^2 + z^2)^{3/2}}$.
:::
:::

::: check
given: I = 0.1..100
answer: 4*pi*1e-7*I*1e6
unit: µT·m
tolerance: 0.5%

## Circulation of $\mathbf B$ in µT·m around a loop enclosing {I} A?

::: misses
- [any] $\mu_0I$.
:::
:::
:::
