A Byte of PhysicsLogo

Numerical drift in rotation

Numerical drift is a systematic departure from a model's expected behavior as repeated approximations accumulate. A rotating object may look smooth while its calculated energy, angular momentum, phase, or orientation constraints gradually become wrong. Drift must be measured against the correct physical balance, not judged from appearance.

What can drift

For a fixed-axis rigid body with constant moment of inertia \(I\), angular momentum and rotational kinetic energy are

\[L=I\omega,\qquad K_{\mathrm{rot}}=\frac12I\omega^2\]

With no external torque, \(L\) should be constant. Energy is constant only when the modeled system is conservative and includes all relevant energy stores. Friction, damping, a motor, or a changing constraint can produce physical energy change.

Even when invariants remain close, phase can drift. An oscillator may preserve nearly the right energy but reach its turning point too early on every cycle. Orientation can also violate its mathematical representation: a quaternion can lose unit length, or a rotation matrix can cease to be orthogonal.

Residuals rather than raw change

The angular impulse balance is

\[L(t_b)-L(t_a)=\int_{t_a}^{t_b}\tau_{\mathrm{ext}}(t)\,dt\]

Define a numerical residual by subtracting the expected transfer:

\[r_L=L_b-L_a-J_{\tau,\mathrm{ext}}\]

For energy, use

\[r_E=E_b-E_a-W_{\mathrm{external}}-Q_{\mathrm{modeled}}\]

The sign of work and heat terms follows the declared system convention. The residual is the unexplained remainder. Demanding raw energy constancy while a drive performs work mislabels correct physics as numerical drift.

initial_l, final_l, angular_impulse = 1.0, 1.6, 0.6
initial_energy, final_energy, work = 1.0, 2.56, 1.56
print("Angular momentum residual:", final_l - initial_l - angular_impulse)
print("Energy residual:", final_energy - initial_energy - work)

Report vector angular-momentum residuals in three dimensions. A small magnitude alone can hide which component or sign is wrong.

Forward Euler and artificial energy growth

For an undamped torsional oscillator,

\[I\ddot\theta=-\kappa\theta\]

the exact mechanical energy is

\[E=\frac12I\omega^2+\frac12\kappa\theta^2\]

Forward Euler uses

\[\theta_{n+1}=\theta_n+\omega_n\Delta t,\qquad \omega_{n+1}=\omega_n-\frac{\kappa}{I}\theta_n\Delta t\]

Substitution shows that its energy grows by a positive term proportional to the square of the step for any nonzero state. Each individual increase can be small, yet repeated steps spiral outward in angular phase space. A smooth trace does not remove this algorithmic bias.

Semi-implicit Euler updates angular velocity first and uses the new value for angle. It often keeps oscillatory energy error bounded, although the exact energy still fluctuates. Higher-order methods can reduce short-time truncation error but do not automatically preserve long-time geometric structure.

Compare at the same physical time

If one calculation uses step \(\Delta t\) and another uses half that step, the second takes twice as many updates to reach the same physical duration. Comparing both after the same step count compares different experiments.

Choose checkpoint times first. Advance each method to those times, using dense output or careful final substeps if needed. Compare angle, angular velocity, invariant residuals, and event timing at those shared times.

for steps in [100, 200, 400]:
    theta, omega, dt = 1.0, 0.0, 10.0 / steps
    errors = []
    for _ in range(steps):
        omega -= theta * dt
        theta += omega * dt
        errors.append(abs(0.5 * (theta**2 + omega**2) - 0.5))
    print(steps, "maximum torsional oscillator energy error:", max(errors))

Convergence should be assessed before selecting a tolerance. If halving the step no longer changes the result because roundoff, event error, or another approximation dominates, further refinement of that one parameter does not improve accuracy.

Absolute and relative measures

An absolute residual retains physical units and matters near zero. A relative residual helps compare across scales:

\[\varepsilon_E=\frac{|r_E|}{E_{\mathrm{scale}}}\]

The scale should not be a nearly cancelling total if large positive and negative terms exist. Use a characteristic sum of magnitudes or another physically justified reference. For angular momentum that is theoretically zero, only a relative error divided by the initial value is undefined; an absolute scale from typical individual angular momenta is needed.

Track maximum, final, and root-mean-square residual. A final value near zero can hide large intermediate error that later cancels. Plotting only rounded values can hide small but systematic trends.

Angle wrapping can imitate drift

Angles used for display may be wrapped into one turn. A transition from just below \(2\pi\) to just above zero is continuous physical rotation but appears as a large negative jump. Never calculate phase error, angular velocity, or accumulated rotation by naive subtraction of wrapped angles.

Keep an unwrapped angle or turn count. When comparing orientations where completed turns do not matter, use a periodic difference such as

\[\delta\theta=\operatorname{atan2}\left[\sin(\theta_1-\theta_2),\cos(\theta_1-\theta_2)\right]\]

This returns a principal signed orientation difference, not accumulated displacement. Choose the comparison that matches the question.

Roundoff and long duration

Floating-point arithmetic rounds every operation. Random-looking roundoff may grow like a walk, while biased summation or asymmetric force evaluation can produce steady drift. Using a smaller time step increases the number of operations, so truncation error falls while accumulated roundoff may eventually become more important.

Keep time with an integer step count when using a fixed step, then derive physical time from count and step. Repeatedly adding a floating-point step can accumulate clock error. Use compensated summation for long energy or impulse ledgers when cancellation is severe.

Constraint drift in rolling

For ideal rolling on a stationary surface, a signed constraint has the form

\[C=v_{\mathrm{cm}}+R\omega=0\]

Independent translation and rotation updates can make \(C\) grow even if each subsystem looks reasonable. Projection can force the residual back to zero, but an arbitrary correction may change momentum or energy. A constraint impulse should account for mass, inertia, contact geometry, and friction limits.

Measure constraint residual separately from conservation residuals. Perfect constraint satisfaction can coexist with incorrect energy transfer.

Three-dimensional orientation drift

A unit quaternion \(q\) must satisfy

\[q\cdot q=1\]

A rotation matrix must satisfy

\[\mathbf R^{\mathsf T}\mathbf R=\mathbf I,\qquad \det\mathbf R=1\]

Naive additive updates can violate these conditions. Renormalizing a quaternion or re-orthogonalizing a matrix controls representation drift but does not prove that the physical trajectory is accurate. Compare orientation against a refined or analytic solution and monitor angular momentum and energy too.

The frame of angular velocity matters. Body-frame and world-frame rates multiply the orientation update on different sides. Mixing them can yield a normalized but physically wrong rotation.

Discontinuous events

Impacts, hard stops, clutches, and friction transitions create events. Error may be dominated by locating event time rather than by the smooth integrator between events. Record pre-event state, event impulse, post-event state, and balance residual. Reduce the event tolerance separately from the regular step.

Applying the same contact impulse over several overlapping steps can create angular- momentum drift. Conversely, silently clamping angular velocity at a stop removes energy and momentum without a ledger. Event changes must be part of the physical accounting.

A layered validation sequence

Begin with zero torque and fixed inertia: angular velocity must remain constant and angle must be linear in time. Continue with constant torque, which has an exact quadratic angle. Then use a conservative torsional oscillator to test phase and bounded energy error. Add damping only after conservative behavior is understood, and verify its predicted energy loss.

For each layer, change one numerical parameter at a time. A reference result calculated with the same flawed method at only a smaller step is evidence of convergence, not an independent proof. Where possible, retain analytic solutions and balance identities.

Reliability checks

Numerical drift becomes diagnosable when every expected transfer and representation constraint has its own residual. The goal is not a perfectly flat graph at any cost, but a calculation whose remaining error decreases predictably and whose physical changes are fully accounted for.

A worked Python notebook

Evaluate the energy diagnostic for a rotor with inertia 0.5 kilogram metres squared. The question for this calculation is precise: how does rotational energy change when we change angular velocity, 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.

An energy change can be physical when external torque does work; drift is the unexplained residual. 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 -4 to 4 rad/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 angular velocity, expressed in rad/s. The output is rotational 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.

\[f(q) = \frac{q^{2}}{4}\]

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 2 rad/s, the expression gives 1 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/4", locals={"q": q})
reference_input = 2.0
reference_output = float(expression.subs(q, reference_input))
print("Input:", reference_input, "rad/s")
print("Predicted rotational 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.

Compare a few cases you can explain

Before drawing hundreds of points, calculate three. The lower endpoint gives 4 J. The midpoint, at 0 rad/s, gives 0 J. The upper endpoint gives 4 J. Read these together with the assumptions: they describe different choices of angular velocity 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([-4.0, 0.0, 4.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} rad/s -> {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.

Make a graph that answers the question

The horizontal axis shows angular velocity; the vertical axis shows rotational 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(-4.0, 4.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("Angular velocity (rad/s)")
ax.set_ylabel("Rotational 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.

Measure the local sensitivity

A derivative asks a more specific question than the whole graph: how quickly does rotational energy change near the reference input? Its units are the output unit divided by the input unit. For this calculation, the derivative at 2 rad/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) = \frac{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 = 2.04
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 2.04 rad/s. The tangent estimate is 1.04 J, while the full expression gives 1.0404 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.

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

Change the example and preserve the reasoning

Make one copy of the reference calculation before editing it. Choose a second value of angular velocity inside the stated interval, predict whether rotational 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: An energy change can be physical when external torque does work; drift is the unexplained residual. 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 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(4.0) - evaluate(-4.0))
for points in [101, 201, 401]:
    grid = np.linspace(-4.0, 4.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.

Sources


Share to: