A Byte of PhysicsLogo

Numerical Ethics

Numerical work becomes evidence when other people use its output to understand a system or make a decision. Ethical practice therefore begins before calculation. It includes choosing an appropriate model, preserving data provenance, showing uncertainty, testing software, avoiding misleading presentation, and preventing a teaching model from being mistaken for a validated predictive tool.

An ethical result is not merely a correct floating-point number. It is a claim whose origin, scope, uncertainty, and limitations can be inspected. Reproducibility helps reveal mistakes, but reproducibility alone is not sufficient: code can reproduce a biased dataset or an inappropriate equation perfectly.

State the purpose and consequence

Begin by asking what question the calculation answers and what someone could do with the result. The validation required for a classroom illustration is different from that required for structural design, radiation safety, medical treatment, or environmental policy. Higher-consequence use demands qualified domain review, stronger evidence, documented uncertainty, and often compliance with standards beyond an introductory physics course.

A scope statement should identify:

Do not broaden a claim simply because software makes it easy to run the same equation on new inputs. Extrapolation beyond tested conditions is a new claim and requires new validation.

Preserve provenance

Provenance is the history needed to trace a result. Record where measurements and constants came from, how data were cleaned or transformed, which values were excluded, and which code and configuration produced the output. Preserve licences and attribution for externally supplied data and text.

result = {
    "value": 1.428,
    "unit": "s",
    "input_height_m": 10.0,
    "input_source": "illustrative, not measured",
    "assumptions": ["release from rest", "uniform g=9.81 m/s^2", "no drag"],
    "method": "sqrt(2h/g)",
    "validation": "substituted into h=gt^2/2",
}
print(result)

This record does not guarantee responsible use, but it makes silent substitution harder. If a constant changes between editions of a reference, or a dataset is corrected, the affected results can be located and regenerated.

Keep raw observations separate from processed data. Processing scripts should be versioned, and irreversible manual edits should be avoided. When privacy, safety, or legal obligations restrict access to raw data, document the restriction and provide the strongest safe audit trail available rather than pretending the input is fully open.

Units and significant figures communicate meaning

Writing units beside inputs and outputs prevents category errors and lets a reader check dimensions. Significant figures should reflect the precision supported by the measurements and calculation, not every digit stored by the computer. If a length is known only to a millimetre, printing fifteen decimal places does not create more knowledge.

For a measured quantity, a transparent report has the form

\[q=q_{\mathrm{best}}\pm u_q\]

where \(q_{\mathrm{best}}\) is the stated estimate and \(u_q\) has a clearly explained meaning. It might be a standard uncertainty, confidence interval, credible interval, instrument resolution, or another defined measure. These are not interchangeable labels.

When independent uncertainties are small and a derived quantity

\(f(x_1,\ldots,x_n)\)

is smooth, a common first-order propagation rule is

\[u_f^2\approx\sum_i\left(\frac{\partial f}{\partial x_i}\right)^2u_{x_i}^2\]

This expression assumes uncorrelated inputs. Covariance terms are required when inputs are correlated, and nonlinear or asymmetric cases may need sampling or another method. Always state the assumptions behind an uncertainty calculation.

Separate kinds of uncertainty

Several uncertainties can coexist:

Combining all of these into one unexplained error bar conceals what further work could improve. More numerical precision does not reduce model-form uncertainty, and more random samples do not repair a biased sensor.

uncertainties = {
    "height measurement contribution_s": 0.007,
    "numerical rounding contribution_s": 0.0005,
    "drag model sensitivity_s": 0.02,
}
for source, value in uncertainties.items():
    print(source, value)
print(
    "These illustrative quantities are not automatically independent standard errors."
)

If model-form uncertainty cannot be quantified responsibly, describe it qualitatively and show sensitivity to plausible assumptions. An honest unknown is better than a fabricated precise interval.

Reproducibility and independent checks

A reproducible calculation gives another investigator enough information to run the same procedure and obtain the same result within a stated tolerance. Preserve software versions, dependencies, parameters, unit conventions, data identifiers, random seeds, and numerical settings.

Random seeds allow exact repetition of a pseudorandom sequence, but one seed is not evidence that a stochastic result is typical. Repeat the analysis with multiple independent seeds and compare distributions or summary statistics.

import numpy as np

for seed in [10, 20, 30, 40]:
    rng = np.random.default_rng(seed)
    heights = rng.normal(10.0, 0.1, 10000)
    times = np.sqrt(2 * heights / 9.81)
    print(seed, times.mean(), times.std(ddof=1))

Independent reproduction is stronger than rerunning the same code because shared bugs can survive repeated execution. Compare with an analytic limit, separately written implementation, alternative numerical method, or trustworthy measurement when possible.

Do not tune on hidden evidence

Changing parameters after inspecting every discrepancy can overfit the available data. Preserve a comparison set that was not used to select the model, or use a documented validation procedure appropriate to the amount and structure of data. Report all relevant tested configurations rather than only the successful one.

Selective reporting also occurs when inconvenient time ranges, failed runs, or outliers are removed without a predeclared rule. Exclusion can be scientifically justified, but the rule, count, and effect on the result must be visible. Never alter or discard evidence merely because it weakens the preferred conclusion.

Visual presentation can overclaim

A graph is an argument about data. Axes, scales, colour, smoothing, interpolation, and cropping change what readers notice. Ethical figures should:

Animation can make a teaching explanation engaging, but motion and smoothness may suggest that a discrete approximation is an observed continuous process. Label interpolation and numerical resolution. Since this course now prioritizes durable written explanations, no scientific claim should depend on an interactive view.

Accessibility is part of accountability

Evidence cannot be checked by readers who cannot perceive or operate its presentation. Equations need readable text alternatives, diagrams need meaningful descriptions, controls need keyboard access, and status must not depend on colour alone. Plain-language explanations should accompany difficult notation without replacing the precise equation.

Accessible Python also matters. Short lines, descriptive names, and one conceptual operation per line let readers follow the calculation on narrow screens and with magnification. Accessibility broadens the group able to find errors and challenge assumptions, strengthening rather than diluting scientific review.

Warnings must be actionable

When an input leaves a validated range, do not silently extrapolate. Stop the calculation when the result would be meaningless, or return a visible warning that names the violated condition. “Invalid input” is less useful than “mass must be positive and expressed in kilograms.”

def validate_massive_particle(mass, speed, position, validated_distance):
    if mass <= 0:
        raise ValueError("Use a positive mass in kilograms.")
    if abs(speed) >= 299792458.0:
        raise ValueError("Use a speed magnitude below c for this model.")
    return (
        "outside validated range"
        if abs(position) > validated_distance
        else "within range"
    )


print(validate_massive_particle(1.0, 20.0, 120.0, 100.0))

Warnings should travel with exported values rather than appearing only once in an interface. A screenshot or copied number can otherwise lose the very information that limits its use.

Consider misuse and dual use

Some physical calculations can be repurposed for harm. A course should explain principles accurately while avoiding unnecessary operational detail that enables dangerous activity. For high-consequence subjects, seek domain and safety review, limit capabilities to the educational purpose, and avoid presenting simplified results as instructions.

Misuse can also be mundane: a neat classroom curve may be copied into a real engineering decision. Prominent scope, conservative defaults, and explicit validation status reduce that risk. A disclaimer buried at the bottom cannot repair a design that otherwise communicates unwarranted confidence.

Review incentives and conflicts

The person building a model may benefit from a particular conclusion, a successful demo, or a deadline. Record material conflicts and invite independent review. Version history should show why assumptions or thresholds changed. Review should include subject-matter experts and, when outcomes affect people, representatives who understand the affected context.

Automated tests are valuable but cannot decide whether the modeled question is appropriate, the data collection is fair, or the result will be misunderstood. Those are scientific and human judgments that require accountable reviewers.

A responsible release record

Before publication, confirm that:

  1. the purpose, audience, and excluded uses are explicit;
  2. equations and constants are traceable to authoritative references;
  3. code reproduces known cases and numerical results converge;
  4. input data, transformations, licences, and exclusions are documented;
  5. units, uncertainties, assumptions, and validity ranges accompany results;
  6. figures distinguish calculation from observation and avoid false precision;
  7. equations and conclusions remain understandable without interaction or colour;
  8. failures and negative results are preserved;
  9. foreseeable harmful or high-consequence use has been reviewed;
  10. another reader can reproduce the result or understand why access is limited.

The final question is not “Can this number be computed?” It is “What claim does this number support, for whom, under which assumptions, and with what possible consequences?” Responsible numerical physics keeps the answer attached to the calculation from first input to final citation.

A worked Python notebook

Propagate a small height uncertainty around a ten metre fall without hiding it in extra printed digits. The question for this calculation is precise: how does first-order fall-time uncertainty change when we change height uncertainty, 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.

This covers one measurement contribution; numerical error and omitted drag must be reported separately. Keep that sentence beside the results. A formula can return a number outside its useful range, and a plotting library will usually draw that number without asking whether the physical assumptions still hold. The selected interval is from 0 to 0.5 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 uncertainty, expressed in m. The output is first-order fall-time uncertainty, expressed in s. 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) = 0.0713921561463532 q\]

This is a function of one changing input. It is not a statement that the physical system has only one variable. We deliberately hold the other inputs fixed so that one cause of variation is visible. Changing several inputs at once would make it harder to tell which change produced the output difference. Write down the held-fixed choices before trying a different experiment.

At 0.1 m, the expression gives 0.00713922 s. 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/(9.81*sqrt(20/9.81))", locals={"q": q})
reference_input = 0.1
reference_output = float(expression.subs(q, reference_input))
print("Input:", reference_input, "m")
print("Predicted first-order fall-time uncertainty:", reference_output, "s")

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 s. The midpoint, at 0.25 m, gives 0.017848 s. The upper endpoint gives 0.0356961 s. Read these together with the assumptions: they describe different choices of height uncertainty within the same example, with the other inputs held fixed.

These three values are a useful first check, but they do not establish the shape between them. Two endpoints can be equal even when the curve bends or oscillates in between. Likewise, a large change between endpoints does not tell us whether the relationship is linear. We need the equation and intermediate samples to answer those questions.

evaluate = sp.lambdify(q, expression, modules="numpy")
inputs = np.array([0.0, 0.25, 0.5])
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} s")
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 uncertainty; the vertical axis shows first-order fall-time uncertainty. Every plotted point is a prediction of the same expression. We mark the reference case separately so that a reader can connect the earlier printed value to its place on the curve. The axis labels include units because a shape without a scale cannot tell us the size of a physical effect.

input_grid = np.linspace(0.0, 0.5, 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 uncertainty (m)")
ax.set_ylabel("First-order fall-time uncertainty (s)")
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 first-order fall-time uncertainty change near the reference input? Its units are the output unit divided by the input unit. For this calculation, the derivative at 0.1 m is 0.0713922 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) = 0.0713921561463532\]

For a small input change, multiply the derivative by that change to estimate the output change. Then compare that estimate with a fresh evaluation of the full expression. The distinction between these two calculations matters: the derivative gives a tangent approximation, while substitution evaluates the chosen expression at the new point.

slope_expression = sp.diff(expression, q)
slope_at_reference = float(slope_expression.subs(q, reference_input))
changed_input = 0.10250000000000001
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, "s")
print("Full expression:", full_prediction, "s")
print("Approximation difference:", full_prediction - linear_prediction, "s")

Here the changed input is 0.1025 m. The tangent estimate is 0.0073177 s, while the full expression gives 0.0073177 s. If the two values are close, it means the chosen input change is small enough for this local approximation at this point. It does not mean the entire model is linear. If the slope is zero, a quadratic or higher-order term may supply the leading change instead.

This is also the beginning of uncertainty propagation. If the input has a small stated standard uncertainty, the magnitude of the slope times that uncertainty estimates one contribution to output uncertainty. Do not automatically use the same rule for a wide interval, a discontinuity, a turning point with zero first derivative, or several correlated uncertain inputs. Those situations need more of the model than one slope.

Check the derivative with numerical differences

We can estimate the same slope from values on either side of the reference point. Subtract the lower output from the upper output and divide by twice the input step. Parentheses are essential: the entire output difference must be divided by the entire input interval. Without them, Python can execute a different mathematical expression while still producing a plausible number.

The calculation below uses three decreasing step sizes. Each estimate is compared with the symbolic derivative, so the reference is independent of the numerical difference formula. Near an endpoint, it is acceptable here to evaluate a small extension only because the displayed mathematical expression is smooth there; such a check does not assert that extrapolated values describe additional physical cases.

input_span = 0.5
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 uncertainty inside the stated interval, predict whether first-order fall-time uncertainty 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: This covers one measurement contribution; numerical error and omitted drag must be reported separately. 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 s: the input unit in the integration cancels the input unit in the denominator of the slope.

This statement is about the mathematics of this particular relationship. It does not assign a new physical meaning to an arbitrary area under a graph. For example, an area under force versus distance represents work, while an area under a different pair of quantities may represent something else or have no standard name. Always carry the axis units through the calculation before naming an integral.

slope_function = sp.lambdify(q, slope_expression, modules="numpy")
endpoint_change = float(evaluate(0.5) - evaluate(0.0))
for points in [101, 201, 401]:
    grid = np.linspace(0.0, 0.5, 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: