TExcelTAD
Home › Electromagnetic Theory: Maxwell's Equations to Waves › Finite Differences for Laplace and Poisson

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 hh, write Vi,j=V(xi,yj)V_{i,j} = V(x_i, y_j). Taylor expansion of the second derivatives (Finite Differences) gives

∂2V∂x2+∂2V∂y2≈Vi+1,j+Vi−1,j+Vi,j+1+Vi,j−1−4Vi,jh2\frac{\partial^2 V}{\partial x^2} + \frac{\partial^2 V}{\partial y^2} \approx \frac{V_{i+1,j} + V_{i-1,j} + V_{i,j+1} + V_{i,j-1} - 4V_{i,j}}{h^2}

with an error proportional to h2h^2. Setting it equal to −ρv/ε-\rho_v/\varepsilon (Poisson) or zero (Laplace):

Vi,j=14(Vi+1,j+Vi−1,j+Vi,j+1+Vi,j−1)+h2ρv,ij4εV_{i,j} = \frac{1}{4}\left(V_{i+1,j} + V_{i-1,j} + V_{i,j+1} + V_{i,j-1}\right) + \frac{h^2\rho_{v,ij}}{4\varepsilon}

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.

i, ji+1, ji-1, ji, j+1i, j-1 h V(i,j) = average of the 4 neighbours fixed: V0fixed: 0 V interior nodes: unknowns

Boundary conditions. Electrode nodes are fixed (Dirichlet). A symmetry plane across which no field crosses is a Neumann condition ∂V/∂n=0\partial V/\partial n = 0, 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 ω\omega between 1 and 2 and, with ω\omega near its optimum 2/(1+sin⁡(π/N))2/(1 + \sin(\pi/N)), needs about NN sweeps instead of N2N^2 (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 VV. The field is the negative gradient (central differences); the charge on an electrode is ε∮E⋅n^ dl\varepsilon\oint \mathbf{E} \cdot \hat{\mathbf{n}}\,dl around it; the capacitance follows from C=Q/ΔVC = Q/\Delta V or from the energy, C=2W/ΔV2C = 2W/\Delta V^2 with W=12ε∑∣ΔV∣2W = \frac{1}{2}\varepsilon\sum \lvert\Delta V\rvert^2 over all grid edges (in 2-D, per metre of depth).

Worked example: one Jacobi sweep by hand

Given: a square trough on a 4×44 \times 4 grid (h=a/4h = a/4): lid nodes at 10 V10\ \text{V}, walls at 0 V0\ \text{V}, the nine interior nodes starting at 0 V0\ \text{V}.

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 14(10+0+0+0)=2.5 V\frac{1}{4}(10 + 0 + 0 + 0) = 2.5\ \text{V}; the other six stay at 0 V0\ \text{V}. By the four-wall symmetry argument of Separation of Variables, which holds for the discrete equations too, the converged centre value is exactly 2.5 V2.5\ \text{V} on any grid.

Check: information spreads one node per Jacobi sweep, so reaching the far wall of an N×NN \times N grid takes at least NN sweeps and converging takes of order N2N^2: 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 16×1616 \times 16 grid with Jacobi until the largest change per sweep is below 1 μV1\ \mu\text{V}, then solves the same problem directly on four grids and compares V(a/2,3a/4)V(a/2, 3a/4) with the separation-of-variables series.

python · try it yourself
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 = err
Jacobi, 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 1 μV1\ \mu\text{V}, yet the centre is still 0.1 mV0.1\ \text{mV} short of the exact 2.5 V2.5\ \text{V}: a small change per sweep is not a small error, because slow solvers creep. Second, halving hh cuts the error by a factor approaching 4: the h2h^2 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 w=4w = 4 and gap d=1d = 1 (any length unit: in 2-D the ratio C′/ε0C'/\varepsilon_0 is dimensionless) at ±0.5 V\pm 0.5\ \text{V} sit in the middle of a grounded box 24×1624 \times 16. The energy on the grid edges gives C′C'; the ideal value is ε0w/d=4ε0\varepsilon_0w/d = 4\varepsilon_0.

python · try it yourself
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 h2h^2 convergence of the smooth trough problem. A Richardson extrapolation assuming first-order error gives 1.371.37; doubling the box size lowers C′/ε0C'/\varepsilon_0 by another 0.050.05, about 0.0120.012 in the ratio (some field lines ended on the box, adding capacitance to it), so the isolated plates come out near 1.361.36, close to Palmer's closed-form estimate of 1.341.34 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 2πε/ln⁡(b/a)2\pi\varepsilon/\ln(b/a).

Guided lab: measure the fringing

Hand calculation. Two aluminium strips 40 mm40\ \text{mm} wide and 500 mm500\ \text{mm} long, held 10 mm10\ \text{mm} apart by foam blocks (w/d=4w/d = 4): ideal C=ε0⋅0.04⋅0.5/0.01=17.7 pFC = \varepsilon_0 \cdot 0.04 \cdot 0.5/0.01 = 17.7\ \text{pF}; with fringing about 1.341.34 times that, 23.7 pF23.7\ \text{pF}, plus a little from the end effects of the finite length.

Simulation. The plates cell above.

What you would measure. Strips on foam (its εr≈1.05\varepsilon_r \approx 1.05 is close to air) away from metal furniture, LCR meter at 100 kHz100\ \text{kHz}, leads nulled. Expect about 2424 to 26 pF26\ \text{pF}: well above the ideal 17.7 pF17.7\ \text{pF}, confirming that fringing is not a small correction for narrow plates. The gap tolerance (±0.5 mm\pm 0.5\ \text{mm} gives about ±4 %\pm 4\ \%) 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 hh (and the box) at least twice and report the trend.
  • Field from a one-sided difference. Derivatives are less accurate than VV, 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

  1. On a 3×33 \times 3 grid (one interior node) of a trough with the lid at 8 V8\ \text{V}, what is the interior value?
  2. A solver gives errors of 0.0400.040, 0.0100.010 and 0.00250.0025 on grids hh, h/2h/2, h/4h/4. What is the order of convergence, and what would the error be at h/8h/8?
  3. Why does SOR with ω\omega just below 2 converge faster than Jacobi on a fine grid?
Answer
  1. 14(8+0+0+0)=2 V\frac{1}{4}(8 + 0 + 0 + 0) = 2\ \text{V}.
  2. Ratio 4 per halving: second order; about 0.0006250.000625 at h/8h/8.
  3. 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 NN sweeps instead of N2N^2.

Test yourself

In the five-point stencil for Laplace's equation, each interior node equals…

  1. the sum of its four neighbours
  2. the average of its four neighbours
  3. the average of its eight neighbours
  4. the largest neighbour

Halving the grid spacing cuts the error in the trough problem by about…

  1. 2
  2. 4
  3. 8
  4. 16

Why does the parallel-plate fringing result converge more slowly than the trough?

  1. the box is too large
  2. the field is singular at the sharp plate edges
  3. Jacobi was used
  4. Laplace's equation does not hold between plates

For plates with w/d=4w/d = 4, fringing raises the 2-D capacitance above ε0w/d\varepsilon_0 w/d by roughly…

  1. 1 %
  2. 10 %
  3. 35 %
  4. 300 %