A Byte of PhysicsLogo

When Models Fail

A mismatch between a prediction and reality does not have one universal cause. The equation may have been copied incorrectly, the code may solve a different equation, the numerical method may be inaccurate or unstable, an input may have the wrong unit, the measurements may be biased, or the physical approximation may omit an important interaction. Scientific debugging means distinguishing these cases rather than adjusting parameters until a graph looks convincing.

Failure is useful evidence when it is preserved and classified. It tells us which claim did not survive a test and what kind of refinement is needed. Hiding a failure with smoothing, an undocumented correction factor, or a wider plotting scale discards the most informative part of the investigation.

Define what “failure” means

A model cannot pass or fail without a stated purpose and tolerance. An error of one millimetre may be irrelevant in an astronomical estimate and unacceptable in a precision instrument. Before comparing values, specify:

For a reference value \(q_{\mathrm{ref}}\) and a prediction \(q_{\mathrm{model}}\), the absolute discrepancy is

\[\Delta q=q_{\mathrm{model}}-q_{\mathrm{ref}}\]

and, when the reference is not zero, a useful relative measure is

\[\epsilon_{\mathrm{rel}}=\frac{|q_{\mathrm{model}}-q_{\mathrm{ref}}|}{|q_{\mathrm{ref}}|}\]

Relative error is undefined when the denominator is zero and can be misleading when it is merely close to zero. In those cases, use an absolute tolerance tied to the physical scale or combine absolute and relative criteria.

import numpy as np

prediction, reference = 9.9, 10.0
absolute_error = abs(prediction - reference)
allowed = 0.01 + 0.02 * abs(reference)
print("Within the declared error allowance:", absolute_error <= allowed)

The tolerance must be chosen before seeing the answer when possible. Moving it afterward to make a result pass is not validation.

First check the question and definitions

Many apparent physics failures are comparison failures. One source may report speed while another reports one component of velocity. One energy value may include rest energy while another reports only kinetic energy. A thermodynamics reference may define work done by the gas as positive while an implementation defines work done on the gas as positive.

Rewrite both results using the same definitions before diagnosing deeper causes. Check the system boundary, sign convention, coordinate origin, reference frame, zero of potential energy, and time at which the quantity is evaluated. A model cannot agree with a reference answer to a different problem.

Check algebra and dimensions

Return to the governing relationship before inspecting code. Confirm every rearrangement, exponent, sign, vector direction, and constant. Then check dimensions. For example, in

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

all terms have dimensions of length. If a term instead contains \(at\), it has dimensions of speed and cannot be added to position. Dimensional consistency does not prove the formula, but dimensional inconsistency proves something is wrong.

Order-of-magnitude reasoning is another early filter. If a walking-speed input produces an interplanetary distance in one second, inspect powers of ten and unit conversion before debating subtle physical effects.

Verify the implementation

Verification tests whether the program follows the stated mathematical model. Useful tests isolate small pieces: a known analytic solution, a zero-input case, a symmetry, a derivative checked by finite differences, or a conserved quantity in a system where conservation applies.

def fall_distance(steps):
    distance, velocity, dt = 0.0, 0.0, 1.0 / steps
    for _ in range(steps):
        distance += velocity * dt
        velocity += 9.81 * dt
    return distance


expected = 0.5 * 9.81
computed = fall_distance(1000)
assert abs(computed - expected) < 0.005
print("Known-case absolute error (m):", abs(computed - expected))

A passing unit test proves only the tested behaviour. It does not establish that the mathematical model is appropriate for a new regime. Tests should include boundaries and invalid inputs, not only a convenient central example.

Common implementation failures include updating state in the wrong order, mutating an input that should remain fixed, mixing degrees and radians, using integer division, losing a minus sign, comparing floating-point values for exact equality, and reading rounded display output back into a calculation.

Separate numerical error from physical error

A numerical method replaces continuous mathematics with finite steps, samples, or precision. Its result can fail even when the differential equation is correct. If a method has error proportional to a power of the step size,

\[E(h)\approx C h^p\]

then \(h\) is the resolution, \(p\) is the method's order, and \(C\) depends on the problem. Halving the step should reduce the leading error by approximately

\(2^p\)

once the calculation is in the asymptotic convergence range.

coarse, medium, fine = [fall_distance(n) for n in [100, 200, 400]]
coarse_change, fine_change = abs(coarse - medium), abs(medium - fine)
assert fine_change < coarse_change
print("Successive differences (m):", coarse_change, fine_change)
print("This convergence test does not establish that air drag is negligible.")

Three resolutions reveal more than two because they show whether changes are decreasing systematically. Convergence toward a stable number does not guarantee physical truth: the program may be converging accurately to the solution of an inappropriate equation.

Instability is not new physics

Some algorithms magnify small numerical errors. An explicit update may oscillate or grow without bound when its step exceeds a stability limit. A visually dramatic result is then a property of the discretization, not evidence of an explosive physical process.

Stability limits depend on the equation and method. They must be derived or taken from a trustworthy numerical analysis, expressed with consistent units, and checked before calculation. Reducing a step until a plot looks smooth is not enough; demonstrate convergence of quantities that matter.

Round-off can dominate at the opposite extreme. Subtracting nearly equal large numbers loses significant digits, and taking excessively small finite-difference steps can make round-off worse even while truncation error improves. Resolution studies should therefore look for a range in which the result stabilizes, not assume smaller is always better.

Inspect inputs and data provenance

Correct code with correct equations still fails when its inputs do not represent the intended system. Check units at the data boundary, missing-value handling, timestamps, sensor calibration, coordinate transformations, sample selection, and whether constants match the reference version.

Measured data contain uncertainty. If the model-reference discrepancy is smaller than the combined uncertainty, the data may not distinguish the model from the reference. If residuals show a systematic pattern rather than random scatter, a missing mechanism or calibration problem may be present.

For observations \(y_i\) and predictions \(f_i\), residuals are

\[r_i=y_i-f_i\]

A single summary number can hide structure. Plot or tabulate residuals against time, position, and relevant inputs. A curve in residuals, a change in spread, or clusters by instrument may identify the source of failure.

Decide whether the physical approximation has failed

Only after verifying definitions, equations, code, numerics, and inputs should we attribute the mismatch to the physical model. Then identify a specific assumption:

The failure boundary is often gradual. Compare the neglected effect with the retained one using a dimensionless ratio. A correction that is one part in a million may be irrelevant for a classroom estimate and essential for a precision measurement.

Avoid overfitting the failure

Adding parameters can make a model follow existing data more closely without improving prediction. A flexible model may fit measurement noise. Preserve data that were not used to choose parameters and evaluate the revised model on that independent set. Prefer a physically motivated correction over an unexplained factor inserted only to erase residuals.

If several models fit within measurement uncertainty, report that the evidence does not distinguish them. Scientific honesty permits an inconclusive result. Selecting the most complicated explanation is not progress when the data cannot test its extra claims.

A disciplined failure report

A useful report makes the investigation reproducible:

  1. State the expected and observed quantities with units and uncertainty.
  2. Give the signed discrepancy and the predeclared acceptance criterion.
  3. Confirm aligned definitions, frames, conventions, and system boundaries.
  4. List implementation tests and their results.
  5. Show numerical convergence or explain why it is unavailable.
  6. Record data sources, versions, transformations, and exclusions.
  7. Identify the assumption most directly challenged by the remaining evidence.
  8. Propose a focused next test that could distinguish competing explanations.

Do not silently delete failed runs. Store enough configuration, software version, random seed, and diagnostic output to reproduce them. A clear failure report is more valuable than a polished success whose assumptions cannot be recovered.

The aim is not to make every model agree forever. A model earns trust by succeeding inside a documented domain, failing visibly outside it, and making the reason for revision inspectable. That cycle is how simplified laws become reliable tools without being mistaken for complete descriptions of nature.

A worked Python notebook

Quantify the departure from uniform gravity as height becomes a significant fraction of Earth's radius. The question for this calculation is precise: how does inverse-square gravity relative to surface gravity change when we change height above Earth surface, 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.

Earth is treated as spherical; this isolates height dependence from rotation and local mass variation. 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 1e+06 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.

State the relationship before choosing a graph

In this small example, q stands for height above Earth surface, expressed in m. The output is inverse-square gravity relative to surface gravity, expressed in dimensionless. 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{40589641000000.0}{\left(q + 6371000.0\right)^{2}}\]

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 100000 m, the expression gives 0.969332 dimensionless. 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("(6.371e6/(6.371e6+q))**2", locals={"q": q})
reference_input = 100000.0
reference_output = float(expression.subs(q, reference_input))
print("Input:", reference_input, "m")
print(
    "Predicted inverse-square gravity relative to surface gravity:",
    reference_output,
    "dimensionless",
)

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 dimensionless. The midpoint, at 500000 m, gives 0.859756 dimensionless. The upper endpoint gives 0.747072 dimensionless. Read these together with the assumptions: they describe different choices of height above Earth surface 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, 500000.0, 1000000.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} m -> {output_value:.6g} dimensionless")
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 height above Earth surface; the vertical axis shows inverse-square gravity relative to surface gravity. 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, 1000000.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("Height above earth surface (m)")
ax.set_ylabel("Inverse-square gravity relative to surface gravity (dimensionless)")
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 inverse-square gravity relative to surface gravity change near the reference input? Its units are the output unit divided by the input unit. For this calculation, the derivative at 100000 m is -2.99593e-07 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{81179282000000.0}{\left(q + 6371000.0\right)^{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 = 105000.0
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, "dimensionless")
print("Full expression:", full_prediction, "dimensionless")
print("Approximation difference:", full_prediction - linear_prediction, "dimensionless")

Here the changed input is 105000 m. The tangent estimate is 0.967834 dimensionless, while the full expression gives 0.967835 dimensionless. 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 = 1000000.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 height above Earth surface inside the stated interval, predict whether inverse-square gravity relative to surface gravity 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: Earth is treated as spherical; this isolates height dependence from rotation and local mass variation. 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 dimensionless: 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(1000000.0) - evaluate(0.0))
for points in [101, 201, 401]:
    grid = np.linspace(0.0, 1000000.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: