A constraint restricts the configurations a system may occupy. A bead threaded on a wire can move along the wire but not away from it. A particle on a sphere can move in two independent surface directions even though its Cartesian position has three components. The allowed configurations form a lower-dimensional geometric set called a constraint manifold when the constraint is smooth and regular.
A holonomic constraint can be written as an equation involving coordinates and possibly time:
\[C(\mathbf q,t)=0\]The generalized coordinate vector \(\mathbf q\) may contain Cartesian components, angles, or other configuration variables. A time-independent constraint is scleronomous; an explicitly time-dependent one is rheonomous.
For a particle restricted to a circle of radius \(R\) centered at the origin,
\[C(x,y)=x^2+y^2-R^2=0\]Two Cartesian coordinates are stored, but one independent equation removes one degree of freedom. Away from singular points of the constraint description, the allowed set is one-dimensional. It can be parameterized by one angle:
\[x=R\cos\phi,\qquad y=R\sin\phi\]Using the angle enforces the circle exactly at the configuration level. It also introduces angle wrapping and a periodic coordinate, which must be handled deliberately.
An allowed position is not enough. Differentiate the constraint along the motion:
\[\frac{dC}{dt}=\nabla_{\mathbf q}C\cdot\dot{\mathbf q}+\frac{\partial C}{\partial t}=0\]For the fixed circle,
\[2x\dot x+2y\dot y=0\]or, in vector form, \(\mathbf r\cdot\mathbf v=0\). The allowed velocity is tangent to the circle. A position exactly on the circle paired with an outward velocity is an inconsistent state even before the next numerical step.
import numpy as np
position = np.array([2.0, 0.0])
velocity = np.array([0.0, 3.0])
radius = 2.0
position_residual = np.dot(position, position) - radius**2
tangent_residual = np.dot(position, velocity)
assert abs(position_residual) < 1e-12
assert abs(tangent_residual) < 1e-12
print("Position and tangent constraints satisfied.")
The two tolerances have different units. One raw numeric tolerance cannot describe both residuals coherently.
Differentiate the fixed-circle velocity condition again:
\[\mathbf v\cdot\mathbf v+\mathbf r\cdot\mathbf a=0\]Therefore the radial acceleration component satisfies
\[\mathbf r\cdot\mathbf a=-v^2\]For uniform circular motion this becomes the inward acceleration of magnitude \(v^2/R\). Tangent velocity does not imply zero acceleration. The constraint continuously bends the trajectory through a normal force even when speed is constant.
For a general time-independent scalar constraint, differentiating twice yields terms from the constraint's curvature. Projecting acceleration only into the tangent plane can be wrong because a normal acceleration may be required to stay on a curved manifold.
For an ideal smooth holonomic constraint, the reaction force is often normal to the allowed manifold. With mass matrix \(\mathbf M\), applied generalized force \(\mathbf Q\), and one constraint, the equations may be written
\[\mathbf M\ddot{\mathbf q}=\mathbf Q+\lambda\nabla C\]The multiplier \(\lambda\) is chosen so the acceleration satisfies the differentiated constraint. The product
\(\lambda\nabla C\)is the constraint force in these coordinates.
For several constraints, collect their gradients into a Jacobian \(\mathbf J\) and use a vector of multipliers. Solving for them is a coupled dynamics problem, not a cosmetic coordinate clamp.
On a horizontal frictionless surface, the normal reaction cancels the forbidden vertical acceleration while doing no work for horizontal tangent displacement. On a rough surface, friction is a separate tangent interaction and the “normal only” ideal constraint model no longer describes the whole contact force.
There are two common approaches.
An intrinsic parameterization uses only independent coordinates. For a circle, solve for \(\phi(t)\) and recover Cartesian position afterward. The geometric constraint is exact by construction, and the state has no redundant coordinate. Finding a nonsingular global parameterization can be difficult for complicated manifolds.
An extrinsic formulation keeps convenient ambient coordinates such as \((x,y)\) and adds constraint equations or forces. It integrates naturally with Cartesian force models but requires a coupled solve and control of constraint drift.
Neither approach is universally better. The choice should preserve the physical degrees of freedom, avoid singular coordinates where possible, and expose how reaction forces are recovered if they are needed.
After an unconstrained numerical step, a simple circle projection is
\[\mathbf r_{\mathrm{proj}}=R\frac{\mathbf r^*}{|\mathbf r^*|}\]This is undefined if the trial position is the origin. It corrects position but leaves a possibly normal velocity. A corresponding tangent projection is
\[\mathbf v_{\mathrm{tan}}=\mathbf v^*-\left(\mathbf v^*\cdot\hat{\mathbf r}\right)\hat{\mathbf r}\]def project_circle(position, velocity, radius):
distance = np.linalg.norm(position)
if distance < 1e-12:
raise ValueError("Cannot project the centre onto a unique circle point.")
normal = position / distance
projected_position = radius * normal
projected_velocity = velocity - np.dot(velocity, normal) * normal
return projected_position, projected_velocity
p, v = project_circle(np.array([2.1, 0.1]), np.array([0.2, 3.0]), 2.0)
print(p, v)
assert np.isclose(np.dot(p, v), 0.0, atol=1e-12)
Projection changes momentum and usually changes kinetic energy. It acts like an implicit correction impulse, but its physical meaning may be unclear. Constraint- preserving algorithms such as SHAKE- or RATTLE-like methods solve position and velocity conditions more systematically. Even then, tolerances and convergence must be checked.
Finite-step integration can move a state gradually away from \(C=0\). Track a residual such as
\[\varepsilon_C=|C(\mathbf q,t)|\]and a velocity residual from the differentiated constraint. Residuals should be scaled to meaningful physical units; the circle expression has length-squared units. A dimensionless relative measure might divide by \(R^2\) when the radius is nonzero.
Smaller residual does not by itself mean a more accurate trajectory. Aggressive projection can keep geometry exact while corrupting phase, momentum, or energy. Compare the trajectory with an analytic solution or a refined calculation and monitor relevant conservation laws as well.
If the constraint depends explicitly on time, the allowed velocity condition includes \(\partial C/\partial t\). A bead on a moving wire can have a velocity component normal to the wire's instantaneous shape while still satisfying the moving constraint. Requiring only
\(\nabla C\cdot\dot{\mathbf q}=0\)would incorrectly treat every constraint as stationary.
A moving ideal constraint can do work on the particle. The familiar statement that an ideal normal force does no work applies when allowed displacement is tangent to a fixed constraint, not automatically to a driven moving boundary.
A surface contact often uses an inequality such as \(C(\mathbf q)\ge0\). The reaction acts only while contact is active and cannot pull two ordinary bodies together. Contact activation, separation, impact, and friction need complementarity or event rules beyond an equality manifold.
A nonholonomic constraint restricts velocities and cannot generally be integrated into a position-only equation. Ideal rolling without slipping is a standard example. It relates translational and angular velocities. Treating every velocity constraint as the derivative of some coordinate equation can remove or add the wrong degrees of freedom.
For \(n\) coordinates and \(m\) regular independent constraints, the local number of configuration degrees of freedom is
\[N_{\mathrm{dof}}=n-m\]This count requires the constraint Jacobian to have rank \(m\). Redundant constraints can make the multiplier system singular without reducing another physical degree of freedom. Constraint gradients that vanish or become dependent mark singular configurations where the local manifold description can fail.
Constraint manifolds explain how a system can live in a lower-dimensional set while being represented in a larger coordinate space. Preserving that geometry requires compatible velocities, curvature-dependent acceleration, and reaction forces—not only valid-looking positions.
Describe the upper branch of a radius 2 metre circle as a constrained path. The question for this calculation is precise: how does upper-circle height change when we change horizontal coordinate, 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.
The square-root branch covers only the upper semicircle and becomes steep near its endpoints. 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 horizontal coordinate, expressed in m. The output is
upper-circle height, expressed in m. 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 1.73205 m. 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("sqrt(4-q**2)", locals={"q": q})
reference_input = 1.0
reference_output = float(expression.subs(q, reference_input))
print("Input:", reference_input, "m")
print("Predicted upper-circle height:", reference_output, "m")
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.32288 m. The midpoint, at 0 m, gives 2 m. The upper endpoint gives 1.32288 m. Read these together with the assumptions: they describe different choices of horizontal coordinate 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} m")
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 horizontal coordinate; the vertical axis shows upper-circle height. 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("Horizontal coordinate (m)")
ax.set_ylabel("Upper-circle height (m)")
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 upper-circle height 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 -0.57735 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{q}{\sqrt{4 - 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.015
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, "m")
print("Full expression:", full_prediction, "m")
print("Approximation difference:", full_prediction - linear_prediction, "m")
Here the changed input is 1.015 m. The tangent estimate is 1.72339 m, while the full expression gives 1.7233 m. 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 horizontal coordinate inside the stated interval, predict whether upper-circle height 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: The square-root branch covers only the upper semicircle and becomes steep near its endpoints. 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 m: 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.