---
title: "Lab: Poisson's equation in code"
heading: Potentials from charge, by integration and relaxation
eyebrow: A9 · Lesson 48 · Lab: Poisson's equation
xp: 60
---

::: hook
Lesson 47 solved Poisson's equation by hand where symmetry made it one-dimensional. In this lab you'll solve it numerically: integrate a junction's charge twice to get its built-in voltage, relax a two-dimensional grid with a charge inside, see how much over-relaxation speeds convergence, and build potentials by adding up the contributions of small pieces of charge, a ring and a ball, checking each against its formula.
:::

::: play
- The curve is the potential of a uniformly charged ball of radius $R$, in units where $\frac{kQ}{R_0} = 1$ for a reference radius.
- Outside, it's $\frac{kQ}{r}$, as if all the charge were at the center. Inside, it's a downward parabola, reaching $\frac32$ of the surface value at the center.
- Shrink the ball: the same charge packed tighter raises the center potential, as $\frac{3kQ}{2R}$ says.
:::

```sim plot
view: graph
x: r = 0..4
y: V = 0..4
slider: R = 0.5..3 step 0.1 = 1
plot: (3/(2*R) - r^2/(2*R^3))*step(R - r) + (1/r)*step(r - R) | label: V(r) | samples: 600
marker: r = R | label: surface
readout: center potential = 3/(2*R) | digits: 4
```

::: predict
## Jacobi relaxation on a 20 × 20 grid takes 369 sweeps to converge. About how many does successive over-relaxation (SOR) with the best factor take?

- [ ] About 300
- [ ] About 180
- [x] About 45
- [ ] About 4

::: reveal
About 45: 44, in fact. SOR updates each point using the newest neighbor values and overshoots the average by a factor $\omega$; with $\omega = \frac{2}{1 + \sin(\pi/n)} = 1.73$, the number of sweeps grows like $n$ instead of $n^2$. On a 200 × 200 grid the advantage would be about 100 times.
:::
:::

::: nameit
## One dimension: integrate twice

$V'' = -\rho/\varepsilon$ can be integrated directly: the field is $E(x) = \frac1\varepsilon\int\rho\,dx$ from a point where $E = 0$, and $V(x) = -\int E\,dx$. Cumulative sums (`np.cumsum` with the trapezoid rule) do both steps on a grid.

## Two dimensions: relaxation

On a grid with spacing $h$, $\nabla^2V = -\rho/\varepsilon$ becomes

$$V_{ij} = \tfrac14\left(V_{i+1,j} + V_{i-1,j} + V_{i,j+1} + V_{i,j-1}\right) + \tfrac{h^2}{4}\frac{\rho_{ij}}{\varepsilon}$$

- **Jacobi** recomputes every point from the previous sweep's values. Vectorized with NumPy slices, each sweep is fast, but it needs about $n^2$ sweeps.
- **Gauss–Seidel** uses each new value as soon as it's computed.
- **SOR** moves each point $\omega$ times as far as Gauss–Seidel would, with $1 < \omega < 2$; the best $\omega$ for a square grid is $\frac{2}{1 + \sin(\pi/n)}$.

## Superposition

$V(\mathbf r) = \sum\frac{k\,\Delta q}{|\mathbf r - \mathbf r'|}$ over small pieces of charge. It needs no grid or boundary, just a sum, and it's exact in the limit of small pieces.
:::

::: example
## A ring of radius $R$ carries charge $Q$. What is the potential on its axis?

::: solution
1. **Same distance from every piece.** Every piece of the ring is the same distance $\sqrt{R^2 + z^2}$ from a point on the axis, so the sum is simply
   $$V = \frac{kQ}{\sqrt{R^2 + z^2}}$$
2. **Put in numbers.** For 1 nC on a ring of radius 5 cm, at 12 cm along the axis:
   $$\begin{aligned} V &= \frac{8.988}{0.13} \\ &= 69.1\ \text{V} \end{aligned}$$
3. **Compare with a numerical sum.** A numerical sum over the ring's pieces gives the same, since every term is equal. Off the axis the distances vary and the sum needs a computer.

**Answer:** $V = \frac{kQ}{\sqrt{R^2 + z^2}}$, which is 69.1 V for 1 nC on a 5 cm ring at 12 cm.
:::
:::

::: example
## What does the grid equation give for $\nabla^2V = -1$ on the unit square with $V = 0$ on the edges?

::: solution
1. **Relax the grid.** Relaxing a 40 × 40 grid until it stops changing gives a dome with its peak at the center, $V = 0.0736$.
2. **Compare with the exact value.** The exact value for the continuous problem is 0.073 671, so the grid is within 0.1%.
3. **Interpret.** This is the shape of a uniformly loaded square membrane, and of the potential in a uniformly charged square region inside a grounded box.

**Answer:** a dome peaking at $V = 0.0736$ in the center.
:::
:::

::: check
given: Q = 1 | 5; R = 3 | 5; z = 4 | 12
answer: 8.988e9*Q*1e-9/sqrt((R/100)^2 + (z/100)^2)
unit: V
tolerance: 0.5%

## A ring of radius {R} cm carries {Q} nC. What is the potential on its axis, {z} cm from its center?

::: right
Right. $\frac{kQ}{\sqrt{R^2 + z^2}}$ = {answer}.
:::

::: misses
- [8.988e9*Q*1e-9/(z/100)] Every piece of the ring is $\sqrt{R^2 + z^2}$ away, not $z$.
- [any] Not yet. All of the charge is at the same distance from the point.
:::
:::

::: check
given: n = 20 | 50 | 100
answer: 2/(1 + sin(pi/n))
tolerance: 0.5%

## What is the best SOR factor for an {n} × {n} grid?

::: right
Right. $\omega = \frac{2}{1 + \sin(\pi/n)}$ = {answer}, closer to 2 for finer grids.
:::

::: misses
- [1] That's Gauss–Seidel, with no over-relaxation.
- [any] Not yet. $\omega_\text{opt} = \frac{2}{1 + \sin(\pi/n)}$.
:::
:::

::: check
kind: python
given: r = 2 | 3 | 4 | 5 | 8

## A 1D junction has $\rho/\varepsilon = -1$ on $-1 < x < 0$ and $+r$ on $0 < x < 1/r$ ($r$ = {r}), zero elsewhere. On a grid of 20 001 points from $-1.5$ to 1.5, integrate twice (trapezoid cumulative sums, $E = 0$ and $V = 0$ at the left end, $E = \int\rho/\varepsilon$, $V = -\int E$), and set `Vbi` to $V$ at the right end.

```python starter
import numpy as np

Vbi = 0.0
print(Vbi)
```

```python solution
import numpy as np

x = np.linspace(-1.5, 1.5, 20001)
rho = np.where((x > -1) & (x < 0), -1.0, 0.0) + np.where((x > 0) & (x < 1 / r), r, 0.0)

def cumtrapz(f, x):
    out = np.zeros_like(f)
    out[1:] = np.cumsum((f[1:] + f[:-1]) / 2 * np.diff(x))
    return out

E = cumtrapz(rho, x)
V = -cumtrapz(E, x)
Vbi = V[-1]
print(Vbi)
```

```python tests
assert abs(Vbi - (1 + 1 / r) / 2) < 1e-3, f"The built-in voltage is (1 + 1/r)/2 = {(1 + 1 / r) / 2:.4f}; got {Vbi}."
```

::: right
Right. Two integrations turn the charge into a voltage step, most of it across the lightly charged side.
:::
:::

::: check
kind: python

## Solve $\nabla^2V = -1$ on the unit square with $V = 0$ on the edges, using vectorized Jacobi on a 41 × 41 grid of points (spacing $1/40$) until the largest change in a sweep is below $10^{-9}$. Set `Vc` to the center value.

```python starter
import numpy as np

Vc = 0.0
print(Vc)
```

```python solution
import numpy as np

n = 40
h = 1 / n
V = np.zeros((n + 1, n + 1))
while True:
    new = V.copy()
    new[1:-1, 1:-1] = 0.25 * (V[2:, 1:-1] + V[:-2, 1:-1] + V[1:-1, 2:] + V[1:-1, :-2]) + h * h / 4
    change = np.max(np.abs(new - V))
    V = new
    if change < 1e-9:
        break
Vc = V[n // 2, n // 2]
print(Vc)
```

```python tests
assert abs(Vc - 0.0736713) < 0.0005, f"The center value should be close to the exact 0.07367; got {Vc}."
```

::: right
Right. A dome peaking at 0.0736, within a fraction of a percent of the continuous answer.
:::
:::

::: check
kind: python

## On a 21 × 21 grid with $V = 1$ on the top edge and 0 on the others, count the Gauss–Seidel sweeps ($\omega = 1$) and the SOR sweeps ($\omega = \frac{2}{1 + \sin(\pi/20)}$) needed until the largest change in a sweep is below $10^{-6}$. Set `it_gs` and `it_sor`, and `Vc` to SOR's center value.

```python starter
import math
import numpy as np

it_gs = it_sor = 0
Vc = 0.0
print(it_gs, it_sor, Vc)
```

```python solution
import math
import numpy as np

def solve(n, w, tol=1e-6):
    V = np.zeros((n + 1, n + 1))
    V[0, :] = 1
    it = 0
    while True:
        it += 1
        biggest = 0.0
        for i in range(1, n):
            for j in range(1, n):
                d = 0.25 * (V[i - 1, j] + V[i + 1, j] + V[i, j - 1] + V[i, j + 1]) - V[i, j]
                V[i, j] += w * d
                biggest = max(biggest, abs(d))
        if biggest < tol:
            return it, V

it_gs, _ = solve(20, 1.0)
it_sor, V = solve(20, 2 / (1 + math.sin(math.pi / 20)))
Vc = V[10, 10]
print(it_gs, it_sor, Vc)
```

```python tests
assert it_sor * 5 < it_gs, f"SOR should need far fewer sweeps than Gauss-Seidel; got {it_sor} against {it_gs}."
assert abs(Vc - 0.25) < 1e-4, f"By symmetry the center of a square with one side at 1 V sits at 0.25 V; got {Vc}."
```

::: right
Right. Over-relaxation cuts the sweeps by nearly a factor of ten even on this small grid.
:::
:::

::: check
kind: python

## Build the potential on the axis of a ring (radius 5 cm, 1 nC) by summing $\frac{k\,\Delta q}{|\mathbf r - \mathbf r'|}$ over 1000 pieces, at $z$ = 12 cm. Set `V` and `formula`.

```python starter
import numpy as np

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

```python solution
import numpy as np

k, Q, R, z, N = 8.988e9, 1e-9, 0.05, 0.12, 1000
ph = np.arange(N) * 2 * np.pi / N
pieces = np.stack([R * np.cos(ph), R * np.sin(ph), 0 * ph], axis=1)
d = np.linalg.norm(np.array([0, 0, z]) - pieces, axis=1)
V = np.sum(k * (Q / N) / d)
formula = k * Q / np.sqrt(R * R + z * z)
print(V, formula)
```

```python tests
assert abs(formula - 69.138) < 0.01, f"The formula gives 69.14 V; got {formula}."
assert abs(V - formula) < 1e-9, f"On the axis every piece is equally far, so the sum matches exactly; got {V}."
```

::: right
Right. 69.1 V. Move the point off the axis and the same sum still works; the formula doesn't.
:::
:::

::: check
kind: python

## Find the potential at the center of a uniformly charged ball ($Q$ = 1 nC, $R$ = 10 cm) by adding thin shells: a shell of radius $r$ and charge $dq$ contributes $\frac{k\,dq}{r}$ at the center. Use 10 000 midpoint shells and set `Vc` and `formula` ($\frac{3kQ}{2R}$).

```python starter
import numpy as np

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

```python solution
import numpy as np

k, Q, R, N = 8.988e9, 1e-9, 0.1, 10000
rho = Q / (4 / 3 * np.pi * R**3)
r = (np.arange(N) + 0.5) * R / N
dq = rho * 4 * np.pi * r**2 * (R / N)
Vc = np.sum(k * dq / r)
formula = 3 * k * Q / (2 * R)
print(Vc, formula)
```

```python tests
assert abs(formula - 134.82) < 0.01, f"3kQ/(2R) = 134.82 V; got {formula}."
assert abs(Vc - formula) < 1e-3, f"Adding shells should give the same; got {Vc}."
```

::: right
Right. Each shell contributes $k\,dq/r$ at the center however its charge is spread, so the ball is a stack of easy pieces.
:::
:::

::: explain
## Why does relaxation on a fine grid converge so slowly, and why does over-relaxation help?

::: model
Each Jacobi or Gauss–Seidel sweep only lets information travel one grid point: a point learns about the boundary through a chain of neighbors averaging each other. Smooth, large-scale errors, a whole region sitting slightly too high, are barely reduced by local averaging, and on an $n \times n$ grid it takes on the order of $n^2$ sweeps for them to decay. Over-relaxation pushes each point past the local average in the direction it was already moving, which carries those large-scale corrections across the grid much faster, so the sweeps needed grow only like $n$. Multigrid methods go further by solving the smooth error on coarser grids, where it isn't smooth any more.
:::
:::

::: practice

::: check
given: Q = 0.1..10; R = 1..20; z = 0..30
answer: 8.988e9*Q*1e-9/sqrt((R/100)^2 + (z/100)^2)
unit: V
tolerance: 0.5%

## On-axis ring potential in volts: {Q} nC, radius {R} cm, at {z} cm?

::: misses
- [any] $\frac{kQ}{\sqrt{R^2 + z^2}}$.
:::
:::

::: check
given: n = 10..500 int
answer: 2/(1 + sin(pi/n))
tolerance: 0.5%

## Best SOR factor for an {n} × {n} grid?

::: misses
- [any] $\frac{2}{1 + \sin(\pi/n)}$.
:::
:::
:::
