A Byte of PhysicsLogo

Motion with constraints

A constraint restricts the configurations a system may occupy. A bead on a straight rail segment must remain between its endpoints. A box resting on a floor cannot move through the floor. Enforcing the allowed position is only part of the physics: the constraint interaction can also change velocity and exert a reaction force.

A one-dimensional rail

Let a bead's coordinate be \(x\) on a rail from \(x=0\) to \(x=L\). The geometric constraint is

\[0\le x\le L\]

This is a unilateral constraint: it prevents motion outside an interval but does not force the bead to stay at an endpoint. In the interior, ordinary equations of motion apply. At an endpoint, the rail stop may provide an impulse during collision or a continuous reaction force if another force keeps pressing the bead against it.

Before solving anything, require \(L>0\) and use one consistent length unit. The initial position must satisfy the constraint unless the program has an explicit recovery policy for invalid input.

Why clamping is not a collision model

The expression

rail_length_m = 2.0
proposed_position_m = 2.3
clamped_position_m = max(0.0, min(rail_length_m, proposed_position_m))
print(f"Clamped position: {clamped_position_m:.1f} m")
# Clamping alone does not calculate an impact velocity.

guarantees an allowed position. It says nothing about velocity. If a bead crosses the right wall at high speed, clamping it to the endpoint while leaving velocity positive causes the next update to penetrate again. Setting velocity to zero makes the collision perfectly inelastic against an immovable wall. Negating velocity makes it perfectly elastic in the wall's frame. These are different physical rules.

Clamping also loses when the impact occurred. If the bead reaches the wall halfway through a step, it should spend the remaining half-step in its post-impact state. Leaving it at the wall until the next step makes the trajectory depend strongly on the arbitrary step grid.

Position projection can be a useful numerical safeguard, especially for tiny errors, but it must not be described as a complete collision solution.

A coefficient-of-restitution rule

For a bead colliding normally with a stationary massive wall, a simple impact model is

\[v^+=-e v^-\]

Here \(v^-\) and \(v^+\) are measured in the wall's frame. The coefficient of restitution \(e\) is dimensionless and commonly lies from zero to one in this simple passive model.

When \(e=1\), speed is preserved and the direction reverses. When \(e=0\), the normal post-impact velocity is zero. For a fixed bead mass, the ratio of post-impact to pre-impact kinetic energy in the normal motion is

\[\frac{K^+}{K^-}=\frac{\tfrac12m(v^+)^2}{\tfrac12m(v^-)^2}=e^2\]

Energy not retained as translational kinetic energy may become deformation, sound, heat, or internal vibration. Momentum of the bead alone is not conserved because the wall and Earth exchange impulse with it; a larger closed system is needed for momentum conservation.

Locate the impact inside a step

For constant positive velocity in the interior, a bead at position \(x_0\) reaches the right wall after

\[t_{\mathrm{hit}}=\frac{L-x_0}{v},\qquad v>0\]

If this time lies inside the proposed step, split the step at the event.

position_m, velocity_m_per_s = 1.8, 1.0
rail_length_m, restitution, step_s = 2.0, 0.8, 0.5
time_to_impact = (rail_length_m - position_m) / velocity_m_per_s
if time_to_impact <= step_s:
    remaining_s = step_s - time_to_impact
    velocity_m_per_s *= -restitution
    position_m = rail_length_m + velocity_m_per_s * remaining_s
else:
    position_m += velocity_m_per_s * step_s
print(f"After impact: {position_m:.3f} m, {velocity_m_per_s:.3f} m/s")

The impact record should include endpoint, event time, incoming velocity, outgoing velocity, and applied rule. That evidence makes energy and step-refinement checks possible.

Multiple impacts in one step

If a large step or high speed allows the bead to cross the whole rail after bouncing, there may be more than one impact in a single proposed step. Handling only one can still leave the final state outside the interval.

An event loop advances to the earliest reachable endpoint, updates velocity, subtracts the consumed time, and repeats until no event remains. It needs a maximum event count or minimum progress rule to prevent an infinite loop when numerical noise repeatedly reports an event at zero time.

def advance_on_rail(position, velocity, duration, length=2.0, restitution=1.0):
    if not (0 <= position <= length and length > 0 and duration >= 0):
        raise ValueError("Invalid rail, position, or duration.")
    if not 0 <= restitution <= 1:
        raise ValueError("Restitution must lie between zero and one.")
    remaining = duration
    impacts = 0
    while remaining > 0 and velocity != 0:
        wall = length if velocity > 0 else 0.0
        hit_time = (wall - position) / velocity
        if hit_time > remaining:
            position += velocity * remaining
            break
        position = wall
        remaining -= hit_time
        velocity *= -restitution
        impacts += 1
        if impacts > 1000:
            raise RuntimeError("Too many impacts; use a shorter interval.")
    return position, velocity, impacts


print(advance_on_rail(1.0, 3.0, 2.0))

For constant speed and perfectly elastic walls, an analytic reflection or folded- coordinate solution can avoid repeated events. The chosen algorithm should match the forces and impact law actually modeled.

Contact without rebound

Suppose gravity or another applied force pushes an object into a floor. After an inelastic impact removes inward velocity, the floor supplies a normal reaction force so the object does not begin accelerating through it again.

In one dimension, a contact force is active only when the object is at the boundary and the unconstrained applied force would point outward from the allowed region. The reaction cancels that forbidden component. If the applied force points back into the allowed region, contact releases and the object moves away.

This force cannot be inferred from position clamping alone. Static contact is a force constraint problem, while a collision is an impulse event over a very short interval. Real contacts may also involve compliance, damping, friction, and finite deformation.

Position correction and numerical tolerance

Floating-point calculations may produce a tiny penetration such as a position just beyond the wall after an event. Projecting that small residual to the endpoint can keep the invariant clean. The tolerance must be tied to the problem scale and numerical method. A large penetration should trigger event handling or an error, not be silently erased as if it were roundoff.

Use separate tolerances for position, time, and velocity because they have different units. A raw constant such as 1e-6 cannot meaningfully serve all three.

Constraint checks

Tests should cover geometry and dynamics:

These tests verify the stated model. They do not determine the restitution of a real material or prove that a rigid wall is appropriate. Those values and approximations need measurement or a more detailed contact model.

Constraints express physical interactions

A constraint is more than form validation. It represents geometry and forces or impulses that prevent forbidden motion. A simple clamp can enforce a visual boundary, but a physical explanation must state what happens to velocity, momentum, energy, and elapsed time at contact.

Separating unconstrained prediction, event detection, interaction response, and residual correction makes those choices inspectable. It also shows exactly which simplifications must change when the model grows from a bead on a rail to deformable or frictional contact.

A worked Python notebook

A cart at 1.8 metres approaches the right end of a 2 metre rail at 1 metre per second. The question for this calculation is precise: how does position change when we change time before impact, 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 formula ends at contact; the rebound uses a new velocity and a new branch. 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 to 0.2 s. 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.

State the relationship before choosing a graph

In this small example, q stands for time before impact, expressed in s. The output is position, 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.

\[f(q) = q + 1.8\]

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.1 s, the expression gives 1.9 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("1.8+q", locals={"q": q})
reference_input = 0.1
reference_output = float(expression.subs(q, reference_input))
print("Input:", reference_input, "s")
print("Predicted position:", 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.

Compare a few cases you can explain

Before drawing hundreds of points, calculate three. The lower endpoint gives 1.8 m. The midpoint, at 0.1 s, gives 1.9 m. The upper endpoint gives 2 m. Read these together with the assumptions: they describe different choices of time before impact 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.0, 0.1, 0.2])
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} s -> {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.

Make a graph that answers the question

The horizontal axis shows time before impact; the vertical axis shows position. 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.0, 0.2, 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("Time before impact (s)")
ax.set_ylabel("Position (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.

Measure the local sensitivity

A derivative asks a more specific question than the whole graph: how quickly does position change near the reference input? Its units are the output unit divided by the input unit. For this calculation, the derivative at 0.1 s is 1 in those ratio units. Locally, the output increases as the input increases. This statement is local; the sign or size of the slope can be different elsewhere on the curve.

\[f'(q) = 1\]

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.101
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 0.101 s. The tangent estimate is 1.901 m, while the full expression gives 1.901 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.

Check the derivative with numerical differences

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 = 0.2
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.

Change the example and preserve the reasoning

Make one copy of the reference calculation before editing it. Choose a second value of time before impact inside the stated interval, predict whether position 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 formula ends at contact; the rebound uses a new velocity and a new branch. 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.

Recover the output change by integrating the slope

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(0.2) - evaluate(0.0))
for points in [101, 201, 401]:
    grid = np.linspace(0.0, 0.2, 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.

Sources


Share to: