Many static configurations can be predicted by asking which allowed arrangement has the lowest potential energy. A hanging mass settles below its support, a stretched spring pulls toward its natural length, and a bead under gravity tends toward a low point on its track. The method is powerful because it can replace vector force balances with one scalar function, but it works only when the energy, constraints, and meaning of "minimum" are stated carefully.
For one conservative coordinate, force and potential energy are related by
\[F(x)=-\frac{dU}{dx}\]At an interior equilibrium,
\[\left.\frac{dU}{dx}\right|_{x_*}=0\]This condition says only that \(x_*\) is stationary. A strict local minimum is stable against sufficiently small displacement in an ideal conservative model, while a maximum is unstable. A stationary inflection point may be neither.
For a smooth one-dimensional potential, the usual curvature test is
\[U''(x_*)>0\Rightarrow\text{strict local minimum}\]If \(U''(x_*)=0\), the test is inconclusive. For example, \(U=ax^4\) with positive \(a\) has a minimum at the origin even though its second derivative vanishes there. Nearby values or higher-order terms must be examined.
A local minimum has no lower allowed neighbor. A global minimum has no lower allowed configuration anywhere in the domain. Physical systems can remain for a long time in a local minimum separated from a lower one by an energy barrier; this is a metastable state. Saying "the system minimizes energy" without specifying local or global behavior can therefore be misleading.
The minimum may also occur at a boundary where the derivative is not zero. For a mass restricted to heights \(h\ge0\), the gravitational potential near Earth's surface is
\[U(h)=mgh\]Its derivative is positive everywhere, yet its allowed minimum is at \(h=0\). The floor supplies the constraint force. Searching only for zero derivatives would miss the correct answer.
import numpy as np
def potential(x):
return (x * x - 1) ** 2
candidates = np.linspace(-2, 2, 401)
best = min(candidates, key=potential)
print(f"One minimum: x={best:.3f} m, U={potential(best):.3f} J")
A discrete search is conceptually simple, but its resolution can miss a narrow well. Refine the configuration spacing and verify that the reported location and energy converge.
For generalized coordinates \(\mathbf q=(q_1,\ldots,q_n)\), an unconstrained interior stationary point satisfies
\[\nabla U(\mathbf q_*)=\mathbf0\]The Hessian matrix contains the local curvatures:
\[H_{ij}=\left.\frac{\partial^2U}{\partial q_i\partial q_j}\right|_{\mathbf q_*}\]If every Hessian eigenvalue is positive, the stationary point is a strict local minimum in the unconstrained coordinates. A negative eigenvalue identifies a direction in which energy decreases. Mixed positive and negative signs describe a saddle. Zero eigenvalues may represent a symmetry, a redundant coordinate, or a need for higher-order analysis.
Coordinates can have different units and scales. A raw gradient component in radians cannot be compared numerically with one in metres without a scale or metric. Optimizer tolerances must be dimensionally meaningful, and a change of coordinates should not change the physical conclusion.
Suppose configurations obey \(g_a(\mathbf q)=0\). At a constrained stationary point, the potential gradient need not vanish in the full space. Instead,
\[\nabla U(\mathbf q_*)+\sum_a\lambda_a\nabla g_a(\mathbf q_*)=\mathbf0\]The multipliers \(\lambda_a\) encode constraint reactions in a coordinate-dependent way. Stability must be tested only along tangent perturbations that preserve the constraints to first order:
\[\nabla g_a(\mathbf q_*)\cdot\delta\mathbf q=0\]For inequality constraints, candidates can occur inside the domain or on active boundaries. Checking only the unconstrained minimum can place objects through walls, stretch inextensible links, or violate fixed-volume conditions.
# Minimise x on the unit circle by projected gradient descent.
point = np.array([0.6, 0.8])
for _ in range(300):
gradient = np.array([1.0, 0.0])
tangent_gradient = gradient - np.dot(gradient, point) * point
proposed = point - 0.1 * tangent_gradient
proposed /= np.linalg.norm(proposed)
if proposed[0] <= point[0]:
point = proposed
print("Constrained minimum:", point)
assert np.isclose(np.linalg.norm(point), 1.0)
Projection followed by constraint restoration is one numerical approach, not a universal recipe. A poor projection can drift off the physical manifold, and a restoration step can change the energy unexpectedly.
For a simple pendulum with angle measured from the downward vertical, choose the zero of potential at the bottom:
\[U(\theta)=mg\ell\left(1-\cos\theta\right)\]Stationary angles satisfy \(\sin\theta=0\). The downward configuration at \(\theta=0\) is a minimum because \(U''(0)=mg\ell>0\). The inverted configuration at \(\theta=\pi\) is a maximum because \(U''(\pi)=-mg\ell<0\).
Angles differing by an integer multiple of \(2\pi\) describe the same orientation. Counting all of them as distinct minima would be a coordinate bookkeeping error.
Suppose a vertical spring extension \(y\) is positive downward and is measured from the spring's unstretched length. A consistent potential is
\[U(y)=\frac12ky^2-mgy\]Differentiation gives
\[\frac{dU}{dy}=ky-mg=0\quad\Rightarrow\quad y_*=\frac{mg}{k}\]Since \(U''=k>0\), this is a strict minimum when the ideal spring model and allowed extension include that value. The minus sign in the gravity term follows from choosing downward as positive; using upward as positive changes the coordinate formula but not the physical extension.
A common optimization update is
\[\mathbf q_{r+1}=\mathbf q_r-\alpha\nabla U(\mathbf q_r)\]Here \(r\) counts iterations and \(\alpha\) is chosen for the algorithm. This is generally not Newton's second law and does not reproduce the system's physical travel time or path. Real inertia can overshoot a minimum; damping, friction, temperature, and barriers can prevent or delay relaxation.
Gradient descent can also stop at a saddle where the gradient is small, oscillate when the step is too large, or advance painfully slowly along a narrow valley. Multiple initial guesses, curvature checks, and comparison with known symmetries are needed before interpreting a returned candidate physically.
At nonzero temperature, potential energy alone may not determine the most probable macroscopic state. Entropy matters, and equilibrium at fixed temperature is associated with minimizing an appropriate free energy rather than microscopic potential energy alone. Thermal fluctuations can cross finite barriers, so a local minimum has a lifetime rather than absolute permanence.
An externally driven or actively controlled system may maintain a steady configuration that is not an energy minimum. Nonconservative forces may have no single-valued potential at all. Before minimizing, confirm that the relevant forces are conservative and that the environmental constraints match the thermodynamic or mechanical question.
First verify the objective function. Shift the potential by a constant and confirm that the minimizing configuration does not change. Differentiate the coded potential and compare \(-\nabla U\) with an independently implemented force at several configurations. Check units term by term.
Next verify the optimizer. Test a quadratic potential whose exact minimum and Hessian are known. Start from several initial configurations. Reduce stopping tolerances and step sizes independently, and report the constraint residual as well as the energy gradient. For a claimed global minimum, compare every known boundary, symmetry-related branch, and competing basin.
def minimise(start):
x = start
for _ in range(1000):
gradient = 4 * x * (x * x - 1)
if abs(gradient) < 1e-10:
break
x -= 0.02 * gradient
return x
for start in [-1.5, -0.2, 0.2, 1.5]:
result = minimise(start)
curvature = 12 * result**2 - 4
print(start, result, potential(result), curvature)
assert curvature > 0
Uncertainty in model parameters can move a minimum or change which basin is lowest. Repeat the minimization over plausible parameter values when that uncertainty affects the conclusion. Reporting more digits from the optimizer does not reduce physical uncertainty.
Energy minimization is most reliable as a carefully constrained equilibrium method. It can identify stable configurations without following every transient, but it does not by itself explain how quickly a system reaches them, whether it crosses a barrier, or whether nonconservative and thermal effects dominate the observed behavior.
Locate minima in a double well and distinguish them from the stationary point at its centre. The question for this calculation is precise: how does potential energy change when we change position, 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.
A local optimiser can return different minima from different initial guesses. 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 -1.5 to 1.5 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 position, expressed in m. The output is
potential energy, expressed in J. 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 0.8 m, the expression gives 0.1296 J. 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("(q**2-1)**2", locals={"q": q})
reference_input = 0.8
reference_output = float(expression.subs(q, reference_input))
print("Input:", reference_input, "m")
print("Predicted potential energy:", reference_output, "J")
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 1.5625 J. The midpoint, at 0 m, gives 1 J. The upper endpoint gives 1.5625 J. Read these together with the assumptions: they describe different choices of position 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([-1.5, 0.0, 1.5])
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} J")
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 position; the vertical axis shows potential energy. 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(-1.5, 1.5, 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("Position (m)")
ax.set_ylabel("Potential energy (J)")
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 energy change near the reference input? Its units are the output unit divided by the input unit. For this calculation, the derivative at 0.8 m is -1.152 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) = 4 q \left(q^{2} - 1\right)\]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 = 0.8150000000000001
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, "J")
print("Full expression:", full_prediction, "J")
print("Approximation difference:", full_prediction - linear_prediction, "J")
Here the changed input is 0.815 m. The tangent estimate is 0.11232 J, while the full expression gives 0.112745 J. 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 = 3.0
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 position inside the stated interval, predict whether potential energy 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: A local optimiser can return different minima from different initial guesses. 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 J: 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(1.5) - evaluate(-1.5))
for points in [101, 201, 401]:
grid = np.linspace(-1.5, 1.5, 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.