A rule for acceleration does not determine one unique motion by itself. The same acceleration can describe objects that start in different places or with different velocities. Initial conditions select one trajectory from the family allowed by the equation.
In one dimension, acceleration is the second derivative of position:
\[\frac{\mathrm{d}^2x}{\mathrm{d}t^2}=a(t,x,v)\]Integrating once introduces a constant that is fixed by velocity at an initial time. Integrating again introduces another constant fixed by position. The initial state is therefore
\[x(t_0)=x_0,\qquad v(t_0)=v_0\]The reference time \(t_0\) is part of the definition. Setting it to zero is convenient but not required.
For constant acceleration, integration gives
\[v(t)=v_0+a(t-t_0)\]and
\[x(t)=x_0+v_0(t-t_0)+\frac{1}{2}a(t-t_0)^2\]Writing elapsed time as \(t-t_0\) prevents a clock reading from being mistaken for the duration of motion.
from dataclasses import dataclass
@dataclass(frozen=True)
class MotionState:
time_seconds: float
position_metres: float
velocity_metres_per_second: float
def state_at_constant_acceleration(
initial: MotionState,
acceleration_metres_per_second_squared: float,
requested_time_seconds: float,
) -> MotionState:
elapsed_time_seconds = requested_time_seconds - initial.time_seconds
velocity_metres_per_second = (
initial.velocity_metres_per_second
+ acceleration_metres_per_second_squared * elapsed_time_seconds
)
position_metres = (
initial.position_metres
+ initial.velocity_metres_per_second * elapsed_time_seconds
+ 0.5 * acceleration_metres_per_second_squared * elapsed_time_seconds**2
)
return MotionState(
time_seconds=requested_time_seconds,
position_metres=position_metres,
velocity_metres_per_second=velocity_metres_per_second,
)
The returned position and velocity are derived values. The function should not mutate the supplied initial record; later evaluations must continue to refer to the same initial event.
The corresponding Python keeps each physical step visible:
initial = MotionState(
time_seconds=1.0,
position_metres=2.0,
velocity_metres_per_second=3.0,
)
result = state_at_constant_acceleration(initial, 0.5, 5.0)
print(result)
assert result.position_metres == 18.0
assert result.velocity_metres_per_second == 5.0
At clock time \(t_0=3.0\,\mathrm{s}\), a cart is at \(x_0=5.0\,\mathrm{m}\) and moving right at \(v_0=12.0\,\mathrm{m/s}\). It then has constant acceleration \(a=-2.0\,\mathrm{m/s^2}\).
At clock time \(t=7.0\,\mathrm{s}\), the elapsed time is \(4.0\,\mathrm{s}\). The velocity is
\[v=12.0+(-2.0)(4.0)=4.0\,\mathrm{m/s}\]and the position is
\[x=5.0+(12.0)(4.0)+\frac{1}{2}(-2.0)(4.0)^2=37.0\,\mathrm{m}\]The negative acceleration reduces a positive velocity, so the cart is slowing during this interval. Negative acceleration alone does not mean motion in the negative direction.
The cart reaches zero velocity when
\[0=v_0+a\Delta t\quad\Rightarrow\quad\Delta t=-\frac{v_0}{a}=6.0\,\mathrm{s}\]Its stopping position is
\[x_{\mathrm{stop}}=5.0+(12.0)(6.0)+\frac{1}{2}(-2.0)(6.0)^2=41.0\,\mathrm{m}\]If the constant-acceleration formula is evaluated after that event, it predicts negative velocity and motion back to the left. That is mathematically correct for constant negative acceleration, but it may not represent a real braking system that stops applying force once the cart rests. Initial conditions do not specify future control changes; the model needs a piecewise force or acceleration rule for that behavior.
Initial position and velocity describe the selected trajectory at one event. Parameters such as a drag coefficient or spring stiffness describe the model's rule. Constant acceleration is a parameter in the closed-form example, although a more general solver might compute acceleration from state and parameters.
Changing the initial position shifts the trajectory without changing its velocity or acceleration. Changing the initial velocity changes both the position slope and future velocity. Changing acceleration changes the rule itself. Keeping these categories separate helps parameter sweeps and uncertainty analyses say what was varied.
For state-dependent acceleration, the equations can be rewritten as two first-order equations:
\[\frac{\mathrm{d}x}{\mathrm{d}t}=v,\qquad\frac{\mathrm{d}v}{\mathrm{d}t}=a(t,x,v)\]A numerical integrator begins with the complete initial state and advances it. Omitting initial velocity leaves the first update underdetermined. Guessing zero is an extra assumption that must be explicit.
time_s, position_m, velocity_m_per_s = 1.0, 2.0, 3.0
dt_s = 0.01
for step in range(400):
acceleration = 0.5
position_m += velocity_m_per_s * dt_s
velocity_m_per_s += acceleration * dt_s
time_s += dt_s
print(f"Numerical position: {position_m:.3f} m")
print(f"Numerical velocity: {velocity_m_per_s:.3f} m/s")
The step size and integrator determine numerical error. The initial-state uncertainty also propagates through the trajectory, and in sensitive systems nearby initial states may diverge rapidly.
An initial-value problem supplies all required state at one time and predicts evolution. A boundary-value problem may specify information at different positions or times, such as the endpoints of a hanging cable. Solving it often requires finding an initial state that satisfies the later boundary.
The distinction matters in code. Passing an endpoint target to an initial-value integrator does not guarantee that the trajectory reaches it. A shooting method, root finder, or other boundary-value algorithm may be needed.
Every solver should reproduce its initial state at the initial time. For the analytic function, substituting \(t=t_0\) must return \(x=x_0\) and \(v=v_0\).
Additional checks include dimensional consistency, comparison of derivatives, known event times, and invariance under a shift of clock origin. Adding the same constant to both initial and requested clock times must leave the predicted position and velocity unchanged because elapsed time is unchanged.
Finally, state the domain. A function can numerically extrapolate before the initial event or beyond a collision, control change, or model limit. Being able to compute a number does not make that number a supported physical prediction.
In an experiment, the initial state is not normally known as an exact pair of numbers. Position may be limited by image resolution, velocity may be estimated from several frames, and the two estimates may be correlated. Starting a solver from only their central values produces one representative trajectory but does not show how uncertainty spreads through later predictions.
One approach is to sample plausible initial states from a stated joint distribution and solve the same model for each sample. Another is to propagate a covariance matrix with a linearized model. Either approach must preserve units, correlations, and the time at which the measurements define the state. Treating position measured at one instant and velocity measured over a later interval as simultaneous can introduce a hidden timing error.
For stable linear motion, nearby initial states remain predictably related. In nonlinear or chaotic systems, small differences may grow quickly. That growth is a property of the model's dynamics and time horizon; it is not fixed by printing more digits in the initial record. Report the initial uncertainty and sensitivity beside the later prediction.
State must contain the information required to continue the model. For a particle whose acceleration depends on position and velocity, both are needed. Storing acceleration as independent state is unnecessary when it can be calculated from current time, position, velocity, and parameters. Duplicating derived values creates opportunities for them to become inconsistent.
Some models require more state. A force with memory may need internal material variables; a controller may need its own mode and accumulated error; a rocket may need changing mass. The order of the differential equations indicates how many independent conditions are required, while the physical model determines what those conditions mean.
Do not add a state variable merely because it is convenient to display. Outputs such as kinetic energy can be derived from the current physical state. Keep display rounding out of state as well, so each update begins from the best available internal values.
Sometimes a long trajectory is restarted from a later computed event. The new initial record must copy position and velocity from the same time and preserve model parameters and units. If the earlier state is numerical, the restart also inherits its accumulated error. It is not equivalent to receiving a new exact measurement.
A useful check evaluates the original solution and the rebased solution at matching later times. For a time-invariant constant-acceleration model, they should agree within floating-point tolerance. Disagreement can reveal a clock-origin error, lost state, or incorrect use of elapsed time.
Start from a position of 2 metres and velocity of 3 metres per second, then accelerate uniformly. The question for this calculation is precise: how does position change when we change elapsed 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.
Elapsed time is measured from the specified initial event, not from an arbitrary clock origin. 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 4 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.
In this small example, q stands for elapsed 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.
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 s, the expression gives 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("2+3*q+q**2/4", locals={"q": q})
reference_input = 2.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.
Before drawing hundreds of points, calculate three. The lower endpoint gives 2 m. The midpoint, at 2 s, gives 9 m. The upper endpoint gives 18 m. Read these together with the assumptions: they describe different choices of elapsed 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, 2.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} 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.
The horizontal axis shows elapsed 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, 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("Elapsed 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.
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 2 s is 4 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} + 3\]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.02
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 2.02 s. The tangent estimate is 9.08 m, while the full expression gives 9.0801 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 = 4.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 elapsed 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: Elapsed time is measured from the specified initial event, not from an arbitrary clock origin. 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(4.0) - evaluate(0.0))
for points in [101, 201, 401]:
grid = np.linspace(0.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.