Conductors#
A conductor is a material where charges are mobile but constrained to the confines of the conductor. In an external electric field those charges rearrange themselves into their lowest energy configuration. This configuration (in the limit of enough electrons) has a remarkable property: the electric field inside the conductor is zero. The excess charge ends up on the surface, and the interior is perfectly screened. This is why you are safe inside a metal car during a lightning strike (a “Faraday cage”).
In this module we will start only with point charges and Coulomb’s law and see this behavior directly. We will:
Write a function that computes the electric field of a set of point charges, and test it on one and two charges.
Place charges on a sphere by hand and check that the field inside vanishes.
Let the charges move on their own — pushing each other around by the Coulomb force (gently damped so they don’t oscillate but converge to some configuration) and watch them discover the surface arrangement themselves: in a solid ball, on a sphere sitting in an external field, in a hemisphere, and in a cube.
In this project we will work in natural units: the Coulomb constant is \(K_E = 1\) and our conductor has radius \(R = 1\). The mobile charges are electrons, each carrying charge \(q = -1\) (in units of the elementary charge), since electrons are what actually move in a metal. Run the setup cell below before you start — it defines a few helper functions so you can focus on the physics.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import animation
from matplotlib.colors import LogNorm
from scipy.integrate import solve_ivp
from IPython.display import HTML
plt.rcParams.update({
"figure.dpi": 90, "savefig.dpi": 90, "font.size": 13,
"axes.grid": True, "grid.alpha": 0.3, "axes.titlesize": 14,
"legend.frameon": False,
})
# ---- physical constants (natural units) ----
K_E = 1.0 # Coulomb constant
R = 1.0 # radius of our conductor
Q_E = -1.0 # charge of each mobile carrier (an electron)
def GetPlot(nrows=1, ncols=1, w=6, h=5, d3=False):
"Return (fig, ax); set d3=True for a single 3D axis."
if d3:
fig = plt.figure(figsize=(w, h))
return fig, fig.add_subplot(111, projection='3d')
return plt.subplots(nrows, ncols, figsize=(w, h))
def GetSpherePoints(numPoints):
"Return ~numPoints points spread (nearly) evenly over the unit sphere."
pts, n, r = [], numPoints, 1.0
alpha = 4.0*np.pi*r*r/n
d = np.sqrt(alpha)
m_nu = int(np.round(np.pi/d))
d_nu = np.pi/m_nu
d_phi = alpha/d_nu
for m in range(m_nu):
nu = np.pi*(m+0.5)/m_nu
m_phi = int(np.round(2*np.pi*np.sin(nu)/d_phi))
for k in range(m_phi):
phi = 2*np.pi*k/m_phi
pts.append((r*np.sin(nu)*np.cos(phi),
r*np.sin(nu)*np.sin(phi),
r*np.cos(nu)))
return np.array(pts)
def GetLinePoints(the_start,the_end,num_points,dir="x"):
"""num_points evenly spaced points on a line through the origin along the x, y, or z axis.
Returns (field_locs, xs): field_locs is (num_points, 3), ready to pass to `field`;
xs is the 1D array of coordinates along the line (handy for the horizontal axis of a plot)."""
xs = np.linspace(the_start, the_end, num_points)
if dir=="x":
field_locs = np.stack([xs, np.zeros_like(xs), np.zeros_like(xs)], axis=1)
return field_locs,xs
elif dir=="y":
field_locs = np.stack([np.zeros_like(xs), xs,np.zeros_like(xs)], axis=1)
return field_locs,xs
elif dir=="z":
field_locs = np.stack([np.zeros_like(xs),np.zeros_like(xs),xs], axis=1)
return field_locs,xs
raise ValueError("dir must be 'x', 'y', or 'z'")
def GetSquarePoints(the_start,the_end,num_points=45,dir='xy'):
"""A num_points x num_points grid covering [the_start, the_end]^2 in the z = 0 plane (dir='xy')
or the y = 0 plane (dir='xz'). Returns (field_locs, X, Y): field_locs is the flattened
(num_points**2, 3) array of grid points, ready to pass to `field`; X, Y are the 2D grid
coordinates (as from np.meshgrid). For dir='xz', Y holds the z coordinate."""
g = np.linspace(the_start,the_end, num_points)
X, Y = np.meshgrid(g, g)
if dir=='xy':
field_locs_XY = np.stack([X.ravel(), Y.ravel(), np.zeros(X.size)], axis=1)
return field_locs_XY,X,Y
elif dir=='xz':
field_locs_XY = np.stack([X.ravel(), np.zeros(X.size),Y.ravel()], axis=1)
return field_locs_XY,X,Y
raise ValueError("dir must be 'xy' or 'xz'")
def GetBallPoints(N, R):
"""N random points uniform in the volume of a ball of radius R (r = R u^(1/3) so they are not
bunched at the center). Returns an (N, 3) array."""
u = np.random.uniform(0, 1, N)
costheta = np.random.uniform(-1, 1, N)
phi = np.random.uniform(0, 2*np.pi, N)
r = R*np.cbrt(u); theta = np.arccos(costheta)
return np.stack([r*np.sin(theta)*np.cos(phi),
r*np.sin(theta)*np.sin(phi),
r*np.cos(theta)], axis=1)
def GetHemispherePoints(N, R):
"""N random points uniform in the volume of the upper half-ball (z >= 0) of radius R.
Returns an (N, 3) array."""
u = np.random.uniform(0, 1, N)
costheta = np.random.uniform(0, 1, N) # upper half only
phi = np.random.uniform(0, 2*np.pi, N)
r = R*np.cbrt(u); theta = np.arccos(costheta)
return np.stack([r*np.sin(theta)*np.cos(phi),
r*np.sin(theta)*np.sin(phi),
r*np.cos(theta)], axis=1)
def PlotSlice(Ex,Ey,Emag,X,Y):
"""Draw a field map on a grid from GetSquarePoints: Emag as a log-scale color map (1e-2 to 1e2)
with field lines on top. Ex, Ey are the two IN-PLANE field components on the grid (for an
'xz' grid pass E_x and E_z). Returns (fig, ax)."""
fig, axes = GetPlot(1, 1, w=5, h=5)
cf = axes.contourf(X, Y, Emag, levels=np.logspace(-2, 2, 40),
norm=LogNorm(vmin=1e-2, vmax=1e2), cmap='inferno', extend='both')
axes.streamplot(X, Y, Ex, Ey, color='white', density=1.1, linewidth=0.5, arrowsize=0.6)
cb = fig.colorbar(cf, ax=axes, label='|E|')
ticks = [0.01, 0.1, 1, 10, 100]
cb.set_ticks(ticks, labels=[f'{t:g}' for t in ticks])
axes.set_aspect('equal')
return fig,axes
def animate_charges(sol, N, lim=1.4, title='', stride=1):
"Animate the 3D charge positions stored in a solve_ivp solution."
pos_t = sol.y[:3*N, ::stride].reshape(N, 3, -1)
fig = plt.figure(figsize=(5.5, 5.5))
ax = fig.add_subplot(111, projection='3d')
scat = ax.scatter(pos_t[:, 0, 0], pos_t[:, 1, 0], pos_t[:, 2, 0], s=12, c='tab:blue')
ax.set_xlim(-lim, lim); ax.set_ylim(-lim, lim); ax.set_zlim(-lim, lim)
ax.set_title(title)
def update(f):
scat._offsets3d = (pos_t[:, 0, f], pos_t[:, 1, f], pos_t[:, 2, f])
return (scat,)
ani = animation.FuncAnimation(fig, update, frames=pos_t.shape[2], interval=80,repeat=False)
plt.close(fig)
return HTML(ani.to_jshtml())
print("Setup complete.")
Setup complete.
Exercise 0. The Electric Field of Point Charges#
We will be interested in computing the electric field of a series of point charges. This can be done by adding up the Coulomb fields over a collection of point charges. We will start by writing this function which takes point charges and field locations and computes the field at those locations for those point charges. This will be used later for conductors.
a. Writing field#
The field of a single point charge \(q\) sitting at \(\mathbf r_i\), measured at a point \(\mathbf r\), is
and the field of many charges is just the sum of these (superposition). Write a function
def field(charges, points, q):
"E field at each of the M points (M,3) due to N charges (N,3), each of charge q; returns (M,3)."
...
return E
chargesis an(N, 3)array: the positions of the \(N\) charges (row \(i\) is \(\mathbf r_i\)).pointsis an(M, 3)array: the places where you want to measure the field.qis the charge on each of them. For our electrons that isQ_E = -1.It returns an
(M, 3)array: row \(k\) is the field vector \(\mathbf E\) atpoints[k].
A few pointers:
The small softening \(\epsilon = 10^{-4}\) in the equation above is added to \(\lvert\mathbf r - \mathbf r_i\rvert^2\) before raising it to the \(3/2\) power, so a field point that lands right on a charge doesn’t divide by zero. (Exercise 2 relies on this: it evaluates the field at each charge, where the charge’s own term becomes \(0/(10^{-4})^{3/2} = 0\).)
Start simple. The easiest fast thing to do is to start with no electric field
E = np.zeros_like(points)and write aforloop over the charges, compute \(\mathbf r - \mathbf r_i\),d=points - charges[i](shape(M, 3)) and add that charge’s field at all \(M\) field locations at once. When you divide the(M, 3)displacements by the(M,)cubed distances, NumPy needs the distances as a column: compute those distances withnp.sum(d**2, axis=1, keepdims=True)(shape(M, 1)) so the division applies to all three components.Optional: remove the loop.
points[:, None, :] - charges[None, :, :]has shape(M, N, 3); it holds every displacement vector \(\mathbf r - \mathbf r_i\) at once. Form the cubed distances (shape(M, N)), divide (index them asr3[:, :, None]so they broadcast against the last axis), and sum over the charge axis (axis=1).Start with
charges = np.asarray(charges, float)(and the same forpoints) so that you can pass in plain Python lists like[[0, 0, 0]].
Quick check. Put one electron at the origin and measure the field at \((1,0,0)\) and \((2,0,0)\) in a single call. The field should point inward (toward \(-x\), since an electron is negative), have magnitude \(1\) at \(x=1\) (you’ll see \(0.99985\) because of the softening), and fall off like \(1/r^2\), so the two magnitudes are in the ratio \(4:1\). For example:
E = field([[0, 0, 0]], [[1, 0, 0], [2, 0, 0]], Q_E)
print(E)
np.linalg.norm(E[0]) gives the magnitude of the first field vector.
Deliverables
Your
field.The printed field vectors at \(x = 1\) and \(x = 2\), and their magnitude ratio.
Your answer here.
b. Two charges#
Now place two electrons, at \((-0.5, 0, 0)\) and \((+0.5, 0, 0)\), and use your field to
measure the field at these points:
point |
where it is |
|---|---|
|
exactly halfway between the electrons |
|
on the perpendicular bisector, a distance 1 from the midpoint |
|
on the axis, outside the pair |
|
far away on the axis |
Put the electron positions in a (2, 3) array and the four measurement points in a (4, 3) array,
so that a single call to field gives all four field vectors:
electron_locs = np.array([[-0.5, 0, 0], [0.5, 0, 0]])
field_locs = np.array([[0, 0, 0], [0, 1, 0], [2, 0, 0], [10, 0, 0]])
Then print the field vector and its magnitude at each point (looping over
zip(field_locs, E) is a convenient way to do that). Keep the name electron_locs: parts (c)
and (d) reuse these two electrons.
Before you run it, predict the direction of the field at each point (remember: the field of an electron points toward it).
Deliverable
The printed \(\mathbf E\) and \(\lvert\mathbf E\rvert\) at the four points.
Questions.
Why is the field zero at the midpoint?
At \((0,1,0)\) the field points straight along \(-y\). Why does its \(x\)-component cancel?
Compare \(\lvert\mathbf E\rvert\) at \((10,0,0)\) to the field of a single charge \(-2\) at the origin, \(2/10^2 = 0.02\). Why do the two electrons look like one charge of \(-2\) from far away?
Your answer here.
c. The field along a line#
A handful of points is useful for checking, but to see the field we want many points. The
helper GetLinePoints(start, end, num_points) returns a (num_points, 3) array of points along the
\(x\)-axis (with \(y = z = 0\)), ready to hand to field, along with the 1D array of their \(x\) values for
plotting:
field_locs, xs = GetLinePoints(-3, 3, 400)
(Pass dir='y' or dir='z' for a line along that axis instead.) Compute the field of the two
electrons at these 400 points with one call to field, take the magnitude of the field using
Ex=E[:,0]; Ey=E[:,1]; Ez=E[:,2]
Emag=np.sqrt(Ex**2+Ey**2+Ez**2)
and plot \(\lvert\mathbf E\rvert\) against \(x\) on a log \(y\)-scale. The helper
GetPlot makes a figure and axis for you:
fig, ax = GetPlot(w=6, h=4)
ax.plot(xs, Emag, label='two electrons')
ax.set_yscale('log'); ax.set_ylim(1e-2, 1e3)
Label your axes (ax.set_xlabel, ax.set_ylabel).
Deliverable
\(\lvert\mathbf E\rvert\) vs. \(x\) for the two electrons.
Your answer here.
d. The field on a plane#
Finally, look at the field of the same two electrons on a whole plane. The helper GetSquarePoints(start, end) builds a
\(45 \times 45\) grid of points covering a square in the \(z = 0\) plane. It returns them as a flat
(2025, 3) array ready to hand to field, along with the grid coordinates X, Y (2D arrays, as
from np.meshgrid). Compute the field there, reshape each component back onto the grid, and draw
it with PlotSlice, which shows \(\lvert\mathbf E\rvert\) as a log-scale color map with field lines on top:
field_locs, X, Y = GetSquarePoints(-2, 2)
E = field(electron_locs, field_locs, Q_E)
Ex = E[:, 0].reshape(X.shape); Ey = E[:, 1].reshape(X.shape); Ez = E[:, 2].reshape(X.shape)
Emag = np.sqrt(Ex**2 + Ey**2 + Ez**2)
fig, ax = PlotSlice(Ex, Ey, Emag, X, Y)
For the \(y = 0\) plane, use GetSquarePoints(-2, 2, dir='xz'). The grid’s second coordinate is then
\(z\), so pass Ez (not Ey) as the second in-plane field component.
Deliverables
A field map of the two electrons in the \(z = 0\) plane.
The same map in the \(y = 0\) plane.
Question. Where is the field weakest, and how does that match part (b)? (A small white patch there means a grid point where \(\lvert\mathbf E\rvert\) is exactly \(0\), which a log color scale can’t show. Matplotlib also prints a harmless warning about it.) Why do the \(z = 0\) and \(y = 0\) pictures look the same?
Your answer here.
Exercise 1. Charges on a Sphere#
In Exercise 0 we computed the field of one or two charges. Now we use the same field to look
at many charges. We begin by spreading electrons uniformly over a sphere by hand, then sum up
their Coulomb fields and look at the result. What we expect to see is that the field inside the
sphere is zero, just as it is inside a conductor.
a. Placing charges on a sphere#
The helper GetSpherePoints(n) returns an array of roughly n points (shape (n, 3), give or
take a few) spread evenly over the unit sphere. Use it to place about 300 electrons on the sphere
\(r = R\), and make a 3D scatter plot so you can see them. GetPlot(d3=True) gives you a 3D axis:
charges = GetSpherePoints(300)
fig, ax = GetPlot(d3=True)
ax.scatter(charges[:, 0], charges[:, 1], charges[:, 2])
Since the helper only returns approximately n points, print len(charges) to see how many you
actually got.
Deliverable
A 3D scatter plot of your charges on the sphere.
Your answer here.
b. The interior is screened#
Now measure the field these charges produce, using the field you wrote in Exercise 0 and the
same tools as Exercise 0d. Build a grid of points on the \(z = 0\) plane with GetSquarePoints,
evaluate the field of your electrons there with one call to field, reshape the components back
onto the grid, and draw the result with PlotSlice:
electron_locs = GetSpherePoints(300)
field_locs, X, Y = GetSquarePoints(-2, 2)
E = field(electron_locs, field_locs, Q_E)
## now plot it.
Then make a line cut, as in Exercise 0c: use GetLinePoints(-2, 2, 400) to get points along the
\(x\)-axis from outside the sphere, through it, and out the other side, and plot \(\lvert\mathbf E\rvert\) against
\(x\) on a log \(y\)-scale. (GetSpherePoints happens to put one charge exactly on the \(+x\) axis, so
expect a sharp spike at \(x = 1\) that has no partner at \(x = -1\). It is just that one nearby charge.)
Deliverables
A 2D field map (\(\lvert\mathbf E\rvert\) with field lines) on the \(z = 0\) slice.
\(\lvert\mathbf E\rvert\) vs. \(x\) along the \(x\)-axis (log \(y\)-scale).
Question. What is the field inside the sphere? Why does it (nearly) vanish there even though every individual charge produces a \(1/r^2\) field?
Your answer here.
Exercise 2. Letting the Charges Rearrange Themselves#
In the previous exercise, we placed the charges by hand. In a real conductor the electrons find their optimal location themselves. Let’s simulate that. To do that, we will let them charges (\(m=1\)) move under their dynamics but remove the kinetic energy so they don’t keep moving. The relevant equations of motion written as two first-order equations for its position \(\mathbf r_i\) and velocity \(\mathbf v_i\):
where \(\mathbf E(\mathbf r)\) is the electric field of all the electrons,
which is exactly what your field from Exercise 0 computes: field(pos, pos, Q_E) gives \(\mathbf E\) at every charge’s own position.
The first term is the Coulomb force \(\mathbf F = q\mathbf E\) on electron \(i\) (with \(m = 1\), force and acceleration are the same). A charge’s own term in the sum is zero, since \(\mathbf r_i - \mathbf r_i = 0\), so it feels no force from itself. Because \(Q_E \cdot Q_E = +1\), electrons repel. The small softening \(\epsilon = 10^{-4}\) (the one built into field) keeps nearby pairs from blowing up. The second term is a drag force (coefficient \(\gamma\)) that bleeds off kinetic energy so the system relaxes into its lowest-energy configuration instead of oscillating forever. The third, \(\mathbf f_\mathrm{wall}\), is a stiff restoring force (stiffness \(k\)) that keeps the charges inside the conductor. Its form depends on the shape of the conductor, so we give it in each part below. Because the wall is a stiff spring rather than a perfectly hard wall, charges pressed against it come to rest slightly outside it, where the spring balances their mutual repulsion (a few percent of \(R\) for the sphere, a bit more for the cube). That is expected.
Common parameters. These are the same in every part:
quantity |
symbol |
in code |
value |
|---|---|---|---|
Coulomb constant |
\(K_E\) |
|
\(1\) |
conductor radius |
\(R\) |
|
\(1\) |
electron charge |
\(Q_E\) |
|
\(-1\) |
mass |
\(m\) |
\(1\) |
|
softening (inside |
\(\epsilon\) |
\(10^{-4}\) |
|
drag coefficient |
\(\gamma\) |
|
\(2.0\) |
wall stiffness |
\(k\) |
|
\(3000\) |
initial velocity |
\(\mathbf v_i(0)\) |
\(0\) |
|
saved frames |
|
60, evenly spaced from \(t=0\) to \(T_\mathrm{max}\) |
|
solver tolerance |
|
\(10^{-3}\) |
Integrating with solve_ivp. solve_ivp integrates a system \(\dot{\mathbf y} = f(t, \mathbf y)\)
where \(\mathbf y\) is a single flat array. So we pack the positions and velocities of all \(N\) charges
into one state vector,
and write a right-hand-side function rhs(t, state) that returns \([\dot{\mathbf r},\ \dot{\mathbf v}]\)
from Eq. (1), packed the same way. The call is
t_eval = np.linspace(0, T_MAX, 60) # the 60 times at which to save the state
sol = solve_ivp(rhs, (0, T_MAX), state0, t_eval=t_eval, method='RK45', atol=1e-3)
where state0 is the initial state. We use atol=1e-3 rather than the default because positions
and velocities are of order 1, so this is plenty accurate and much faster. The result holds the
saved times in sol.t (length 60) and the saved states in sol.y, an array of shape (6N, 60):
column k is the full state at time sol.t[k]. So, for example, the positions at the last
saved time are sol.y[:3*N, -1].reshape(N, 3).
The number of charges \(N\), the run time \(T_\mathrm{max}\) (T_MAX), and anything else specific to a
geometry are given in each part. The same template works for every geometry below — only the
wall force and the initial positions change, plus (in part b) an external charge added to
\(\mathbf E\).
a. Charges in a solid metal ball#
Step 1 — Set up and run the dynamics.
Write the right-hand side rhs(t, state) of Eq. (1) for charges inside a ball of radius \(R\). Here
is the skeleton: the first two lines unpack the state, and the last line packs the answer back up.
def rhs(t, state):
pos = state[:3*N].reshape(N, 3) # (N, 3): row i is r_i
vel = state[3*N:].reshape(N, 3) # (N, 3): row i is v_i
acc = ... # (N, 3): row i is dv_i/dt from Eq. (1)
return np.concatenate([vel.ravel(), acc.ravel()])
Build acc one term of Eq. (1) at a time:
Coulomb force.
field(pos, pos, Q_E)is the field of all the electrons, evaluated at every electron. Multiply by the charge \(Q_E\) to get the force.Drag. Subtract
DRAG*vel.Wall. A one-sided wall that pushes a charge back only when it strays outside (\(r > R\)). Writing \(r_i = \lvert\mathbf r_i\rvert\) and \(\hat{\mathbf r}_i = \mathbf r_i / r_i\),
\[ \mathbf f_\mathrm{wall}(\mathbf r_i) = \begin{cases} -k\,(r_i - R)\,\hat{\mathbf r}_i & r_i > R \cr 0 & r_i \le R. \end{cases} \]This is the first time we need an “if” applied to every charge at once, which
np.wheredoes:r = np.linalg.norm(pos, axis=1, keepdims=True) # (N, 1): distance of each charge acc += np.where(r > R, -K_WALL*(r - R)*(pos/r), 0.0) # wall force where r > R, else 0
keepdims=Truekeepsras a column, sopos/rdivides each row by that charge’s distance (giving \(\hat{\mathbf r}_i\)).np.where(condition, a, b)takesawhere the condition is true andbwhere it is false.
Initial conditions. Start the charges at random positions throughout the volume of the ball,
at rest. GetBallPoints(N, R) returns such positions as an (N, 3) array; flatten it with .ravel()
to build the initial state:
init_pos = GetBallPoints(N, R)
state0 = np.concatenate([init_pos.ravel(), np.zeros(3*N)])
Then integrate with solve_ivp as described above, and print sol.success to check that the
integration finished.
Parameters. \(N = 150\) charges, \(T_\mathrm{max} = 8\) (plus DRAG and K_WALL from the common
parameters table).
Your answer here.
Step 2 — Did the charges move to the surface?
Pull the initial and final positions out of the solution (column 0 and the last column of
sol.y):
start_pos = sol.y[:3*N, 0].reshape(N, 3)
final_pos = sol.y[:3*N, -1].reshape(N, 3)
Make a 3D scatter plot of the initial and final positions side by side. add_subplot(121, ...) is
the left panel of a 1-row, 2-column figure, and add_subplot(122, ...) the right:
fig = plt.figure(figsize=(11, 5))
ax1 = fig.add_subplot(121, projection='3d')
ax1.scatter(start_pos[:, 0], start_pos[:, 1], start_pos[:, 2], s=10, c='tab:gray')
ax2 = fig.add_subplot(122, projection='3d')
ax2.scatter(final_pos[:, 0], final_pos[:, 1], final_pos[:, 2], s=10, c='tab:blue')
plt.show()
Then compute each charge’s distance from the center, \(r = \lvert\mathbf r\rvert\), with
np.linalg.norm(start_pos, axis=1) (and the same for final_pos), and histogram the initial and
final radii on the same axes. Use the same bins for both, the_bins = list(np.linspace(0, 2, 20)),
so they can be compared: call ax.hist(r_start, bins=the_bins) and then ax.hist(r_final, bins=the_bins).
Deliverables
3D scatter: initial (interior) vs. final positions.
Histogram of initial and final radii.
Question. Where do the charges end up, and why?
Your answer here.
Step 3 — Watch it happen. Animate the charges migrating from the interior to the surface.
The helper animate_charges turns the saved frames of a solve_ivp solution into an animation:
animate_charges(sol, N, lim=1.3, title='Charges migrating to the surface')
lim sets the axis limits (from -lim to +lim in each direction). Make it the last line of the cell so the
animation displays; it takes a few seconds to build.
Deliverable
The animation.
Your answer here.
Step 4 — Did the system actually relax?
The drag removes energy, so the total energy should fall as the electrons move into a screening
configuration, and then flatten out once they have settled. Check this by computing the kinetic
and potential energy at every saved frame. Loop over the frames, pulling out the positions and
velocities of frame k from column k of sol.y:
num_frames = len(sol.t)
ke = np.zeros(num_frames)
pe = np.zeros(num_frames)
for k in range(num_frames):
pos = sol.y[:3*N, k].reshape(N, 3) # positions at frame k (first 3N entries of the state)
vel = sol.y[3*N:, k].reshape(N, 3) # velocities at frame k (last 3N entries)
# ke[k] = ...
# pe[k] = ...
Kinetic energy. \(K = \sum_i \tfrac12 m \lvert\mathbf v_i\rvert^2\), with \(m = 1\).
Potential energy. The Coulomb energy is a sum over pairs, \(U = \sum_{i<j} K_E\, q_i q_j / \lvert\mathbf r_i - \mathbf r_j\rvert\). Rather than looping over pairs, you can get it from the forces you already know how to compute. For Coulomb interactions,
\[ U = \sum_i \mathbf r_i \cdot \mathbf F_i, \qquad \mathbf F_i = Q_E\,\mathbf E(\mathbf r_i). \]In code, compute the forces with
fieldas in yourrhs, thennp.sum(pos*F)adds up all the dot products \(\mathbf r_i\cdot\mathbf F_i\) at once. (Becausefieldis softened, this agrees with the exact pair sum to about 0.1%.)
Plot two graphs side by side, using fig, axes = GetPlot(1, 2, w=11, h=4) (then axes[0] is the
left panel and axes[1] the right):
left: the potential energy and the total energy (kinetic + potential) vs. time (
sol.t);right: the kinetic energy vs. time on a log \(y\)-scale, since it falls by orders of magnitude.
A few things you will notice. The kinetic energy at \(t = 0\) is exactly zero (the charges start at rest), so the log plot can’t show that first point. Late in the run the kinetic energy levels off around \(0.1\) instead of falling forever; that is numerical jitter from the solver tolerance and doesn’t matter. And our “total” ignores the small energy stored in the springy wall (about 1% of the total), which is why it isn’t exactly the conserved quantity.
Deliverables
The two energy-vs-time graphs.
The total energy at the start and at the end of the run.
Question. How can you tell from these plots that the charges have finished relaxing?
Your answer here.
Step 5 — Is the inside screened?
Repeat the screening checks from Exercise 1b on both the initial and the final configuration,
using start_pos and final_pos as the charge positions:
a field map on the \(z = 0\) slice (
GetSquarePoints(-2, 2)andPlotSlice) for each, and\(\lvert\mathbf E\rvert\) along the \(x\)-axis (
GetLinePoints(-2, 2, 400)) for both, drawn as two curves on the same log-scale plot.
Deliverables
Field slices for the initial and final configurations.
\(\lvert\mathbf E\rvert\) vs. \(x\) for the initial and final configurations.
Question. How does the field inside the ball compare before and after the charges relax?
Your answer here.
b. A conductor in an external field#
So far the electrons have relaxed without any external charge or field. Now we bring up an external point charge \(Q_\mathrm{ext}\) off to one side and watch the surface electrons rearrange to cancel its field inside the conductor. Pin the electrons to the spherical surface (a two-sided wall holds them at \(r = R\)). As the electrons rearrange, they pile up so as to cancel the external field everywhere inside the sphere — induced screening.
We use a positive external charge so the electrons are attracted to it: they crowd onto the near side (making it negative) and leave the far side electron-poor (relatively positive).
Step 1 — Set up and run. The field each electron feels now has two pieces: the field of the other electrons, as before, plus the field of the fixed external charge \(Q_\mathrm{ext}\) at \(\mathbf r_\mathrm{ext}\),
That is just one more call to your field, with a single “charge” at POS_EXT carrying charge
Q_EXT: field([POS_EXT], pos, Q_EXT). Add it to the electrons’ field and multiply the total by
\(Q_E\) to get the force, exactly as in part (a). The sign takes care of itself: \(Q_E < 0\) and
\(Q_\mathrm{ext} > 0\), so the force pulls the electrons toward the external charge.
Instead of part (a)’s one-sided wall, use a two-sided spring that holds the charges on the shell \(r = R\) whether they stray outside or inside:
In code this is part (a)’s wall without the np.where. Write a new rhs with the Coulomb force
(electrons plus external charge), drag, and this wall.
Start the charges spread evenly on the sphere, at rest. Because GetSpherePoints returns only
approximately the number you ask for, reset N to the number you actually got before building the
state:
charges = GetSpherePoints(N)
N = len(charges)
state0 = np.concatenate([charges.ravel(), np.zeros(3*N)])
Parameters. \(N \approx 500\) charges (ask GetSpherePoints for 500),
\(Q_\mathrm{ext} = 20\) (Q_EXT) at \(\mathbf r_\mathrm{ext} = (1.6, 0, 0)\)
(POS_EXT = np.array([1.6, 0.0, 0.0])), \(T_\mathrm{max} = 6\).
Your answer here.
Step 2 — Look at the induced distribution and the field.
Pull out the final positions as in part (a) (final_pos = sol.y[:3*N, -1].reshape(N, 3)) and plot
them in three dimensions. Color each charge by its \(x\)-coordinate, add a color bar, and mark the
external charge with a star. The bunching is subtle (the near side is only about 30% denser), so
look for more closely spaced dots near the star:
fig = plt.figure(figsize=(6, 5.5))
ax = fig.add_subplot(111, projection='3d')
p = ax.scatter(final_pos[:, 0], final_pos[:, 1], final_pos[:, 2],
c=final_pos[:, 0], cmap='coolwarm', s=14)
ax.scatter(*POS_EXT, c='k', marker='*', s=200) # *POS_EXT unpacks to x, y, z
fig.colorbar(p, ax=ax, label='x', shrink=0.6)
Next, make a field map on the \(z = 0\) slice that includes the external charge: the total field is
field(final_pos, field_locs, Q_E) + field([POS_EXT], field_locs, Q_EXT). Use a slightly larger
square, GetSquarePoints(-2.5, 2.5), so the external charge at \(x = 1.6\) is well inside the picture.
Finally, plot \(\lvert\mathbf E\rvert\) along the \(x\)-axis inside the sphere, at
field_locs, xs = GetLinePoints(-1., 1., 400), for two cases on the same axes: the total field
(electrons plus external charge) and the bare field of the external charge alone. Use a linear
\(y\)-scale here. Inside the sphere, the conductor should strongly suppress the field. Ignore the
last \(\approx 0.1\) at each end of the line: there you are within one charge spacing of individual
surface charges, so the total field shoots up.
Deliverables
3D scatter of the induced distribution (with the external charge marked).
Field-map slice including the external charge.
\(\lvert\mathbf E\rvert\) inside the sphere, with vs. without the conductor.
Question. Where do the electrons bunch up, and how well does the conductor cancel the external field inside the sphere?
Your answer here.
Step 3 — Watch it happen. Use animate_charges as in part (a) to animate the charges sliding
around to their induced positions.
Deliverable
The animation.
Your answer here.
c. A hemispherical conductor#
The surface arrangement isn’t special to spheres. Take a solid hemisphere (the top half of the ball, \(z \ge 0\)) and let charges relax inside it. Now there are two walls: the curved cap \(r = R\) and the flat base \(z = 0\). The charges should coat the curved surface and the flat disk, again leaving the interior screened.
Write rhs with both constraints: part (a)’s one-sided spherical wall for \(r > R\), plus a floor
that pushes up whenever \(z < 0\),
The curved cap is exactly part (a)’s wall. The floor acts only on the \(z\)-component of the
acceleration, the third column of acc:
z = pos[:, 2]
acc[:, 2] += np.where(z < 0, -K_WALL*z, 0.0)
Start the charges at random positions inside the hemisphere, at rest. GetHemispherePoints(N, R)
returns them as an (N, 3) array (just like GetBallPoints), so use .ravel() when you build
state0. Then run it and check the result:
a 3D scatter of the final positions;
a field map on the \(x\)–\(z\) slice (the plane \(y = 0\), which cuts through the flat base). As in Exercise 0d, use
GetSquarePoints(-2, 2, dir='xz')and passEz(notEy) toPlotSliceas the second in-plane component;an animation with
animate_charges.
Parameters. \(N = 150\) charges, \(T_\mathrm{max} = 8\).
Deliverables
3D scatter of the relaxed charges.
Field map on the \(x\)–\(z\) slice.
The animation.
Question. Where does the charge sit, and where does it pile up most? Is the interior screened? (The contrast is weaker than for the ball, because no point inside a hemisphere is very far from the surface charges.)
Your answer here.
d. A cubic conductor#
We will now do a conductor with corners - a cube. Confine the charges to a cube of side \(L\) (walls at \(x, y, z = \pm L/2\)) and let them relax. Conductors with sharp features concentrate charge there — you should find the charges crowding onto the faces and especially piling up at the edges and corners, where the field just outside is largest.
Write rhs with a one-sided wall on each of the six faces. Each face pushes back only along its
own axis, so apply this to each component \(x_i\), \(y_i\), \(z_i\) separately (shown for \(x\)):
Because each component is treated the same way, you don’t need to split pos into columns:
np.where works element by element on the whole (N, 3) array. For example, the three faces on the
positive side are
acc += np.where(pos > SIDE/2, -K_WALL*(pos - SIDE/2), 0.0)
and the negative side is the same idea.
Start the charges at random positions inside the cube, at rest:
np.random.uniform(-SIDE/2, SIDE/2, (N, 3)) gives an (N, 3) array of uniform random points.
With 800 charges each run takes up to a minute or so. Then:
show the final positions in a 3D scatter;
check that the interior is screened with a field map on the \(z = 0\) slice (
GetSquarePoints(-2, 2));animate the relaxation with
animate_charges.
Parameters. \(N = 800\) charges, side \(L = 2\) (SIDE), \(T_\mathrm{max} = 4\).
Deliverables
3D scatter of the relaxed charges.
Field map on the \(z = 0\) slice.
Histogram of distances from the center.
The animation.
Question. Where is the surface charge density largest, and why?
Your answer here.
Acknowledgements:
Bryan Clark (original)
© Copyright 2026