---
title: Computing fields numerically
heading: Superposition by computer, checked against the formulas
eyebrow: B2 · Lesson 13 · Computing fields
xp: 50
---

::: hook
The formulas of lesson 5 cover a handful of symmetric shapes. A real electrode, a PCB trace or an irregular charged part has no formula. But superposition still holds, so a computer can do what the integral does: chop the charge into many small pieces, add up their fields as point charges, and refine until the answer stops changing. Field solvers in electronics design start from exactly this idea. In this lab you'll write one in NumPy and test it against cases where the answer is known.
:::

::: play
- The solid curve is the exact field of a charged rod (half-length $a$, 2 nC/m) on its perpendicular bisector. The dashed curves are an infinitely long line and a point charge with the rod's total charge.
- Close to the rod it looks like an infinite line; far away, like a point. In between, neither formula works, and that's where numerical summing earns its keep.
- Make the rod longer. Where does the changeover move?
:::
:::

```sim plot
view: graph
x: y = 0.2..30 cm
y: E = 1..100000 V/m log
slider: a = 1..10 step 0.5 = 5 cm
plot: 2*8.988e9*2e-9*(a/100)/((y/100)*sqrt((y/100)^2 + (a/100)^2)) | label: rod, exact
plot: 2*8.988e9*2e-9/(y/100) | label: infinite line | dashed | color: ch2
plot: 8.988e9*2e-9*2*(a/100)/(y/100)^2 | label: point charge | dashed | color: ch3
```

::: predict
## You approximate a charged rod by $n$ equal point charges at the middles of $n$ equal segments. Roughly how does the error behave as $n$ grows?

- [ ] It stays constant: point charges never match a continuous rod
- [x] It shrinks quickly, about as $1/n^2$
- [ ] It shrinks as $1/n$
- [ ] It grows, because more charges add more error

::: reveal
It shrinks as about $1/n^2$. Placing each point charge at its segment's middle is the midpoint rule for the integral (A6), whose error falls as the square of the segment length. For a 10 cm rod seen from 2 cm away, 10 pieces are within 0.06% and 50 pieces within 0.002%.
:::
:::

::: nameit
## Superposition in code

For point charges $q_j$ at positions $\mathbf r_j$, the field at a point $\mathbf r$ is

$$\mathbf E(\mathbf r) = \sum_j kq_j\frac{\mathbf r - \mathbf r_j}{|\mathbf r - \mathbf r_j|^3}$$

In NumPy, with sources as an $N \times 3$ array and field points as $M \times 3$, broadcasting builds all $M \times N$ separation vectors at once: `d = pts[:, None, :] - src[None, :, :]`. Divide by the cube of each distance, weight by the charges, and sum over the sources.

## Discretizing continuous charge

Chop a line of charge into $n$ segments of length $\Delta x$, each carrying $\lambda\Delta x$ at its midpoint. As $n$ grows the sum approaches the integral, with error about $\frac{1}{n^2}$. Surfaces work the same way with small patches carrying $\sigma\Delta A$.

## Testing a field code

- **One point charge** must give exactly $kq/r^2$, pointing away.
- **A symmetric shape** must reproduce its formula: a rod on its bisector, a ring on its axis.
- **Refine and compare:** doubling $n$ should change the answer by about a quarter of the remaining error.
- **Check far-field behavior:** any neutral pair of charges must fall off as $1/r^3$ far away, the dipole law; measuring the exponent on a log-log scale checks the whole calculation at once.
:::

::: example
## A 10 cm rod carries 2 nC/m. What is its field 2 cm out on its bisector, exactly and with 10 point charges?

::: solution
1. **Exact field.**
   $$\begin{aligned} E &= \frac{2k\lambda a}{y\sqrt{y^2 + a^2}} \\ &= \frac{2 \times 8.988 \times 10^9}{0.02\sqrt{0.0004 + 0.0025}} \\ &\quad \times 2 \times 10^{-9} \times 0.05 \\ &= 1669.0\ \text{V/m} \end{aligned}$$
2. **Ten point charges.** With 10 midpoint charges of 0.2 nC each, the sum is 1669.9 V/m, high by 0.055%.
3. **Two hundred point charges.** With 200, it's 1669.03 V/m.

**Answer:** the exact field is 1669.0 V/m; 10 point charges give 1669.9 V/m (0.055% high), and 200 give 1669.03 V/m.
:::
:::

::: example
## How can you check numerically that a dipole's field falls as $1/r^3$?

::: solution
1. **Two distances.** Compute the field at two distances $r_1$ and $r_2$ along the axis.
2. **Slope on a log-log plot.**
   $$\text{slope} = \frac{\ln(E_2/E_1)}{\ln(r_2/r_1)}$$
3. **Far out.** For ±1 nC charges 1 mm apart, distances of 2 and 5 cm give −3.001.
4. **Close in.** At 2 and 4 mm, it's −3.14: the dipole law holds only far compared with the separation.

**Answer:** find the log-log slope between two distances on the axis; for this dipole it's −3.001 at 2 and 5 cm, very close to −3.
:::
:::

::: check
kind: python

## Step 1. Write `field(q, src, pts)` returning an $M \times 3$ array of field vectors at the $M$ points `pts`, from charges `q` (length $N$) at positions `src` ($N \times 3$), using $k$ = 8.988 × 10⁹.

```python starter
import numpy as np
k = 8.988e9

def field(q, src, pts):
    pts = np.atleast_2d(pts).astype(float)
    return np.zeros_like(pts)

print(field([1e-9], [[0, 0, 0]], [[0.03, 0.04, 0]]))
```

```python solution
import numpy as np
k = 8.988e9

def field(q, src, pts):
    q = np.asarray(q, float)
    src = np.atleast_2d(src).astype(float)
    pts = np.atleast_2d(pts).astype(float)
    d = pts[:, None, :] - src[None, :, :]
    r3 = np.linalg.norm(d, axis=2) ** 3
    return k * np.sum(q[None, :, None] * d / r3[:, :, None], axis=1)

print(field([1e-9], [[0, 0, 0]], [[0.03, 0.04, 0]]))
```

```python tests
import numpy as np
E = field([1e-9], [[0, 0, 0]], [[0.03, 0.04, 0]])
assert E.shape == (1, 3), "Return one 3-vector per field point."
assert np.allclose(E[0], [2157.12, 2876.16, 0]), f"1 nC at the origin gives (2157, 2876, 0) V/m at (3, 4, 0) cm; got {E[0]}."
E = field([1e-9, 1e-9], [[-0.01, 0, 0], [0.01, 0, 0]], [[0, 0, 0], [0, 0.01, 0]])
assert np.allclose(E[0], 0, atol=1e-6), "Midway between equal charges the field cancels."
assert E[1, 0] == 0 or abs(E[1, 0]) < 1e-6, "Above the midpoint the x parts cancel."
assert np.isclose(E[1, 1], 2 * k * 1e-9 * 0.01 / (2e-4) ** 1.5), "Above the midpoint the y parts add."
```

::: right
Right. One call computes every source at every point, with no Python loops.
:::
:::

::: check
kind: python

## Step 2. Write `rod_field(lam, a, y, n)` returning $E_y$ at $(0, y, 0)$ from a rod along $x$ from $-a$ to $a$ carrying `lam` C/m, approximated by `n` charges at segment midpoints. `field` is included.

```python starter
import numpy as np
k = 8.988e9

def field(q, src, pts):
    q = np.asarray(q, float); src = np.atleast_2d(src).astype(float); pts = np.atleast_2d(pts).astype(float)
    d = pts[:, None, :] - src[None, :, :]
    return k * np.sum(q[None, :, None] * d / (np.linalg.norm(d, axis=2) ** 3)[:, :, None], axis=1)

def rod_field(lam, a, y, n):
    return 0.0

print(rod_field(2e-9, 0.05, 0.02, 10))
```

```python solution
import numpy as np
k = 8.988e9

def field(q, src, pts):
    q = np.asarray(q, float); src = np.atleast_2d(src).astype(float); pts = np.atleast_2d(pts).astype(float)
    d = pts[:, None, :] - src[None, :, :]
    return k * np.sum(q[None, :, None] * d / (np.linalg.norm(d, axis=2) ** 3)[:, :, None], axis=1)

def rod_field(lam, a, y, n):
    dx = 2 * a / n
    xs = -a + dx * (np.arange(n) + 0.5)
    src = np.stack([xs, np.zeros(n), np.zeros(n)], axis=1)
    return field(np.full(n, lam * dx), src, [[0, y, 0]])[0, 1]

print(rod_field(2e-9, 0.05, 0.02, 10))
```

```python tests
import numpy as np
exact = 2 * k * 2e-9 * 0.05 / (0.02 * np.sqrt(0.02**2 + 0.05**2))
e10 = rod_field(2e-9, 0.05, 0.02, 10) / exact - 1
e200 = rod_field(2e-9, 0.05, 0.02, 200) / exact - 1
assert abs(e200) < 1e-5, f"With 200 pieces the rod field should match the formula to 1e-5; relative error {e200:.2e}."
assert abs(e10) < 1e-3 and abs(e10) > 10 * abs(e200), "The error should shrink quickly as n grows."
```

::: right
Right. Midpoint charges converge to the exact rod field as $1/n^2$.
:::
:::

::: check
kind: python

## Step 3. Write `axis_exponent(q, d, r1, r2)`: for charges $+q$ at $(-d/2, 0, 0)$ and $-q$ at $(d/2, 0, 0)$, compute the field strength on the $x$ axis at $r_1$ and $r_2$ and return $\frac{\ln(E_2/E_1)}{\ln(r_2/r_1)}$. `field` is included.

```python starter
import numpy as np
k = 8.988e9

def field(q, src, pts):
    q = np.asarray(q, float); src = np.atleast_2d(src).astype(float); pts = np.atleast_2d(pts).astype(float)
    d = pts[:, None, :] - src[None, :, :]
    return k * np.sum(q[None, :, None] * d / (np.linalg.norm(d, axis=2) ** 3)[:, :, None], axis=1)

def axis_exponent(q, d, r1, r2):
    return 0.0

print(axis_exponent(1e-9, 1e-3, 0.02, 0.05))
```

```python solution
import numpy as np
k = 8.988e9

def field(q, src, pts):
    q = np.asarray(q, float); src = np.atleast_2d(src).astype(float); pts = np.atleast_2d(pts).astype(float)
    d = pts[:, None, :] - src[None, :, :]
    return k * np.sum(q[None, :, None] * d / (np.linalg.norm(d, axis=2) ** 3)[:, :, None], axis=1)

def axis_exponent(q, d, r1, r2):
    src = [[-d / 2, 0, 0], [d / 2, 0, 0]]
    E1 = np.linalg.norm(field([q, -q], src, [[r1, 0, 0]]))
    E2 = np.linalg.norm(field([q, -q], src, [[r2, 0, 0]]))
    return np.log(E2 / E1) / np.log(r2 / r1)

print(axis_exponent(1e-9, 1e-3, 0.02, 0.05))
```

```python tests
x = axis_exponent(1e-9, 1e-3, 0.02, 0.05)
assert abs(x + 3) < 0.01, f"Far away a dipole's field should fall as 1/r³ (exponent −3); got {x:.4f}."
y = axis_exponent(1e-9, 1e-3, 0.002, 0.004)
assert y < -3.05, f"Close in, at distances comparable to the separation, the exponent should differ from −3; got {y:.4f}."
```

::: right
Right. −3.00 far away and −3.14 up close: the dipole formula is a far-field approximation, and the computer shows exactly where it stops working.
:::
:::

::: check
given: n1 = 10 | 20; e1 = 0.06 | 0.1; k = 2 | 4
answer: e1/k^2
tolerance: 0.5%

## Step 4. A midpoint-rule field sum with {n1} pieces is off by {e1}%. The error falls as $1/n^2$. What error do you expect with {k} times as many pieces, in percent?

::: right
Right. $\frac{e}{k^2}$ = {answer}%.
:::

::: misses
- [e1/k] The midpoint rule's error falls as $1/n^2$, not $1/n$.
- [any] Not yet. $k$ times the pieces divides the error by $k^2$.
:::
:::

::: explain
## Why is placing each piece's charge at the middle of its segment so much better than placing it at one end?

::: model
Treating a segment as a point charge at its middle is the midpoint rule for the integral. Its errors on the two halves of each segment nearly cancel, because the field's variation is roughly linear across a small segment: the near half pulls the answer one way and the far half the other. Putting the charge at an end has no such cancellation, so it leaves an error proportional to the segment length, $1/n$. The midpoint version leaves only the curvature's effect, proportional to the length squared, $1/n^2$.
:::
:::

::: practice

::: check
given: lam = 1 | 4; L = 10 | 20; n = 10 | 50
answer: lam*L/100/n*1e3
unit: pC
tolerance: 0.5%

## A {L} cm rod carrying {lam} nC/m is split into {n} pieces. How much charge does each carry?

::: misses
- [any] $\lambda\Delta x$ with $\Delta x = L/n$.
:::
:::

::: check
given: r1 = 2 | 5; r2 = 4 | 10
answer: (r1/r2)^3
tolerance: 0.5%

## A dipole's far field is measured at {r1} cm and {r2} cm. What ratio $E_2/E_1$ do you expect?

::: misses
- [(r1/r2)^2] A dipole falls as $1/r^3$.
- [any] $(r_1/r_2)^3$.
:::
:::

::: check
given: N = 100 | 1000; M = 50 | 400
answer: N*M
tolerance: 0.01%

## A field code sums {N} source charges at each of {M} field points. How many pairwise terms does it compute?

::: misses
- [any] Every source at every point.
:::
:::
:::
