Finite Differences for Laplace and Poisson
Separation of variables solves boxes, cylinders and spheres. A real cross-section, a track on a laminate under a shield can, a connector pin, a high-voltage bushing, has no such symmetry, and every field solver used in industry is numerical. The simplest of them, and the one whose behaviour is easiest to understand, replaces the continuous potential by its values on a grid and Laplace's equation by an averaging rule. This lesson builds that solver in a few lines of NumPy, then does what every engineer must do with a numerical result: validate it against an exact solution and check convergence as the grid is refined.
The five-point stencil
On a square grid of spacing , write . Taylor expansion of the second derivatives (Finite Differences) gives
with an error proportional to . Setting it equal to (Poisson) or zero (Laplace):
In a charge-free region every node is the average of its four neighbours: the discrete form of the mean-value property of Laplace's equation.
Boundary conditions. Electrode nodes are fixed (Dirichlet). A symmetry plane across which no field crosses is a Neumann condition , handled with a mirrored ghost node, and halves the problem. An open region is closed with a grounded box far enough away that moving it changes the answer negligibly, a convergence check of its own.
Solving. The equations form a sparse linear system, one row per unknown node with at most five entries (Sparse Matrices). Two families of methods:
- Iterative relaxation: Jacobi replaces every node by its neighbours' average; Gauss–Seidel uses new values as soon as they exist; SOR over-corrects by a factor between 1 and 2 and, with near its optimum , needs about sweeps instead of (Jacobi and Gauss–Seidel, Poisson in 2-D). Memory is tiny and the code is three lines.
- Direct sparse factorisation (
scipy.sparse.linalg.spsolve): exact for the discrete system, fast for the tens of thousands of unknowns of a 2-D problem.
Quantities from . The field is the negative gradient (central differences); the charge on an electrode is around it; the capacitance follows from or from the energy, with over all grid edges (in 2-D, per metre of depth).
Worked example: one Jacobi sweep by hand
Given: a square trough on a grid (): lid nodes at , walls at , the nine interior nodes starting at .
Find: the interior values after the first Jacobi sweep, and the exact answer of this coarse discrete system at the centre.
Solve: only the three nodes touching the lid have a nonzero neighbour after the first sweep: each becomes ; the other six stay at . By the four-wall symmetry argument of Separation of Variables, which holds for the discrete equations too, the converged centre value is exactly on any grid.
Check: information spreads one node per Jacobi sweep, so reaching the far wall of an grid takes at least sweeps and converging takes of order : this is why Jacobi is slow and why SOR or a direct solver is used for real grids.
In Python: validate against the exact series
The code first relaxes a grid with Jacobi until the largest change per sweep is below , then solves the same problem directly on four grids and compares with the separation-of-variables series.
import numpy as np
import scipy.sparse as sp
import scipy.sparse.linalg as spla
def solve_laplace(fixed, val):
"""Five-point Laplace on a grid. fixed: True where V is prescribed (val). Edges must be fixed."""
free = ~fixed
idx = -np.ones(fixed.shape, dtype=np.int64)
idx[free] = np.arange(int(free.sum()))
I, J = np.nonzero(free)
k = idx[I, J]
rows, cols, data = [k], [k], [np.full(k.size, -4.0)]
b = np.zeros(k.size)
for di, dj in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
In, Jn = I + di, J + dj
nf = free[In, Jn]
rows.append(k[nf]); cols.append(idx[In[nf], Jn[nf]]); data.append(np.ones(int(nf.sum())))
np.add.at(b, k[~nf], -val[In[~nf], Jn[~nf]]) # known neighbours go to the right side
A = sp.csr_matrix((np.concatenate(data), (np.concatenate(rows), np.concatenate(cols))))
V = val.copy()
V[free] = spla.spsolve(A, b)
return V
def series(x, y, V0=10.0, nmax=399): # exact trough solution (a = b = 1)
n = np.arange(1, nmax + 1, 2)
r = np.exp(n*np.pi*(y - 1)) * (1 - np.exp(-2*n*np.pi*y)) / (1 - np.exp(-2*n*np.pi))
return float(np.sum(4*V0/(n*np.pi) * np.sin(n*np.pi*x) * r))
N = 16 # Jacobi on a coarse grid
V = np.zeros((N + 1, N + 1)); V[-1, 1:-1] = 10.0 # row = y; lid on top, corners at 0 V
sweeps = 0
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])
sweeps += 1
change = float(np.max(np.abs(new - V)))
V = new
if change < 1e-6:
break
print(f"Jacobi, h = a/{N}: {sweeps} sweeps, V(centre) = {V[N//2, N//2]:.4f} V, "
f"V(0.5, 0.75) = {V[3*N//4, N//2]:.4f} V")
exact = series(0.5, 0.75)
print(f"series at (0.5, 0.75): {exact:.5f} V")
print(" h V(0.5,0.75) error ratio")
prev = None
for N in [8, 16, 32, 64]:
fixed = np.zeros((N + 1, N + 1), bool)
fixed[0, :] = fixed[-1, :] = fixed[:, 0] = fixed[:, -1] = True
val = np.zeros((N + 1, N + 1)); val[-1, 1:-1] = 10.0
Vd = solve_laplace(fixed, val)
err = Vd[3*N//4, N//2] - exact
print(f" a/{N:<3d} {Vd[3*N//4, N//2]:10.5f} {err:+.5f} {'' if prev is None else f'{prev/err:6.2f}'}")
prev = errJacobi, h = a/16: 582 sweeps, V(centre) = 2.4999 V, V(0.5, 0.75) = 5.3932 V
series at (0.5, 0.75): 5.40529 V
h V(0.5,0.75) error ratio
a/8 5.36080 -0.04450
a/16 5.39325 -0.01204 3.70
a/32 5.40222 -0.00307 3.92
a/64 5.40452 -0.00077 3.98
Two lessons in six lines. First, Jacobi stopped when the change per sweep fell below , yet the centre is still short of the exact : a small change per sweep is not a small error, because slow solvers creep. Second, halving cuts the error by a factor approaching 4: the convergence the Taylor analysis predicts. Seeing that ratio is the evidence that the solver is right; a ratio that drifts means a bug or a singularity.
In Python: fringing of a parallel-plate capacitor
Two thin plates of width and gap (any length unit: in 2-D the ratio is dimensionless) at sit in the middle of a grounded box . The energy on the grid edges gives ; the ideal value is .
import numpy as np
import scipy.sparse as sp
import scipy.sparse.linalg as spla
import matplotlib.pyplot as plt
def solve_laplace(fixed, val):
free = ~fixed
idx = -np.ones(fixed.shape, dtype=np.int64); idx[free] = np.arange(int(free.sum()))
I, J = np.nonzero(free); k = idx[I, J]
rows, cols, data, b = [k], [k], [np.full(k.size, -4.0)], np.zeros(k.size)
for di, dj in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
In, Jn = I + di, J + dj; nf = free[In, Jn]
rows.append(k[nf]); cols.append(idx[In[nf], Jn[nf]]); data.append(np.ones(int(nf.sum())))
np.add.at(b, k[~nf], -val[In[~nf], Jn[~nf]])
A = sp.csr_matrix((np.concatenate(data), (np.concatenate(rows), np.concatenate(cols))))
V = val.copy(); V[free] = spla.spsolve(A, b)
return V
def plates(h, W=24.0, H=16.0, w=4.0, d=1.0):
x = np.linspace(-W/2, W/2, int(round(W/h)) + 1); y = np.linspace(-H/2, H/2, int(round(H/h)) + 1)
X, Y = np.meshgrid(x, y)
fixed = np.zeros(X.shape, bool); val = np.zeros(X.shape)
fixed[0, :] = fixed[-1, :] = fixed[:, 0] = fixed[:, -1] = True # grounded box
on = np.abs(X) <= w/2 + 1e-9
top, bot = on & (np.abs(Y - d/2) < 1e-9), on & (np.abs(Y + d/2) < 1e-9)
fixed |= top | bot; val[top], val[bot] = 0.5, -0.5
V = solve_laplace(fixed, val)
c = np.sum(np.diff(V, axis=0)**2) + np.sum(np.diff(V, axis=1)**2) # C'/eps0 = 2W'/(eps0 dV^2)
return float(c), X, Y, V
print(" h C'/eps0 C'/(eps0 w/d)")
results = []
for h in [0.5, 0.25, 0.125]:
c, X, Y, V = plates(h)
results.append(c)
print(f" {h:5.3f} {c:6.3f} {c/4:6.3f}")
print(f"Richardson (error ~ h): {2*results[-1] - results[-2]:.3f} -> ratio {(2*results[-1] - results[-2])/4:.3f}")
c_big = plates(0.25, W=48.0, H=32.0)[0]
print(f"box doubled at h = 0.25: {c_big:.3f} (was {results[1]:.3f})")
w_d = 4.0
palmer = w_d * (1 + (1 + np.log(2*np.pi*w_d)) / (np.pi*w_d))
print(f"Palmer's approximate formula: {palmer:.3f} -> ratio {palmer/4:.3f}")
fig, ax = plt.subplots(figsize=(6, 3.4))
cs = ax.contour(X, Y, V, levels=np.linspace(-0.45, 0.45, 10), colors="tab:blue", linewidths=0.8)
ax.plot([-2, 2], [0.5, 0.5], "k", lw=3); ax.plot([-2, 2], [-0.5, -0.5], "k", lw=3)
ax.set_xlim(-6, 6); ax.set_ylim(-3, 3); ax.set_aspect("equal")
ax.set_title("Plates w = 4, d = 1 at +-0.5 V: equipotentials bulge past the edges")
plt.show() h C'/eps0 C'/(eps0 w/d)
0.500 5.927 1.482
0.250 5.696 1.424
0.125 5.591 1.398
Richardson (error ~ h): 5.486 -> ratio 1.372
box doubled at h = 0.25: 5.648 (was 5.696)
Palmer's approximate formula: 5.345 -> ratio 1.336
Here the error shrinks only about twofold per halving: the field is singular at the sharp plate edges, which spoils the convergence of the smooth trough problem. A Richardson extrapolation assuming first-order error gives ; doubling the box size lowers by another , about in the ratio (some field lines ended on the box, adding capacitance to it), so the isolated plates come out near , close to Palmer's closed-form estimate of for isolated thin strips: fringing adds about a third to the ideal capacitance when the plates are four gaps wide. To get three reliable digits you would refine near the edges only, the idea behind the adaptive meshes of FEM.
The mini project uses this solver on a coaxial cross-section and validates it against .
Guided lab: measure the fringing
Hand calculation. Two aluminium strips wide and long, held apart by foam blocks (): ideal ; with fringing about times that, , plus a little from the end effects of the finite length.
Simulation. The plates cell above.
What you would measure. Strips on foam (its is close to air) away from metal furniture, LCR meter at , leads nulled. Expect about to : well above the ideal , confirming that fringing is not a small correction for narrow plates. The gap tolerance ( gives about ) and nearby objects are the main uncertainties.
Hazards and safe setup. Meter signals only; deburr the strip edges.
Pitfalls
- Stopping criterion is not accuracy. A small change per sweep can hide a large remaining error; compare with a direct solve or check the residual.
- No convergence study, no result. Always refine (and the box) at least twice and report the trend.
- Field from a one-sided difference. Derivatives are less accurate than , and worst at sharp edges, exactly where breakdown starts.
- Too small a box. A grounded boundary too close adds capacitance and distorts the field.
Practice
- On a grid (one interior node) of a trough with the lid at , what is the interior value?
- A solver gives errors of , and on grids , , . What is the order of convergence, and what would the error be at ?
- Why does SOR with just below 2 converge faster than Jacobi on a fine grid?
Answer
- .
- Ratio 4 per halving: second order; about at .
- It over-relaxes, pushing each node past its neighbours' average in the direction the solution is moving, so long-wavelength errors (which Jacobi removes very slowly) decay in about sweeps instead of .
Test yourself
In the five-point stencil for Laplace's equation, each interior node equals…
- the sum of its four neighbours
- the average of its four neighbours
- the average of its eight neighbours
- the largest neighbour
Halving the grid spacing cuts the error in the trough problem by about…
- 2
- 4
- 8
- 16
Why does the parallel-plate fringing result converge more slowly than the trough?
- the box is too large
- the field is singular at the sharp plate edges
- Jacobi was used
- Laplace's equation does not hold between plates
For plates with , fringing raises the 2-D capacitance above by roughly…
- 1 %
- 10 %
- 35 %
- 300 %