Electric potential and electric field describe the same electrostatic physics in two forms. Potential is a scalar that describes energy per unit charge. The field is a vector that describes force per unit positive charge. The field points in the direction in which potential decreases most rapidly.
This relationship is both a calculation method and an independent check: a potential derived from charges should produce the same field as direct Coulomb superposition.
The potential difference between points \(A\) and \(B\) is
\[V_B-V_A =-\int_A^B\mathbf E\cdot d\boldsymbol{\ell}\]For a very short displacement \(d\boldsymbol{\ell}\),
\[dV=-\mathbf E\cdot d\boldsymbol{\ell}\]The gradient is the vector whose dot product with a displacement gives the local scalar change:
\[dV=\boldsymbol{\nabla}V \cdot d\boldsymbol{\ell}\]Comparing the two expressions for every possible displacement gives
\[\mathbf E=-\boldsymbol{\nabla}V\]The minus sign is not a convention that can be dropped. A positive test charge accelerates in the field direction while its electric potential energy decreases.
In Cartesian coordinates,
\[\mathbf E =-\frac{\partial V}{\partial x}\hat{\mathbf x} -\frac{\partial V}{\partial y}\hat{\mathbf y} -\frac{\partial V}{\partial z}\hat{\mathbf z}\]Thus \(E_x=-\partial V/\partial x\), with analogous relations in the other directions. Dividing volts by meters gives volts per meter, which is equivalent to newtons per coulomb.
For the linear potential
\[V(x,y)=3x-2y\]when position is measured in meters and coefficients carry volts per meter, the field is
\[\mathbf E =-3\hat{\mathbf x} +2\hat{\mathbf y}\ \mathrm{V/m}\]This fixture catches a missing minus sign or swapped coordinate before a more complicated source is attempted.
If a uniform field points in the positive horizontal direction, then
\[V(x)=V(x_0)-E_x(x-x_0)\]Potential decreases linearly as position increases along the field. Between two points separated by \(\Delta x\),
\[\Delta V=-E_x\Delta x\]This simple result applies only when the field component is constant over the interval. For a varying field, use the line integral.
With zero potential at infinity, a point charge has
\[V(r)=\frac{1}{4\pi\epsilon_0}\frac{q}{r}\]Spherical symmetry makes the gradient radial:
\[\boldsymbol{\nabla}V =\frac{dV}{dr}\hat{\mathbf r} =-\frac{1}{4\pi\epsilon_0} \frac{q}{r^2}\hat{\mathbf r}\]Negating the gradient gives
\[\mathbf E =\frac{1}{4\pi\epsilon_0} \frac{q}{r^2}\hat{\mathbf r}\]For positive charge, the potential decreases outward but remains positive, and the field points outward. For negative charge, both signs reverse appropriately.
Along an equipotential surface, \(dV=0\). Therefore
\[\mathbf E\cdot d\boldsymbol{\ell}=0\]The electric field is perpendicular to a regular equipotential surface. Moving a charge along that surface requires no electrostatic work. This does not mean no external work is ever needed; gravity, friction, or constraints may still matter.
Closely spaced contours drawn at equal potential increments indicate a large potential gradient and therefore a strong field. Unequal or automatic contour intervals must be labeled before spacing is interpreted physically.
Gauss's law and the field–potential relationship combine:
\[\boldsymbol{\nabla}\cdot\mathbf E =\frac{\rho}{\epsilon_0}, \qquad \mathbf E=-\boldsymbol{\nabla}V\]Substitution yields Poisson's equation:
\[\nabla^2V=-\frac{\rho}{\epsilon_0}\]In a charge-free region where \(\rho=0\), potential satisfies Laplace's equation:
\[\nabla^2V=0\]Charge outside the region still influences boundary values, so zero local charge does not mean constant potential or zero field. Boundary conditions are needed to select a unique solution up to any remaining reference freedom.
For uniform grid spacing \(h\), a central approximation to the horizontal derivative is
\[\frac{\partial V}{\partial x}(x,y) \approx \frac{V(x+h,y)-V(x-h,y)}{2h}\]In two dimensions, the numerical field becomes
\[\mathbf E_h(x,y) =\left( -\frac{V(x+h,y)-V(x-h,y)}{2h}, -\frac{V(x,y+h)-V(x,y-h)}{2h} \right)\]For a smooth potential, the truncation error is generally proportional to the square of the step size. Halving \(h\) should reduce that regime's error by roughly a factor of four. At extremely small steps, subtraction of nearly equal floating-point values amplifies roundoff, so error eventually stops improving.
A centered stencil needs points on both sides. Near a domain boundary or source mask, either reject the derivative, use an explicitly lower-order one-sided stencil, add ghost values from a boundary condition, or use a suitable nonuniform formula. Quietly reading outside the domain is not acceptable.
On a nonuniform grid, the centered formula above is generally wrong because the two neighbor distances differ. Store physical coordinates and derive weights for the actual spacing. Array indices are not distances.
Near a point-charge singularity, potential changes too rapidly for a coarse stencil and is undefined at the source. A stencil that crosses the source does not approximate a smooth local derivative.
The numerical calculation should expose every sampled potential used in each component.
import numpy as np
def potential(point):
return 8.9875517923 / np.linalg.norm(point)
probe = np.array([0.8, 0.6])
step = 1e-4
field = []
for direction in np.eye(2):
derivative = (
potential(probe + step * direction) - potential(probe - step * direction)
) / (2 * step)
field.append(-derivative)
expected = 8.9875517923 * probe / np.linalg.norm(probe) ** 3
assert np.allclose(field, expected)
print("Field (V/m):", field)
Keeping the expression vertical prevents source coordinates, probe coordinates, and display coordinates from being compressed into one hard-to-audit line.
Adding a constant \(C\) gives
\[\boldsymbol{\nabla}(V+C) =\boldsymbol{\nabla}V\]A numerical derivative should therefore be unchanged except for roundoff. This is a simple regression test for accidentally differentiating a color scale, normalized display value, or mismatched reference.
Compare the numerical negative gradient with an independently computed Coulomb field at several fixed physical probes. Include a linear fixture, an ordinary off-axis point, a symmetry point, and a point-charge case safely away from the source.
Repeat with several step sizes while holding each probe fixed. Report component residuals and vector magnitude residuals. Use absolute error when the reference component is zero; relative error against zero is undefined.
For time-dependent electromagnetic fields, the general potential representation includes a vector potential:
\[\mathbf E =-\boldsymbol{\nabla}V -\frac{\partial\mathbf A}{\partial t}\]The vector potential \(\mathbf A\) contributes when fields change with time. The electrostatic equation is recovered when that time derivative vanishes in the chosen description.
Within electrostatics, the negative gradient relation is exact. In computation, its usefulness depends on coordinate units, source and boundary treatment, stencil choice, and convergence evidence. Those details turn a formal derivative into a trustworthy field calculation.
Keep potential reference choices separate from measured potential differences. Adding one constant to every sampled potential changes neither voltage differences nor the electric field, but mixing two reference conventions can create an apparent offset. A useful data record therefore stores the reference location, its assigned potential, and the coordinate system beside each potential grid.
Compare a centred finite difference of potential with the radial electric field. The question for this calculation is precise: how does potential change when we change radial distance, while keeping the other choices fixed? The earlier sections explain the physical relationship. Here we turn one part of that relationship into a calculation that you can run, inspect, and change in Google Colab.
Finite-difference samples must avoid the singular source and use a physically meaningful spacing. Keep that sentence beside the results. A formula can return a number outside its useful range, and a plotting library will usually draw that number without asking whether the physical assumptions still hold. The selected interval is from 0.5 to 3 m. It gives us a specific domain to discuss instead of leaving the graph's range to a software default.
Use the notebook link above the lesson, run the setup cell, and then run the cells in order. The code below is also included there. NumPy handles the arrays of numerical values, SymPy keeps the equation symbolic, and Matplotlib draws the results. If these libraries or notebook cells are unfamiliar, start with Your first physics notebook.
In this small example, q stands for radial distance, expressed in m. The output is
potential, expressed in V. The equation below uses the numerical values in those
units. Any fixed coefficients therefore carry the units needed to make the relation
consistent. A value supplied in another unit must be converted before it enters this
expression.
This is a function of one changing input. It is not a statement that the physical system has only one variable. We deliberately hold the other inputs fixed so that one cause of variation is visible. Changing several inputs at once would make it harder to tell which change produced the output difference. Write down the held-fixed choices before trying a different experiment.
At 1 m, the expression gives 8.98755 V. This is our reference calculation. It is a prediction of the stated example, not a new measurement. Its displayed digits help us compare implementations. They should not be read as a claim that physical inputs are known to six significant figures.
import numpy as np
import sympy as sp
import matplotlib.pyplot as plt
q = sp.Symbol("q", real=True)
expression = sp.sympify("8.9875517923/q", locals={"q": q})
reference_input = 1.0
reference_output = float(expression.subs(q, reference_input))
print("Input:", reference_input, "m")
print("Predicted potential:", reference_output, "V")
sp.Symbol declares a mathematical symbol. It does not assign a numerical measurement
to that symbol. subs then replaces the symbol with our chosen input, and float
converts the resulting symbolic number into a standard Python numerical value.
Keeping these steps separate lets us inspect the equation before numerical substitution.
It also prevents a later plot from becoming the only surviving record of the model.
Before drawing hundreds of points, calculate three. The lower endpoint gives 17.9751 V. The midpoint, at 1.75 m, gives 5.13574 V. The upper endpoint gives 2.99585 V. Read these together with the assumptions: they describe different choices of radial distance within the same example, with the other inputs held fixed.
These three values are a useful first check, but they do not establish the shape between them. Two endpoints can be equal even when the curve bends or oscillates in between. Likewise, a large change between endpoints does not tell us whether the relationship is linear. We need the equation and intermediate samples to answer those questions.
evaluate = sp.lambdify(q, expression, modules="numpy")
inputs = np.array([0.5, 1.75, 3.0])
outputs = np.asarray(evaluate(inputs), dtype=float)
outputs = np.broadcast_to(outputs, inputs.shape)
for input_value, output_value in zip(inputs, outputs):
print(f"{input_value:.6g} m -> {output_value:.6g} V")
assert np.all(np.isfinite(outputs))
lambdify turns the symbolic expression into a numerical function. We explicitly select
NumPy as its numerical backend so it can accept an array. The same expression now has
two useful forms: one for algebra and one for calculating many cases. The assertion
checks that the chosen inputs produce finite outputs. It would catch an infinity or an
undefined numerical result, but a finite value can still be physically inappropriate.
The horizontal axis shows radial distance; the vertical axis shows potential. Every plotted point is a prediction of the same expression. We mark the reference case separately so that a reader can connect the earlier printed value to its place on the curve. The axis labels include units because a shape without a scale cannot tell us the size of a physical effect.
input_grid = np.linspace(0.5, 3.0, 301)
output_grid = np.asarray(evaluate(input_grid), dtype=float)
output_grid = np.broadcast_to(output_grid, input_grid.shape)
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(input_grid, output_grid, label="Stated model")
ax.scatter([reference_input], [reference_output], label="Reference case", zorder=3)
ax.set_xlabel("Radial distance (m)")
ax.set_ylabel("Potential (V)")
ax.legend()
ax.grid(alpha=0.25)
fig.tight_layout()
plt.show()
Look for a sign change, a turning point, or a region where the curve becomes steep. Connect each feature to the expression rather than to the colour of the line. If the curve has a minimum or maximum, changing the input in opposite directions may have similar effects on the output near that point. If it is nearly straight over a short interval, a local linear approximation may be useful even when the complete expression is nonlinear.
Increasing the number of samples makes the line smoother and may reveal features that a coarse grid missed. It does not improve the physical inputs or enlarge the model's validity range. For quantities that can take only discrete values, use the line as a guide to the relationship and interpret only the allowed input values. A plotting function does not enforce such restrictions for you.
A derivative asks a more specific question than the whole graph: how quickly does potential change near the reference input? Its units are the output unit divided by the input unit. For this calculation, the derivative at 1 m is -8.98755 in those ratio units. Locally, the output decreases as the input increases. This statement is local; the sign or size of the slope can be different elsewhere on the curve.
\[f'(q) = - \frac{8.9875517923}{q^{2}}\]For a small input change, multiply the derivative by that change to estimate the output change. Then compare that estimate with a fresh evaluation of the full expression. The distinction between these two calculations matters: the derivative gives a tangent approximation, while substitution evaluates the chosen expression at the new point.
slope_expression = sp.diff(expression, q)
slope_at_reference = float(slope_expression.subs(q, reference_input))
changed_input = 1.0125
linear_prediction = reference_output + slope_at_reference * (
changed_input - reference_input
)
full_prediction = float(evaluate(changed_input))
print("Symbolic derivative:", slope_expression)
print("Tangent prediction:", linear_prediction, "V")
print("Full expression:", full_prediction, "V")
print("Approximation difference:", full_prediction - linear_prediction, "V")
Here the changed input is 1.0125 m. The tangent estimate is 8.87521 V, while the full expression gives 8.87659 V. If the two values are close, it means the chosen input change is small enough for this local approximation at this point. It does not mean the entire model is linear. If the slope is zero, a quadratic or higher-order term may supply the leading change instead.
This is also the beginning of uncertainty propagation. If the input has a small stated standard uncertainty, the magnitude of the slope times that uncertainty estimates one contribution to output uncertainty. Do not automatically use the same rule for a wide interval, a discontinuity, a turning point with zero first derivative, or several correlated uncertain inputs. Those situations need more of the model than one slope.
We can estimate the same slope from values on either side of the reference point. Subtract the lower output from the upper output and divide by twice the input step. Parentheses are essential: the entire output difference must be divided by the entire input interval. Without them, Python can execute a different mathematical expression while still producing a plausible number.
The calculation below uses three decreasing step sizes. Each estimate is compared with the symbolic derivative, so the reference is independent of the numerical difference formula. Near an endpoint, it is acceptable here to evaluate a small extension only because the displayed mathematical expression is smooth there; such a check does not assert that extrapolated values describe additional physical cases.
input_span = 2.5
for fraction in [1e-2, 1e-3, 1e-4]:
step = input_span * fraction
upper = float(evaluate(reference_input + step))
lower = float(evaluate(reference_input - step))
numerical_slope = (upper - lower) / (2 * step)
difference = numerical_slope - slope_at_reference
print(f"step={step:.6g}: slope={numerical_slope:.6g}, difference={difference:.6g}")
For a smooth function, reducing the step often reduces the approximation error at first. Very small steps can eventually make subtraction of nearly equal floating-point values less reliable. Therefore “smaller” is not an unlimited guarantee of “better.” Compare the observed behaviour over a useful range of steps instead of choosing the smallest number the computer can represent.
An absolute slope difference is useful when the expected slope is near zero. A relative difference would divide by a very small reference and could look enormous even when the absolute discrepancy is tiny. Away from zero, a relative difference can help compare quantities with very different scales. The tolerance should reflect the question and the numerical method, rather than a universal decimal threshold copied into every test.
Make one copy of the reference calculation before editing it. Choose a second value of radial distance inside the stated interval, predict whether potential will rise or fall, and then evaluate the expression. Place the prediction and the result in a text cell. If they disagree, identify whether the mistake was in the sign, the unit conversion, the algebra, or the assumption about how the curve behaves.
Next choose a shorter plotting interval around the reference point. Compare the local curve with its tangent approximation. Then widen the interval again. The difference shows why a useful local estimate need not describe the whole range. Keep the axis labels and numerical scale visible when comparing the plots; automatic axis limits can make two different effects appear equally large.
Finally, return to the physical limit stated at the start: Finite-difference samples must avoid the singular source and use a physically meaningful spacing. Describe one change to the setup that would violate that limit. State what new input, equation, or observation would be needed before trusting an answer in the changed situation. This last step connects the Python experiment to the physics instead of treating successful execution as the only criterion for a useful result.
Before saving, restart the runtime and run all cells in order. A result that depends on an earlier, now-deleted input cell is not reproducible from the saved notebook. Keep unrounded values for later calculations, round only the reported output, and label any new data as measured, assumed, or generated. The graph and printed values should remain traceable to the same expression and the same choices of inputs.
There is another way to check that the expression and its derivative describe the same relationship. Add up the small output changes predicted by the slope across the chosen input interval. In the continuous limit, this integral equals the output at the upper endpoint minus the output at the lower endpoint. The result has units of V: the input unit in the integration cancels the input unit in the denominator of the slope.
This statement is about the mathematics of this particular relationship. It does not assign a new physical meaning to an arbitrary area under a graph. For example, an area under force versus distance represents work, while an area under a different pair of quantities may represent something else or have no standard name. Always carry the axis units through the calculation before naming an integral.
slope_function = sp.lambdify(q, slope_expression, modules="numpy")
endpoint_change = float(evaluate(3.0) - evaluate(0.5))
for points in [101, 201, 401]:
grid = np.linspace(0.5, 3.0, points)
slopes = np.asarray(slope_function(grid), dtype=float)
slopes = np.broadcast_to(slopes, grid.shape)
integrated_change = np.trapezoid(slopes, grid)
print(
points,
"integrated change:",
integrated_change,
"endpoint change:",
endpoint_change,
)
The trapezoidal rule joins neighbouring slope samples with straight segments and adds their signed areas. A negative contribution remains negative; replacing every slope by its magnitude would calculate a different quantity. Increasing the sample count provides a practical refinement check. If the values do not settle toward the endpoint difference, first inspect the interval, singularities, and array ordering.
Do not conclude that two agreeing calculations prove the model is physically complete. Both use the same selected relationship, so an omitted effect would be omitted from both. Their agreement is evidence that the numerical tools implement that relationship consistently. Comparing with an independent experiment or a more appropriate physical model is a separate test.
Keep this comparison in the notebook when you change the expression. It is particularly useful after adding a coefficient, changing a sign convention, or converting an input unit. A code cell that produces a smooth graph can conceal these mistakes; a second calculation of the same output change gives you another place to notice them.