A Byte of PhysicsLogo

Discrete vs continuous motion

Classical kinematics usually models time and position as continuous quantities. A computer stores only finitely many values, a sensor records samples at particular times, and a numerical method advances state in finite steps. The samples are not the continuous trajectory itself; they are selected information about it.

Continuous motion as a function

For constant acceleration in one dimension,

\[x(t)=x_0+v_0t+\frac{1}{2}at^2\]

assigns a position to every time in its domain. Velocity and acceleration follow from derivatives:

\[v(t)=v_0+at,\qquad a(t)=a\]

The functions are continuous in time. This does not mean every real motion is perfectly described by them. Constant acceleration remains an idealization, and a collision may be represented by an abrupt velocity change. "Continuous" describes the mathematical independent variable and trajectory between modeled events, not the completeness of the physics.

Sampling a known trajectory

Choose a sample interval \(\Delta t\) and store values at

\[t_n=t_0+n\Delta t\]

The position samples are \(x_n=x(t_n)\). If the analytic function is known, sampling evaluates it directly; there is no integration truncation error in the positions. The array still omits what happens between sample times.

import numpy as np

times_s = np.linspace(0, 2, 9)
positions_m = 0.5 * 9.81 * times_s**2
for time, position in zip(times_s, positions_m):
    print(f"{time:.2f} s: {position:.3f} m downward")

Time must be stored beside every sample. Assuming a constant interval from an array index is unsafe when data can be dropped, delayed, or measured at irregular times.

Stepping is different from sampling

When no closed-form trajectory is available, a numerical method estimates later state from earlier state. Forward Euler for position and velocity uses

\[x_{n+1}=x_n+v_n\Delta t,\qquad v_{n+1}=v_n+a_n\Delta t\]

Now the stored values depend on the step size and method. Sampling a known analytic function at coarse times loses between-sample detail but gives the exact model value at each sample. Euler stepping at those same times also introduces truncation error. These two operations should not be described as if they were the same.

position_m = 0.0
velocity_m_per_s = 0.0
time_s = 0.0
end_s = 2.0
dt_s = 0.1
while time_s < end_s:
    step_s = min(dt_s, end_s - time_s)
    position_m += velocity_m_per_s * step_s
    velocity_m_per_s += 9.81 * step_s
    time_s += step_s
print(f"Euler distance: {position_m:.3f} m")
print(f"Exact distance: {0.5 * 9.81 * end_s**2:.3f} m")

Shortening the final step prevents the algorithm from silently returning a state after the requested end time. For state-dependent acceleration, evaluate acceleration from the state required by the documented method.

Step size controls more than smoothness

A small step usually improves a consistent stable method in a smooth problem, but it also increases work. Halving the step approximately doubles the number of updates over the same duration. The observed error should be measured against an analytic answer or an independently refined reference.

For forward Euler under constant acceleration, the global position error over a fixed duration is proportional to \(\Delta t\). The plot may look smooth even when the error is large, because the renderer can connect incorrect samples with smooth line segments. Visual smoothness is not convergence.

Extremely small steps are not an unlimited cure. More operations accumulate more floating-point rounding, and some problems need a different method because their time scales differ greatly. A refinement table should show step size, number of steps, reported quantity, and error at the same physical time.

Between-sample motion is unknown without a rule

Plotting software often joins samples with straight lines. That is linear interpolation, an additional assumption. A constant-acceleration trajectory is curved, so the line between two exact endpoint samples is not the exact intermediate path.

Different continuous motions can pass through exactly the same finite sample points. Samples alone therefore cannot uniquely reconstruct arbitrary between-sample behavior. Reconstruction needs assumptions about smoothness, frequency content, or the governing equation.

For a position array, a linear interpolator can be stated explicitly:

\[x(t)\approx x_n+\frac{t-t_n}{t_{n+1}-t_n}(x_{n+1}-x_n)\]

This preserves endpoint positions but generally creates velocity jumps at sample boundaries. If velocity continuity matters, use a suitable interpolation method and state what additional data it uses.

Fast motion can disappear between samples

Suppose an object oscillates as

\[x(t)=A\cos(2\pi ft)\]

If samples are too widely spaced, a high-frequency motion can appear slower, stationary, or reversed. This aliasing is not fixed by drawing more pixels between the same samples. The sampling rate must be high enough for the motion's relevant frequency content, and real measurements often need filtering before sampling.

Even nonperiodic motion can hide brief events. A collision that begins and ends between two sample times may leave no recorded contact state. Event-driven methods locate a crossing within a step rather than discovering it only after penetration has occurred.

Boundaries and events need special handling

If an object reaches a wall during a step, clamping its final position to the wall loses the impact time and the remaining fraction of the step. A better event calculation finds when the continuous path reaches the boundary, applies the collision rule there, and advances the remaining time with the post-impact state.

The same issue occurs when velocity crosses zero, a switch changes force, or a phase of piecewise motion ends. The event time rarely equals an existing sample time. Recording the event explicitly avoids making its timing depend entirely on the arbitrary grid.

Discrete data from sensors

Measured samples add uncertainty, finite resolution, clock error, and noise. Numerical differentiation of position can amplify sample noise, while numerical integration of velocity can accumulate bias. Reducing an algorithmic step cannot create measurements between the times a sensor actually recorded.

Irregular timestamps require formulas that use the actual intervals. Sorting by time, handling duplicates, identifying gaps, and preserving units are part of preparing the data. Resampling onto a regular grid changes the data through an interpolation or filtering rule and should be recorded as a derived product.

Evidence for a discrete representation

A credible calculation reports the continuous model, the numerical method, step or sample interval, event policy, interpolation rule, and error comparison. Useful checks include:

The time grid is a computational choice, not a hidden clock inside the physical object. Keeping that distinction visible prevents a discrete approximation from being mistaken for the continuous law it is intended to represent.

A worked Python notebook

Sample a smooth oscillation at selected times and compare samples with the continuous curve. The question for this calculation is precise: how does position change when we change sample time, 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.

Sampling a known function does not introduce the integration error of a time-stepping solver. 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 3 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 sample time, 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) = \sin{\left(2 q \right)}\]

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 s, the expression gives 0.909297 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("sin(2*q)", locals={"q": q})
reference_input = 1.0
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 0 m. The midpoint, at 1.5 s, gives 0.14112 m. The upper endpoint gives -0.279415 m. Read these together with the assumptions: they describe different choices of sample time 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, 1.5, 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} 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 sample time; 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, 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("Sample time (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 1 s is -0.832294 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) = 2 \cos{\left(2 q \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 = 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 s. The tangent estimate is 0.896813 m, while the full expression gives 0.896406 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 = 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.

Change the example and preserve the reasoning

Make one copy of the reference calculation before editing it. Choose a second value of sample time 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: Sampling a known function does not introduce the integration error of a time-stepping solver. 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(3.0) - evaluate(0.0))
for points in [101, 201, 401]:
    grid = np.linspace(0.0, 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.

Sources


Share to: