{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "markdown-000",
      "metadata": {},
      "source": [
        "# Numerical Ethics\n",
        "\n",
        "[Read the lesson](https://tirta.co/a-byte-of-physics/numerical-ethics). This notebook includes the lesson text and its Python examples in reading order. Run the setup cell, then run the remaining cells from top to bottom. In Colab, use File → Save a copy in Drive to keep your edits. You can run and edit this view without changing the course source. Examples use illustrative data unless stated otherwise."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-001",
      "metadata": {},
      "source": [
        "import importlib.metadata\n",
        "import subprocess\n",
        "import sys\n",
        "\n",
        "requirements = {\"numpy\": (2, 0), \"sympy\": (1, 13), \"matplotlib\": (3, 8)}\n",
        "to_install = []\n",
        "for package, minimum in requirements.items():\n",
        "    try:\n",
        "        installed = importlib.metadata.version(package)\n",
        "        version = tuple(int(part) for part in installed.split(\".\")[:2])\n",
        "    except importlib.metadata.PackageNotFoundError:\n",
        "        version = (0, 0)\n",
        "    if version < minimum:\n",
        "        to_install.append(f\"{package}>={minimum[0]}.{minimum[1]}\")\n",
        "if to_install:\n",
        "    subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", *to_install])\n",
        "\n",
        "import numpy as np\n",
        "import sympy as sp\n",
        "import matplotlib\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "print(\"Python\", sys.version.split()[0])\n",
        "print(\"NumPy\", np.__version__)\n",
        "print(\"SymPy\", sp.__version__)\n",
        "print(\"Matplotlib\", matplotlib.__version__)\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-002",
      "metadata": {},
      "source": [
        "Numerical work becomes evidence when other people use its output to understand a\n",
        "system or make a decision. Ethical practice therefore begins before calculation.\n",
        "It includes choosing an appropriate model, preserving data provenance, showing\n",
        "uncertainty, testing software, avoiding misleading presentation, and preventing a\n",
        "teaching model from being mistaken for a validated predictive tool.\n",
        "\n",
        "An ethical result is not merely a correct floating-point number. It is a claim\n",
        "whose origin, scope, uncertainty, and limitations can be inspected. Reproducibility\n",
        "helps reveal mistakes, but reproducibility alone is not sufficient: code can\n",
        "reproduce a biased dataset or an inappropriate equation perfectly.\n",
        "\n",
        "## State the purpose and consequence\n",
        "\n",
        "Begin by asking what question the calculation answers and what someone could do\n",
        "with the result. The validation required for a classroom illustration is different\n",
        "from that required for structural design, radiation safety, medical treatment, or\n",
        "environmental policy. Higher-consequence use demands qualified domain review,\n",
        "stronger evidence, documented uncertainty, and often compliance with standards\n",
        "beyond an introductory physics course.\n",
        "\n",
        "A scope statement should identify:\n",
        "\n",
        "- intended and excluded uses;\n",
        "- the physical system, population, place, and time represented;\n",
        "- who may be affected by a wrong prediction;\n",
        "- inputs and outputs, with units and definitions;\n",
        "- assumptions and known failure conditions;\n",
        "- the evidence used for verification and validation;\n",
        "- a person or process responsible for reviewing changes.\n",
        "\n",
        "Do not broaden a claim simply because software makes it easy to run the same\n",
        "equation on new inputs. Extrapolation beyond tested conditions is a new claim and\n",
        "requires new validation.\n",
        "\n",
        "## Preserve provenance\n",
        "\n",
        "Provenance is the history needed to trace a result. Record where measurements and\n",
        "constants came from, how data were cleaned or transformed, which values were\n",
        "excluded, and which code and configuration produced the output. Preserve licences\n",
        "and attribution for externally supplied data and text."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-003",
      "metadata": {},
      "source": [
        "result = {\n",
        "    \"value\": 1.428,\n",
        "    \"unit\": \"s\",\n",
        "    \"input_height_m\": 10.0,\n",
        "    \"input_source\": \"illustrative, not measured\",\n",
        "    \"assumptions\": [\"release from rest\", \"uniform g=9.81 m/s^2\", \"no drag\"],\n",
        "    \"method\": \"sqrt(2h/g)\",\n",
        "    \"validation\": \"substituted into h=gt^2/2\",\n",
        "}\n",
        "print(result)\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-004",
      "metadata": {},
      "source": [
        "This record does not guarantee responsible use, but it makes silent substitution\n",
        "harder. If a constant changes between editions of a reference, or a dataset is\n",
        "corrected, the affected results can be located and regenerated.\n",
        "\n",
        "Keep raw observations separate from processed data. Processing scripts should be\n",
        "versioned, and irreversible manual edits should be avoided. When privacy, safety,\n",
        "or legal obligations restrict access to raw data, document the restriction and\n",
        "provide the strongest safe audit trail available rather than pretending the input\n",
        "is fully open.\n",
        "\n",
        "## Units and significant figures communicate meaning\n",
        "\n",
        "Writing units beside inputs and outputs prevents category errors and lets a reader\n",
        "check dimensions. Significant figures should reflect the precision supported by\n",
        "the measurements and calculation, not every digit stored by the computer. If a\n",
        "length is known only to a millimetre, printing fifteen decimal places does not\n",
        "create more knowledge.\n",
        "\n",
        "For a measured quantity, a transparent report has the form\n",
        "\n",
        "\n",
        "$$\n",
        "q=q_{\\mathrm{best}}\\pm u_q\n",
        "$$\n",
        "\n",
        "\n",
        "where $q_{\\mathrm{best}}$\n",
        "is the stated estimate and $u_q$\n",
        "has a clearly explained meaning. It might be a standard uncertainty, confidence\n",
        "interval, credible interval, instrument resolution, or another defined measure.\n",
        "These are not interchangeable labels.\n",
        "\n",
        "When independent uncertainties are small and a derived quantity\n",
        "$f(x_1,\\ldots,x_n)$\n",
        "is smooth, a common first-order propagation rule is\n",
        "\n",
        "\n",
        "$$\n",
        "u_f^2\\approx\\sum_i\\left(\\frac{\\partial f}{\\partial x_i}\\right)^2u_{x_i}^2\n",
        "$$\n",
        "\n",
        "\n",
        "This expression assumes uncorrelated inputs. Covariance terms are required when\n",
        "inputs are correlated, and nonlinear or asymmetric cases may need sampling or\n",
        "another method. Always state the assumptions behind an uncertainty calculation.\n",
        "\n",
        "## Separate kinds of uncertainty\n",
        "\n",
        "Several uncertainties can coexist:\n",
        "\n",
        "- **Measurement uncertainty** comes from instrument resolution, calibration,\n",
        "  sampling, environmental variation, and other observation limits.\n",
        "- **Parameter uncertainty** reflects imperfect knowledge of model inputs.\n",
        "- **Numerical error** comes from finite steps, grids, samples, and precision.\n",
        "- **Model-form uncertainty** comes from simplified or omitted physics.\n",
        "- **Statistical sampling uncertainty** comes from estimating population behaviour\n",
        "  with finite observations or random draws.\n",
        "\n",
        "Combining all of these into one unexplained error bar conceals what further work\n",
        "could improve. More numerical precision does not reduce model-form uncertainty,\n",
        "and more random samples do not repair a biased sensor."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-005",
      "metadata": {},
      "source": [
        "uncertainties = {\n",
        "    \"height measurement contribution_s\": 0.007,\n",
        "    \"numerical rounding contribution_s\": 0.0005,\n",
        "    \"drag model sensitivity_s\": 0.02,\n",
        "}\n",
        "for source, value in uncertainties.items():\n",
        "    print(source, value)\n",
        "print(\n",
        "    \"These illustrative quantities are not automatically independent standard errors.\"\n",
        ")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-006",
      "metadata": {},
      "source": [
        "If model-form uncertainty cannot be quantified responsibly, describe it\n",
        "qualitatively and show sensitivity to plausible assumptions. An honest unknown is\n",
        "better than a fabricated precise interval.\n",
        "\n",
        "## Reproducibility and independent checks\n",
        "\n",
        "A reproducible calculation gives another investigator enough information to run\n",
        "the same procedure and obtain the same result within a stated tolerance. Preserve\n",
        "software versions, dependencies, parameters, unit conventions, data identifiers,\n",
        "random seeds, and numerical settings.\n",
        "\n",
        "Random seeds allow exact repetition of a pseudorandom sequence, but one seed is\n",
        "not evidence that a stochastic result is typical. Repeat the analysis with\n",
        "multiple independent seeds and compare distributions or summary statistics."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-007",
      "metadata": {},
      "source": [
        "import numpy as np\n",
        "\n",
        "for seed in [10, 20, 30, 40]:\n",
        "    rng = np.random.default_rng(seed)\n",
        "    heights = rng.normal(10.0, 0.1, 10000)\n",
        "    times = np.sqrt(2 * heights / 9.81)\n",
        "    print(seed, times.mean(), times.std(ddof=1))\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-008",
      "metadata": {},
      "source": [
        "Independent reproduction is stronger than rerunning the same code because shared\n",
        "bugs can survive repeated execution. Compare with an analytic limit, separately\n",
        "written implementation, alternative numerical method, or trustworthy measurement\n",
        "when possible.\n",
        "\n",
        "## Do not tune on hidden evidence\n",
        "\n",
        "Changing parameters after inspecting every discrepancy can overfit the available\n",
        "data. Preserve a comparison set that was not used to select the model, or use a\n",
        "documented validation procedure appropriate to the amount and structure of data.\n",
        "Report all relevant tested configurations rather than only the successful one.\n",
        "\n",
        "Selective reporting also occurs when inconvenient time ranges, failed runs, or\n",
        "outliers are removed without a predeclared rule. Exclusion can be scientifically\n",
        "justified, but the rule, count, and effect on the result must be visible. Never\n",
        "alter or discard evidence merely because it weakens the preferred conclusion.\n",
        "\n",
        "## Visual presentation can overclaim\n",
        "\n",
        "A graph is an argument about data. Axes, scales, colour, smoothing, interpolation,\n",
        "and cropping change what readers notice. Ethical figures should:\n",
        "\n",
        "- label quantities and units;\n",
        "- distinguish observations from model predictions;\n",
        "- show uncertainty or variation when it affects interpretation;\n",
        "- disclose logarithmic axes, smoothing, normalization, and excluded values;\n",
        "- avoid truncated axes that exaggerate small differences without explanation;\n",
        "- retain sampled points when a smooth curve might imply unsupported resolution;\n",
        "- use colour schemes and text or shape cues accessible to colour-blind readers;\n",
        "- include a data table or textual values when exact inspection matters.\n",
        "\n",
        "Animation can make a teaching explanation engaging, but motion and smoothness may\n",
        "suggest that a discrete approximation is an observed continuous process. Label\n",
        "interpolation and numerical resolution. Since this course now prioritizes durable\n",
        "written explanations, no scientific claim should depend on an interactive view.\n",
        "\n",
        "## Accessibility is part of accountability\n",
        "\n",
        "Evidence cannot be checked by readers who cannot perceive or operate its\n",
        "presentation. Equations need readable text alternatives, diagrams need meaningful\n",
        "descriptions, controls need keyboard access, and status must not depend on colour\n",
        "alone. Plain-language explanations should accompany difficult notation without\n",
        "replacing the precise equation.\n",
        "\n",
        "Accessible Python also matters. Short lines, descriptive names, and one\n",
        "conceptual operation per line let readers follow the calculation on narrow screens\n",
        "and with magnification. Accessibility broadens the group able to find errors and\n",
        "challenge assumptions, strengthening rather than diluting scientific review.\n",
        "\n",
        "## Warnings must be actionable\n",
        "\n",
        "When an input leaves a validated range, do not silently extrapolate. Stop the\n",
        "calculation when the result would be meaningless, or return a visible warning that\n",
        "names the violated condition. “Invalid input” is less useful than “mass must be\n",
        "positive and expressed in kilograms.”"
      ]
    },
    {
      "cell_type": "code",
      "id": "code-009",
      "metadata": {},
      "source": [
        "def validate_massive_particle(mass, speed, position, validated_distance):\n",
        "    if mass <= 0:\n",
        "        raise ValueError(\"Use a positive mass in kilograms.\")\n",
        "    if abs(speed) >= 299792458.0:\n",
        "        raise ValueError(\"Use a speed magnitude below c for this model.\")\n",
        "    return (\n",
        "        \"outside validated range\"\n",
        "        if abs(position) > validated_distance\n",
        "        else \"within range\"\n",
        "    )\n",
        "\n",
        "\n",
        "print(validate_massive_particle(1.0, 20.0, 120.0, 100.0))\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-010",
      "metadata": {},
      "source": [
        "Warnings should travel with exported values rather than appearing only once in an\n",
        "interface. A screenshot or copied number can otherwise lose the very information\n",
        "that limits its use.\n",
        "\n",
        "## Consider misuse and dual use\n",
        "\n",
        "Some physical calculations can be repurposed for harm. A course should explain\n",
        "principles accurately while avoiding unnecessary operational detail that enables\n",
        "dangerous activity. For high-consequence subjects, seek domain and safety review,\n",
        "limit capabilities to the educational purpose, and avoid presenting simplified\n",
        "results as instructions.\n",
        "\n",
        "Misuse can also be mundane: a neat classroom curve may be copied into a real\n",
        "engineering decision. Prominent scope, conservative defaults, and explicit\n",
        "validation status reduce that risk. A disclaimer buried at the bottom cannot\n",
        "repair a design that otherwise communicates unwarranted confidence.\n",
        "\n",
        "## Review incentives and conflicts\n",
        "\n",
        "The person building a model may benefit from a particular conclusion, a successful\n",
        "demo, or a deadline. Record material conflicts and invite independent review.\n",
        "Version history should show why assumptions or thresholds changed. Review should\n",
        "include subject-matter experts and, when outcomes affect people, representatives\n",
        "who understand the affected context.\n",
        "\n",
        "Automated tests are valuable but cannot decide whether the modeled question is\n",
        "appropriate, the data collection is fair, or the result will be misunderstood.\n",
        "Those are scientific and human judgments that require accountable reviewers.\n",
        "\n",
        "## A responsible release record\n",
        "\n",
        "Before publication, confirm that:\n",
        "\n",
        "1. the purpose, audience, and excluded uses are explicit;\n",
        "2. equations and constants are traceable to authoritative references;\n",
        "3. code reproduces known cases and numerical results converge;\n",
        "4. input data, transformations, licences, and exclusions are documented;\n",
        "5. units, uncertainties, assumptions, and validity ranges accompany results;\n",
        "6. figures distinguish calculation from observation and avoid false precision;\n",
        "7. equations and conclusions remain understandable without interaction or colour;\n",
        "8. failures and negative results are preserved;\n",
        "9. foreseeable harmful or high-consequence use has been reviewed;\n",
        "10. another reader can reproduce the result or understand why access is limited.\n",
        "\n",
        "The final question is not “Can this number be computed?” It is “What claim does\n",
        "this number support, for whom, under which assumptions, and with what possible\n",
        "consequences?” Responsible numerical physics keeps the answer attached to the\n",
        "calculation from first input to final citation.\n",
        "\n",
        "## A worked Python notebook\n",
        "\n",
        "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**\n",
        "change when we change **height uncertainty**, while keeping the other choices fixed?\n",
        "The earlier sections explain the physical relationship. Here we turn one part of that\n",
        "relationship into a calculation that you can run, inspect, and change in Google Colab.\n",
        "\n",
        "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\n",
        "its useful range, and a plotting library will usually draw that number without asking\n",
        "whether the physical assumptions still hold. The selected interval is from\n",
        "0 to 0.5 m. It gives us a specific domain to discuss\n",
        "instead of leaving the graph's range to a software default.\n",
        "\n",
        "Use the notebook link above the lesson, run the setup cell, and then run the cells in\n",
        "order. The code below is also included there. NumPy handles the arrays of numerical\n",
        "values, SymPy keeps the equation symbolic, and Matplotlib draws the results. If these\n",
        "libraries or notebook cells are unfamiliar, start with\n",
        "[Your first physics notebook](https://tirta.co/a-byte-of-physics/your-first-physics-notebook).\n",
        "\n",
        "### State the relationship before choosing a graph\n",
        "\n",
        "In this small example, `q` stands for height uncertainty, expressed in m. The output is\n",
        "first-order fall-time uncertainty, expressed in s. The equation below uses the numerical values in those\n",
        "units. Any fixed coefficients therefore carry the units needed to make the relation\n",
        "consistent. A value supplied in another unit must be converted before it enters this\n",
        "expression.\n",
        "\n",
        "\n",
        "$$\n",
        "f(q) = 0.0713921561463532 q\n",
        "$$\n",
        "\n",
        "\n",
        "This is a function of one changing input. It is not a statement that the physical\n",
        "system has only one variable. We deliberately hold the other inputs fixed so that one\n",
        "cause of variation is visible. Changing several inputs at once would make it harder\n",
        "to tell which change produced the output difference. Write down the held-fixed choices\n",
        "before trying a different experiment.\n",
        "\n",
        "At 0.1 m, the expression gives 0.00713922 s. This is our\n",
        "reference calculation. It is a prediction of the stated example, not a new measurement.\n",
        "Its displayed digits help us compare implementations. They should not be read as a\n",
        "claim that physical inputs are known to six significant figures."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-011",
      "metadata": {},
      "source": [
        "import numpy as np\n",
        "import sympy as sp\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "q = sp.Symbol(\"q\", real=True)\n",
        "expression = sp.sympify(\"q/(9.81*sqrt(20/9.81))\", locals={\"q\": q})\n",
        "reference_input = 0.1\n",
        "reference_output = float(expression.subs(q, reference_input))\n",
        "print(\"Input:\", reference_input, \"m\")\n",
        "print(\"Predicted first-order fall-time uncertainty:\", reference_output, \"s\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-012",
      "metadata": {},
      "source": [
        "`sp.Symbol` declares a mathematical symbol. It does not assign a numerical measurement\n",
        "to that symbol. `subs` then replaces the symbol with our chosen input, and `float`\n",
        "converts the resulting symbolic number into a standard Python numerical value.\n",
        "Keeping these steps separate lets us inspect the equation before numerical substitution.\n",
        "It also prevents a later plot from becoming the only surviving record of the model.\n",
        "\n",
        "### Compare a few cases you can explain\n",
        "\n",
        "Before drawing hundreds of points, calculate three. The lower endpoint gives\n",
        "0 s. The midpoint, at 0.25 m, gives\n",
        "0.017848 s. The upper endpoint gives 0.0356961 s.\n",
        "Read these together with the assumptions: they describe different choices of height uncertainty\n",
        "within the same example, with the other inputs held fixed.\n",
        "\n",
        "These three values are a useful first check, but they do not establish the shape between\n",
        "them. Two endpoints can be equal even when the curve bends or oscillates in between.\n",
        "Likewise, a large change between endpoints does not tell us whether the relationship is\n",
        "linear. We need the equation and intermediate samples to answer those questions."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-013",
      "metadata": {},
      "source": [
        "evaluate = sp.lambdify(q, expression, modules=\"numpy\")\n",
        "inputs = np.array([0.0, 0.25, 0.5])\n",
        "outputs = np.asarray(evaluate(inputs), dtype=float)\n",
        "outputs = np.broadcast_to(outputs, inputs.shape)\n",
        "for input_value, output_value in zip(inputs, outputs):\n",
        "    print(f\"{input_value:.6g} m -> {output_value:.6g} s\")\n",
        "assert np.all(np.isfinite(outputs))\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-014",
      "metadata": {},
      "source": [
        "`lambdify` turns the symbolic expression into a numerical function. We explicitly select\n",
        "NumPy as its numerical backend so it can accept an array. The same expression now has\n",
        "two useful forms: one for algebra and one for calculating many cases. The assertion\n",
        "checks that the chosen inputs produce finite outputs. It would catch an infinity or an\n",
        "undefined numerical result, but a finite value can still be physically inappropriate.\n",
        "\n",
        "### Make a graph that answers the question\n",
        "\n",
        "The horizontal axis shows height uncertainty; the vertical axis shows first-order fall-time uncertainty. Every plotted\n",
        "point is a prediction of the same expression. We mark the reference case separately\n",
        "so that a reader can connect the earlier printed value to its place on the curve.\n",
        "The axis labels include units because a shape without a scale cannot tell us the size\n",
        "of a physical effect."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-015",
      "metadata": {},
      "source": [
        "input_grid = np.linspace(0.0, 0.5, 301)\n",
        "output_grid = np.asarray(evaluate(input_grid), dtype=float)\n",
        "output_grid = np.broadcast_to(output_grid, input_grid.shape)\n",
        "fig, ax = plt.subplots(figsize=(7, 4))\n",
        "ax.plot(input_grid, output_grid, label=\"Stated model\")\n",
        "ax.scatter([reference_input], [reference_output], label=\"Reference case\", zorder=3)\n",
        "ax.set_xlabel(\"Height uncertainty (m)\")\n",
        "ax.set_ylabel(\"First-order fall-time uncertainty (s)\")\n",
        "ax.legend()\n",
        "ax.grid(alpha=0.25)\n",
        "fig.tight_layout()\n",
        "plt.show()\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-016",
      "metadata": {},
      "source": [
        "Look for a sign change, a turning point, or a region where the curve becomes steep.\n",
        "Connect each feature to the expression rather than to the colour of the line. If the\n",
        "curve has a minimum or maximum, changing the input in opposite directions may have\n",
        "similar effects on the output near that point. If it is nearly straight over a short\n",
        "interval, a local linear approximation may be useful even when the complete expression\n",
        "is nonlinear.\n",
        "\n",
        "Increasing the number of samples makes the line smoother and may reveal features that\n",
        "a coarse grid missed. It does not improve the physical inputs or enlarge the model's\n",
        "validity range. For quantities that can take only discrete values, use the line as a\n",
        "guide to the relationship and interpret only the allowed input values. A plotting\n",
        "function does not enforce such restrictions for you.\n",
        "\n",
        "### Measure the local sensitivity\n",
        "\n",
        "A derivative asks a more specific question than the whole graph: how quickly does\n",
        "first-order fall-time uncertainty change near the reference input? Its units are the output unit divided by\n",
        "the input unit. For this calculation, the derivative at 0.1 m is\n",
        "0.0713922 in those ratio units. Locally, the output increases as the\n",
        "input increases. This statement is local; the sign or size of the slope can be different\n",
        "elsewhere on the curve.\n",
        "\n",
        "\n",
        "$$\n",
        "f'(q) = 0.0713921561463532\n",
        "$$\n",
        "\n",
        "\n",
        "For a small input change, multiply the derivative by that change to estimate the output\n",
        "change. Then compare that estimate with a fresh evaluation of the full expression.\n",
        "The distinction between these two calculations matters: the derivative gives a tangent\n",
        "approximation, while substitution evaluates the chosen expression at the new point."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-017",
      "metadata": {},
      "source": [
        "slope_expression = sp.diff(expression, q)\n",
        "slope_at_reference = float(slope_expression.subs(q, reference_input))\n",
        "changed_input = 0.10250000000000001\n",
        "linear_prediction = reference_output + slope_at_reference * (\n",
        "    changed_input - reference_input\n",
        ")\n",
        "full_prediction = float(evaluate(changed_input))\n",
        "print(\"Symbolic derivative:\", slope_expression)\n",
        "print(\"Tangent prediction:\", linear_prediction, \"s\")\n",
        "print(\"Full expression:\", full_prediction, \"s\")\n",
        "print(\"Approximation difference:\", full_prediction - linear_prediction, \"s\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-018",
      "metadata": {},
      "source": [
        "Here the changed input is 0.1025 m. The tangent estimate is\n",
        "0.0073177 s, while the full expression gives\n",
        "0.0073177 s. If the two values are close, it means the chosen\n",
        "input change is small enough for this local approximation at this point. It does not\n",
        "mean the entire model is linear. If the slope is zero, a quadratic or higher-order term\n",
        "may supply the leading change instead.\n",
        "\n",
        "This is also the beginning of uncertainty propagation. If the input has a small stated\n",
        "standard uncertainty, the magnitude of the slope times that uncertainty estimates one\n",
        "contribution to output uncertainty. Do not automatically use the same rule for a wide\n",
        "interval, a discontinuity, a turning point with zero first derivative, or several\n",
        "correlated uncertain inputs. Those situations need more of the model than one slope.\n",
        "\n",
        "### Check the derivative with numerical differences\n",
        "\n",
        "We can estimate the same slope from values on either side of the reference point.\n",
        "Subtract the lower output from the upper output and divide by twice the input step.\n",
        "Parentheses are essential: the entire output difference must be divided by the entire\n",
        "input interval. Without them, Python can execute a different mathematical expression\n",
        "while still producing a plausible number.\n",
        "\n",
        "The calculation below uses three decreasing step sizes. Each estimate is compared with\n",
        "the symbolic derivative, so the reference is independent of the numerical difference\n",
        "formula. Near an endpoint, it is acceptable here to evaluate a small extension only\n",
        "because the displayed mathematical expression is smooth there; such a check does not\n",
        "assert that extrapolated values describe additional physical cases."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-019",
      "metadata": {},
      "source": [
        "input_span = 0.5\n",
        "for fraction in [1e-2, 1e-3, 1e-4]:\n",
        "    step = input_span * fraction\n",
        "    upper = float(evaluate(reference_input + step))\n",
        "    lower = float(evaluate(reference_input - step))\n",
        "    numerical_slope = (upper - lower) / (2 * step)\n",
        "    difference = numerical_slope - slope_at_reference\n",
        "    print(f\"step={step:.6g}: slope={numerical_slope:.6g}, difference={difference:.6g}\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-020",
      "metadata": {},
      "source": [
        "For a smooth function, reducing the step often reduces the approximation error at first.\n",
        "Very small steps can eventually make subtraction of nearly equal floating-point values\n",
        "less reliable. Therefore “smaller” is not an unlimited guarantee of “better.” Compare\n",
        "the observed behaviour over a useful range of steps instead of choosing the smallest\n",
        "number the computer can represent.\n",
        "\n",
        "An absolute slope difference is useful when the expected slope is near zero. A relative\n",
        "difference would divide by a very small reference and could look enormous even when the\n",
        "absolute discrepancy is tiny. Away from zero, a relative difference can help compare\n",
        "quantities with very different scales. The tolerance should reflect the question and\n",
        "the numerical method, rather than a universal decimal threshold copied into every test.\n",
        "\n",
        "### Change the example and preserve the reasoning\n",
        "\n",
        "Make one copy of the reference calculation before editing it. Choose a second value of\n",
        "height uncertainty inside the stated interval, predict whether first-order fall-time uncertainty will rise or fall,\n",
        "and then evaluate the expression. Place the prediction and the result in a text cell.\n",
        "If they disagree, identify whether the mistake was in the sign, the unit conversion,\n",
        "the algebra, or the assumption about how the curve behaves.\n",
        "\n",
        "Next choose a shorter plotting interval around the reference point. Compare the local\n",
        "curve with its tangent approximation. Then widen the interval again. The difference\n",
        "shows why a useful local estimate need not describe the whole range. Keep the axis\n",
        "labels and numerical scale visible when comparing the plots; automatic axis limits can\n",
        "make two different effects appear equally large.\n",
        "\n",
        "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\n",
        "to the setup that would violate that limit. State what new input, equation, or observation\n",
        "would be needed before trusting an answer in the changed situation. This last step\n",
        "connects the Python experiment to the physics instead of treating successful execution\n",
        "as the only criterion for a useful result.\n",
        "\n",
        "Before saving, restart the runtime and run all cells in order. A result that depends on\n",
        "an earlier, now-deleted input cell is not reproducible from the saved notebook. Keep\n",
        "unrounded values for later calculations, round only the reported output, and label any\n",
        "new data as measured, assumed, or generated. The graph and printed values should remain\n",
        "traceable to the same expression and the same choices of inputs.\n",
        "\n",
        "### Recover the output change by integrating the slope\n",
        "\n",
        "There is another way to check that the expression and its derivative describe the same\n",
        "relationship. Add up the small output changes predicted by the slope across the chosen\n",
        "input interval. In the continuous limit, this integral equals the output at the upper\n",
        "endpoint minus the output at the lower endpoint. The result has units of s:\n",
        "the input unit in the integration cancels the input unit in the denominator of the slope.\n",
        "\n",
        "This statement is about the mathematics of this particular relationship. It does not\n",
        "assign a new physical meaning to an arbitrary area under a graph. For example, an area\n",
        "under force versus distance represents work, while an area under a different pair of\n",
        "quantities may represent something else or have no standard name. Always carry the\n",
        "axis units through the calculation before naming an integral."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-021",
      "metadata": {},
      "source": [
        "slope_function = sp.lambdify(q, slope_expression, modules=\"numpy\")\n",
        "endpoint_change = float(evaluate(0.5) - evaluate(0.0))\n",
        "for points in [101, 201, 401]:\n",
        "    grid = np.linspace(0.0, 0.5, points)\n",
        "    slopes = np.asarray(slope_function(grid), dtype=float)\n",
        "    slopes = np.broadcast_to(slopes, grid.shape)\n",
        "    integrated_change = np.trapezoid(slopes, grid)\n",
        "    print(\n",
        "        points,\n",
        "        \"integrated change:\",\n",
        "        integrated_change,\n",
        "        \"endpoint change:\",\n",
        "        endpoint_change,\n",
        "    )\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-022",
      "metadata": {},
      "source": [
        "The trapezoidal rule joins neighbouring slope samples with straight segments and adds\n",
        "their signed areas. A negative contribution remains negative; replacing every slope\n",
        "by its magnitude would calculate a different quantity. Increasing the sample count\n",
        "provides a practical refinement check. If the values do not settle toward the endpoint\n",
        "difference, first inspect the interval, singularities, and array ordering.\n",
        "\n",
        "Do not conclude that two agreeing calculations prove the model is physically complete.\n",
        "Both use the same selected relationship, so an omitted effect would be omitted from\n",
        "both. Their agreement is evidence that the numerical tools implement that relationship\n",
        "consistently. Comparing with an independent experiment or a more appropriate physical\n",
        "model is a separate test.\n",
        "\n",
        "Keep this comparison in the notebook when you change the expression. It is particularly\n",
        "useful after adding a coefficient, changing a sign convention, or converting an input\n",
        "unit. A code cell that produces a smooth graph can conceal these mistakes; a second\n",
        "calculation of the same output change gives you another place to notice them.\n",
        "\n",
        "## Sources\n",
        "\n",
        "- [OpenStax, *University Physics Volume 1*, Section 1.3: The Language of Physics—Physical Quantities and Units](https://openstax.org/books/university-physics-volume-1/pages/1-3-the-language-of-physics-physical-quantities-and-units).\n",
        "- [OpenStax, *University Physics Volume 1*, Section 1.6: Significant Figures](https://openstax.org/books/university-physics-volume-1/pages/1-6-significant-figures).\n",
        "- [OpenStax, *University Physics Volume 1*, Section 1.5: Estimates and Fermi Calculations](https://openstax.org/books/university-physics-volume-1/pages/1-5-estimates-and-fermi-calculations).\n",
        "- [MIT OpenCourseWare, 8.01SC Classical Mechanics: Online Textbook](https://ocw.mit.edu/courses/8-01sc-classical-mechanics-fall-2016/pages/online-textbook/).\n",
        "- [The Physics Hypertextbook](https://physics.info/).\n",
        "- [Physics LibreTexts](https://phys.libretexts.org/).\n",
        "- Benjamin Crowell, *Light and Matter*, locally archived course reference."
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.12"
    },
    "colab": {
      "name": "numerical-ethics.ipynb",
      "provenance": []
    },
    "tirta": {
      "lesson": "https://tirta.co/a-byte-of-physics/numerical-ethics",
      "source_sha256": "cdad27b186f1cc4d9292194e1ba6e3b11b68ff7b909dea38c0a256bfd6aee2a6"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
