---
title: Magnetic field lab
heading: Biot–Savart in code, uniform-field coils, solenoids, orbits and a Hall measurement
eyebrow: B5 · Lesson 14 · Magnetic field lab
xp: 50
---

::: hook
Every magnetic field in this unit came from a symmetric shape: an infinite wire, a circular loop, an ideal solenoid. Real coils are square, short, or bent around a sensor, and the Biot–Savart law handles them all if you add up enough small pieces of current. In this lab you'll write that sum, check it against the shapes you know, design a Helmholtz pair for a uniform field, build a finite solenoid out of loops, track a charge through a field with a method that keeps its speed exact, and pull a carrier density out of noisy Hall data.
:::

::: play
- Two coaxial coils of radius R carry equal currents. The curve is the field along their shared axis, relative to its value at the midpoint, as you move along the axis.
- Set the spacing to R: the curve is flattest there, the Helmholtz condition, where the field's second derivative at the center vanishes.
- Closer coils give a dip at the center, wider ones a hump. The readout gives the field 0.1R from the center, relative to the center.
:::

```sim plot
view: graph
x: z = -1..1
y: B = 0.8..1.1
slider: s = 0.6..1.6 step 0.05 = 1
plot: ((1 + (z - s/2)^2)^(-1.5) + (1 + (z + s/2)^2)^(-1.5))/(2*(1 + (s/2)^2)^(-1.5)) | label: axial field over its center value | samples: 400
plot: 1 | dashed
readout: field at 0.1 R over center = ((1 + (0.1 - s/2)^2)^(-1.5) + (1 + (0.1 + s/2)^2)^(-1.5))/(2*(1 + (s/2)^2)^(-1.5)) | digits: 5
```

::: predict
## A Helmholtz pair of 100-turn coils, each 10 cm in radius, carries 1 A. What is the field at the center, compared with one coil alone at its own center?

- [ ] Twice as large
- [ ] The same
- [x] About 1.43 times as large
- [ ] About 0.72 times as large

::: reveal
About 1.43 times. Each coil sits half a radius from the center, where its field has fallen to $\left(\frac45\right)^{3/2} = 0.716$ of its own center value, and two of them give 1.43. That's 899 µT here, against 628 µT for one coil at its center. The pair trades some strength for uniformity.
:::
:::

::: nameit
## Biot–Savart in pieces

A short piece of wire $d\mathbf l$ carrying I contributes $d\mathbf B = \frac{\mu_0I}{4\pi}\frac{d\mathbf l \times \mathbf r}{r^3}$ at a point a displacement r away. Split any path into many short pieces, put each piece's current at its midpoint, and add the contributions. Check the sum on shapes with known answers: a circle's center ($\frac{\mu_0I}{2R}$), its axis, and a square's center ($\frac{2\sqrt2\mu_0I}{\pi a}$).

## Helmholtz coils

Two coaxial coils of radius R spaced R apart give a field at the center of $\left(\frac45\right)^{3/2}\frac{\mu_0NI}{R}$, uniform to about 1 part in 10 000 within 0.1R of the center. Calibration coils for magnetometers and setups that cancel the Earth's field use them.

## Finite solenoids

A solenoid is a stack of loops. On its axis, a solenoid of length L and radius R with n turns per meter gives

$$B(z) = \frac{\mu_0nI}{2}\left(\frac{z + L/2}{\sqrt{(z + L/2)^2 + R^2}} - \frac{z - L/2}{\sqrt{(z - L/2)^2 + R^2}}\right),$$

which approaches $\mu_0nI$ at the center only when $L \gg R$.

## Tracking a charge

The magnetic force does no work, so a good numerical method should keep the speed constant. The **Boris method** splits each step into a half push by any electric field, an exact-length rotation by the magnetic field, and another half push: it conserves the speed to rounding error in a pure magnetic field, however many steps it takes.

## Fitting Hall data

The Hall voltage is $V_H = \frac{IB}{nqt}$, plus an offset when the voltage probes aren't perfectly opposite each other. Fitting a line to $V_H$ against I removes the offset as the intercept and gives n from the slope.
:::

::: example
## Find the field of a 10 cm length of wire carrying 1 A, 1 cm from its middle, and compare it with an infinite wire.

::: solution
1. **Field of a straight segment.** Adding Biot–Savart pieces along the segment gives
   $$B = \frac{\mu_0I}{4\pi r}\cdot\frac{2(L/2)}{\sqrt{r^2 + (L/2)^2}}$$
2. **Put in the numbers.** With r = 1 cm and a half-length of 5 cm:
   $$\begin{aligned} B &= 10^{-5} \times \frac{0.1}{\sqrt{0.01^2 + 0.05^2}} \\ &= 19.6\ \mu\text{T} \end{aligned}$$
3. **Infinite wire.**
   $$\frac{\mu_0I}{2\pi r} = 20.0\ \mu\text{T}$$
4. **Compare.** A wire ten times longer than the distance to it already acts as infinite to within 2%. The far parts of a wire contribute little, since their pieces are both distant and nearly lined up with the point.

**Answer:** the 10 cm wire makes 19.6 µT, against 20.0 µT for an infinite wire.
:::
:::

::: example
## How uniform is the field of a Helmholtz pair, and how much worse is it with the coils 20% too far apart?

::: solution
1. **At the Helmholtz spacing.** With the coils R apart, the axial field 0.1R from the center is
   $$\frac{B(0.1R)}{B(0)} = 0.99989$$
   uniform to 1.1 parts in 10 000.
2. **At 1.2R.** With the coils 20% too far apart, the same ratio is
   $$\frac{B(0.1R)}{B(0)} = 1.0034$$
   30 times less uniform, with a dip at the center.
3. **Why the Helmholtz spacing is so flat.** It makes the field's second derivative vanish at the center, so its first error is fourth order in distance.
4. **What misplacement costs.** A few millimeters of misplacement in a 10 cm coil spoils that quickly.

**Answer:** at the Helmholtz spacing the field 0.1R from the center is within 1.1 parts in 10 000 of the center value; with the coils 20% too far apart it is 30 times less uniform.
:::
:::

::: example
## A Hall bar 0.2 mm thick in a 0.5 T field reads 31.7, 62.9, 94.1, 125.3 and 156.5 mV at 1 to 5 mA. What is its carrier density?

::: solution
1. **Fit a line.** The points lie on a line of slope 31.2 V/A, with an intercept of 0.5 mV, the probes' offset.
2. **Solve for the density.** The slope is $\frac{B}{nqt}$, so $n = \frac{B}{qt \cdot \text{slope}}$, where
   $$\begin{aligned} qt \cdot \text{slope} &= 1.602 \times 10^{-19} \\ &\quad \times 2 \times 10^{-4} \times 31.2 \\ &= 1.00 \times 10^{-21} \end{aligned}$$
3. **Carrier density.**
   $$\begin{aligned} n &= \frac{0.5}{1.00 \times 10^{-21}} \\ &= 5.0 \times 10^{20}\ \text{m}^{-3} \end{aligned}$$
4. **Why fit a line.** Dividing a single reading by its current would have included the offset: at 1 mA it would give 31.7 V/A and n about 1.6% low.
5. **Another way.** Reversing the field and averaging is the other common way to cancel the offset.

**Answer:** the carrier density is $5.0 \times 10^{20}$ m⁻³.
:::
:::

::: check
kind: python

## Step 1. Write `biot_savart(path, I, pts, n)`: `path` is a list of 3D points joined by straight segments carrying current I, `pts` an M × 3 array of field points. Split each segment into n pieces at their midpoints and return the M × 3 array of fields, with μ₀ = 4π × 10⁻⁷.

```python starter
import numpy as np
mu0 = 4e-7 * np.pi

def biot_savart(path, I, pts, n=20):
    return np.zeros((len(pts), 3))

print(biot_savart([[0, 0, 0], [1, 0, 0]], 1, [[0.5, 0.1, 0]]))
```

```python solution
import numpy as np
mu0 = 4e-7 * np.pi

def biot_savart(path, I, pts, n=20):
    path = np.asarray(path, float)
    pts = np.asarray(pts, float)
    B = np.zeros_like(pts)
    for p0, p1 in zip(path[:-1], path[1:]):
        t = (np.arange(n) + 0.5) / n
        mids = p0 + np.outer(t, p1 - p0)
        dl = (p1 - p0) / n
        R = pts[:, None, :] - mids[None, :, :]
        r = np.linalg.norm(R, axis=2)
        B += mu0 * I / (4 * np.pi) * np.sum(np.cross(np.broadcast_to(dl, R.shape), R) / r[:, :, None]**3, axis=1)
    return B

print(biot_savart([[0, 0, 0], [1, 0, 0]], 1, [[0.5, 0.1, 0]]))
```

```python tests
import numpy as np
mu0 = 4e-7 * np.pi
ph = np.linspace(0, 2 * np.pi, 361)
loop = np.c_[0.1 * np.cos(ph), 0.1 * np.sin(ph), 0 * ph]
Bc = biot_savart(loop, 1, [[0, 0, 0], [0, 0, 0.1]], 20)
assert abs(Bc[0, 2] / (mu0 / 0.2) - 1) < 1e-4, f"A 10 cm loop's center field should be μ0I/2R = 6.283 µT; got {Bc[0, 2] * 1e6:.4f}."
assert abs(Bc[1, 2] / (mu0 * 0.01 / (2 * 0.02**1.5)) - 1) < 1e-4, "On the axis at z = R it should be μ0IR²/(2(R² + z²)^1.5)."
sq = [[-0.05, -0.05, 0], [0.05, -0.05, 0], [0.05, 0.05, 0], [-0.05, 0.05, 0], [-0.05, -0.05, 0]]
Bs = biot_savart(sq, 1, [[0, 0, 0]], 400)
assert abs(Bs[0, 2] / (2 * np.sqrt(2) * mu0 / (np.pi * 0.1)) - 1) < 1e-5, "A square loop's center field is 2√2 μ0I/(πa)."
```

::: right
Right. A 360-sided polygon reproduces the circle to 2 parts in 100 000, and the square to better than a part in a million, since its sides really are straight.
:::
:::

::: check
kind: python

## Step 2. Write `coil_axis(R, I, z)` for one turn's axial field, and `helmholtz_variation(R, s, span)` that puts two coils at $z = \pm s/2$, samples their total axial field at 2001 points from −span to span, and returns (max − min) divided by the center value.

```python starter
import numpy as np
mu0 = 4e-7 * np.pi

def coil_axis(R, I, z):
    return mu0 * I / (2 * R) + 0 * z

def helmholtz_variation(R, s, span):
    return 0.0

print(helmholtz_variation(0.1, 0.1, 0.01))
```

```python solution
import numpy as np
mu0 = 4e-7 * np.pi

def coil_axis(R, I, z):
    return mu0 * I * R**2 / (2 * (R**2 + z**2)**1.5)

def helmholtz_variation(R, s, span):
    z = np.linspace(-span, span, 2001)
    B = coil_axis(R, 1, z - s / 2) + coil_axis(R, 1, z + s / 2)
    return float((B.max() - B.min()) / B[1000])

print(helmholtz_variation(0.1, 0.1, 0.01))
```

```python tests
v = helmholtz_variation(0.1, 0.1, 0.01)
assert abs(v - 1.1394e-4) < 1e-7, f"At the Helmholtz spacing the field varies by 1.14e-4 within ±R/10; got {v:.4e}."
w = helmholtz_variation(0.1, 0.12, 0.01)
assert abs(w - 3.444e-3) < 1e-5 and w > 25 * v, f"At 1.2R spacing it varies by 3.4e-3; got {w:.4e}."
assert abs(helmholtz_variation(0.1, 0.1, 0.02) / v - 15.48) < 0.05, "Doubling the span multiplies the variation by about 16: the error is fourth order."
```

::: right
Right. Doubling the region multiplies the variation by about 16, the signature of a fourth-order error: the Helmholtz spacing cancels everything up to the third.
:::
:::

::: check
kind: python

## Step 3. Write `solenoid_sum(n, I, L, R, z, m)` that builds a solenoid of length L, radius R and n turns per meter from m equally spaced loops (each carrying the current of $nL/m$ turns) and returns the axial field at z. Compare with the exact formula in `solenoid_exact`. `coil_axis` is included.

```python starter
import numpy as np
mu0 = 4e-7 * np.pi

def coil_axis(R, I, z):
    return mu0 * I * R**2 / (2 * (R**2 + z**2)**1.5)

def solenoid_sum(n, I, L, R, z, m):
    return mu0 * n * I

def solenoid_exact(n, I, L, R, z):
    return mu0 * n * I

print(solenoid_sum(1000, 1, 0.1, 0.02, 0, 2000), solenoid_exact(1000, 1, 0.1, 0.02, 0))
```

```python solution
import numpy as np
mu0 = 4e-7 * np.pi

def coil_axis(R, I, z):
    return mu0 * I * R**2 / (2 * (R**2 + z**2)**1.5)

def solenoid_sum(n, I, L, R, z, m):
    zs = -L / 2 + (np.arange(m) + 0.5) * L / m
    return float(np.sum(coil_axis(R, n * I * L / m, z - zs)))

def solenoid_exact(n, I, L, R, z):
    a, b = z + L / 2, z - L / 2
    return mu0 * n * I / 2 * (a / np.sqrt(a**2 + R**2) - b / np.sqrt(b**2 + R**2))

print(solenoid_sum(1000, 1, 0.1, 0.02, 0, 2000), solenoid_exact(1000, 1, 0.1, 0.02, 0))
```

```python tests
import numpy as np
c = solenoid_exact(1000, 1, 0.1, 0.02, 0)
assert abs(c * 1e3 - 1.16676) < 1e-5, f"A 10 cm solenoid of 2 cm radius gives 1.1668 mT at its center; got {c * 1e3:.5f}."
assert abs(solenoid_sum(1000, 1, 0.1, 0.02, 0, 2000) / c - 1) < 1e-6, "2000 loops reproduce the exact formula."
e = solenoid_exact(1000, 1, 0.1, 0.02, 0.05)
assert abs(e / c - 0.52806) < 1e-4, f"At the end the field is 0.528 of the center's; got {e / c:.5f}."
```

::: right
Right. At this length-to-radius ratio of 5 the center reaches only 93% of $\mu_0nI$, and the end gets 53% of the center's field, a little more than the half that a very long solenoid would give.
:::
:::

::: check
kind: python

## Step 4. Write `boris(q, m, v0, B, dt, steps)` that moves a charge in a uniform magnetic field by the Boris rotation, returning the array of positions and the final velocity. Each step: $\mathbf t = \frac{q\mathbf B}{m}\frac{\Delta t}{2}$, $\mathbf s = \frac{2\mathbf t}{1 + t^2}$, $\mathbf v' = \mathbf v + \mathbf v \times \mathbf t$, $\mathbf v \leftarrow \mathbf v + \mathbf v' \times \mathbf s$, then $\mathbf x \leftarrow \mathbf x + \mathbf v\Delta t$.

```python starter
import numpy as np

def boris(q, m, v0, B, dt, steps):
    v = np.array(v0, float)
    x = np.zeros(3)
    xs = []
    for _ in range(steps):
        v = v + q / m * np.cross(v, B) * dt
        x = x + v * dt
        xs.append(x.copy())
    return np.array(xs), v

xs, v = boris(-1.602e-19, 9.109e-31, [1e6, 0, 0], [0, 0, 1e-3], 1e-11, 20000)
print(np.linalg.norm(v))
```

```python solution
import numpy as np

def boris(q, m, v0, B, dt, steps):
    v = np.array(v0, float)
    x = np.zeros(3)
    xs = []
    for _ in range(steps):
        t = q * np.array(B, float) / m * dt / 2
        s = 2 * t / (1 + t @ t)
        vp = v + np.cross(v, t)
        v = v + np.cross(vp, s)
        x = x + v * dt
        xs.append(x.copy())
    return np.array(xs), v

xs, v = boris(-1.602e-19, 9.109e-31, [1e6, 0, 0], [0, 0, 1e-3], 1e-11, 20000)
print(np.linalg.norm(v))
```

```python tests
import numpy as np
xs, v = boris(-1.602e-19, 9.109e-31, [1e6, 0, 0], [0, 0, 1e-3], 1e-11, 20000)
assert abs(np.linalg.norm(v) / 1e6 - 1) < 1e-12, f"The speed must stay 1e6 m/s; got {np.linalg.norm(v)}."
r = (xs[:, 1].max() - xs[:, 1].min()) / 2
assert abs(r / (9.109e-31 * 1e6 / (1.602e-19 * 1e-3)) - 1) < 1e-3, f"The orbit's radius is mv/(qB) = 5.686 mm; got {r * 1000:.4f} mm."
```

::: right
Right. After 20 000 steps the speed is still exact to rounding, while plain Euler would have spiraled outward, gaining energy from nothing on every step.
:::
:::

::: check
kind: python

## Step 5. Write `hall_density(I, VH, B, t)` that fits $V_H = aI + b$ by least squares to measured arrays (amperes and volts) and returns the carrier density $n = \frac{B}{qta}$ in m⁻³.

```python starter
import numpy as np

def hall_density(I, VH, B, t):
    return B * I[0] / (1.602e-19 * t * VH[0])

I = np.array([1, 2, 3, 4, 5]) * 1e-3
VH = np.array([31.7, 62.9, 94.1, 125.3, 156.5]) * 1e-3
print(hall_density(I, VH, 0.5, 2e-4))
```

```python solution
import numpy as np

def hall_density(I, VH, B, t):
    A = np.vstack([I, np.ones_like(I)]).T
    a, b = np.linalg.lstsq(A, VH, rcond=None)[0]
    return float(B / (1.602e-19 * t * a))

I = np.array([1, 2, 3, 4, 5]) * 1e-3
VH = np.array([31.7, 62.9, 94.1, 125.3, 156.5]) * 1e-3
print(hall_density(I, VH, 0.5, 2e-4))
```

```python tests
import numpy as np
I = np.array([1, 2, 3, 4, 5]) * 1e-3
n = hall_density(I, np.array([31.7, 62.9, 94.1, 125.3, 156.5]) * 1e-3, 0.5, 2e-4)
assert abs(n / 5.0018e20 - 1) < 1e-4, f"The slope of 31.2 V/A gives n = 5.0e20 m⁻³; got {n:.4e}."
n2 = hall_density(I, 31.2 * I, 0.5, 2e-4)
assert abs(n2 / n - 1) < 1e-9, "The offset must not change the answer: only the slope matters."
```

::: right
Right. The intercept soaks up the probes' offset, so the density comes from the slope alone, the same idea as fitting a battery's line.
:::
:::

::: check
kind: parts
given: N = 50 | 200; R = 5 | 15; I = 0.5 | 2

## A Helmholtz pair has {N} turns per coil, radius {R} cm, and carries {I} A.

::: part
answer: 0.8^1.5*4*pi*1e-7*N*I/(R/100)*1e6
unit: µT
tolerance: 0.5%

### What field does it make at its center?

::: misses
- [4*pi*1e-7*N*I/(R/100)*1e6] Each coil gives $\frac{\mu_0NI}{2R}$ at its own center, but the midpoint is R/2 away from each.
- [any] $\left(\frac45\right)^{3/2}\frac{\mu_0NI}{R}$.
:::
:::

::: part
answer: R
unit: cm
tolerance: 0.5%

### How far apart should the coils be for the most uniform field?

::: misses
- [2*R] The spacing equals the radius, not the diameter.
- [any] The Helmholtz spacing is one radius.
:::
:::
:::

::: check
given: v = 1 | 5; B = 1 | 10
answer: 9.109e-31*v*1e6/(1.602e-19*B/1000)*1000
unit: mm
tolerance: 0.5%

## An electron moves at {v} × 10⁶ m/s square to a {B} mT field. What is the radius of the circle a correct simulation should trace?

::: right
Right. $r = \frac{mv}{qB}$; a simulation that drifts from it is gaining or losing energy it shouldn't.
:::

::: misses
- [9.109e-31*v*1e6*1.602e-19*B/1000] Divide by qB.
- [any] $r = \frac{mv}{qB}$.
:::
:::

::: explain
## Why is it important that a simulation of a charge in a magnetic field keep the speed exactly constant?

::: model
A magnetic force is always perpendicular to the velocity, so it does no work: in the real motion the speed never changes and the charge circles at a fixed radius forever. A numerical method that doesn't respect this makes a small error in the speed every step, and those errors don't cancel; plain Euler, for instance, always makes the speed slightly larger, so a simulated electron spirals outward and a simulated plasma heats up from nothing. Over the millions of steps of a beam or plasma simulation, that becomes a large, unphysical effect. The Boris method rotates the velocity by an exact-length rotation each step, so the speed is preserved to rounding error no matter how long the run is.
:::
:::

::: practice

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

## Field at the center of a one-turn loop of radius {R} cm carrying {I} A?

::: misses
- [any] $\frac{\mu_0I}{2R}$.
:::
:::

::: check
given: a = 2 | 10; I = 0.5 | 5
answer: 2*sqrt(2)*4*pi*1e-7*I/(pi*a/100)*1e6
unit: µT
tolerance: 0.5%

## Field at the center of a square loop {a} cm on a side carrying {I} A?

::: misses
- [any] $\frac{2\sqrt2\mu_0I}{\pi a}$.
:::
:::
:::
