{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "markdown-000",
      "metadata": {},
      "source": [
        "# Numerical energy conservation\n",
        "\n",
        "[Read the lesson](https://tirta.co/a-byte-of-physics/numerical-energy-conservation). 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": [
        "Energy is one of the strongest diagnostics for a trajectory calculation, but “energy\n",
        "should be constant” is true only for a correctly chosen closed, time-independent model.\n",
        "A useful numerical check first defines the system, names every included energy store and\n",
        "boundary transfer, and then measures the unexplained residual at compatible times.\n",
        "\n",
        "## Define what is conserved\n",
        "\n",
        "For one particle moving in a time-independent conservative potential,\n",
        "\n",
        "\n",
        "$$\n",
        "E=K+U=\\frac12m|\\mathbf v|^2+U(\\mathbf r)\n",
        "$$\n",
        "\n",
        "\n",
        "and the continuous equations imply\n",
        "$dE/dt=0$.\n",
        "Kinetic and potential energy can change substantially while their sum remains constant.\n",
        "\n",
        "For several interacting particles, include every particle's kinetic energy and count\n",
        "each pair potential once:\n",
        "\n",
        "\n",
        "$$\n",
        "E=\\sum_i\\frac12m_i|\\mathbf v_i|^2+\\sum_{i<j}U_{ij}\n",
        "$$\n",
        "\n",
        "\n",
        "Summing over both ordered pairs would double the potential energy. External fields may\n",
        "add potential terms or boundary work depending on the chosen system.\n",
        "\n",
        "## An energy ledger for open or dissipative models\n",
        "\n",
        "Choose positive transfer into the system. Between two checkpoints,\n",
        "\n",
        "\n",
        "$$\n",
        "E_{n+1}^{\\mathrm{expected}}=E_n+W_{\\mathrm{external}}+Q_{\\mathrm{in}}-E_{\\mathrm{out}}\n",
        "$$\n",
        "\n",
        "\n",
        "The numerical residual is\n",
        "\n",
        "\n",
        "$$\n",
        "r_{n+1}=E_{n+1}^{\\mathrm{computed}}-E_{n+1}^{\\mathrm{expected}}\n",
        "$$\n",
        "\n",
        "\n",
        "For kinetic friction, decreasing mechanical energy can be correct while total energy of\n",
        "a larger closed system remains constant through increased thermal energy. For a driven\n",
        "system, external work should be integrated rather than demanding a fixed mechanical\n",
        "total."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-003",
      "metadata": {},
      "source": [
        "previous_energy_j = 20.0\n",
        "transfers_j = {\"work in\": 5.0, \"heat out\": -2.0}\n",
        "computed_energy_j = 23.0\n",
        "expected_energy_j = previous_energy_j + sum(transfers_j.values())\n",
        "residual_j = computed_energy_j - expected_energy_j\n",
        "print(f\"Energy ledger residual: {residual_j:.3g} J\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-004",
      "metadata": {},
      "source": [
        "Every transfer must cover the same time interval and system boundary as the stored\n",
        "energies.\n",
        "\n",
        "## A harmonic-oscillator reference\n",
        "\n",
        "The ideal oscillator satisfies\n",
        "\n",
        "\n",
        "$$\n",
        "m\\ddot x=-kx,\\qquad E=\\frac12mv^2+\\frac12kx^2\n",
        "$$\n",
        "\n",
        "\n",
        "Its exact solution is bounded and periodic. It is an excellent reference because\n",
        "position, velocity, phase, and energy are known analytically.\n",
        "\n",
        "Forward Euler uses\n",
        "\n",
        "\n",
        "$$\n",
        "x_{n+1}=x_n+hv_n,\\qquad v_{n+1}=v_n-h\\frac{k}{m}x_n\n",
        "$$\n",
        "\n",
        "\n",
        "and increases energy by the factor\n",
        "\n",
        "\n",
        "$$\n",
        "E_{n+1}=\\left(1+h^2\\frac{k}{m}\\right)E_n\n",
        "$$\n",
        "\n",
        "\n",
        "for every nonzero step. This systematic growth is a property of the discrete update, not\n",
        "of the oscillator.\n",
        "\n",
        "## Integrator behavior matters\n",
        "\n",
        "Velocity-first semi-implicit Euler updates\n",
        "\n",
        "\n",
        "$$\n",
        "v_{n+1}=v_n-h\\frac{k}{m}x_n,\\qquad x_{n+1}=x_n+hv_{n+1}\n",
        "$$\n",
        "\n",
        "\n",
        "and usually gives bounded oscillatory energy error for a sufficiently small step. It is\n",
        "still first-order accurate and does not conserve the exact physical energy at every\n",
        "step.\n",
        "\n",
        "Velocity Verlet is second-order and symplectic for position-dependent conservative\n",
        "forces. It often keeps energy near a bounded modified value over long times. Classical\n",
        "RK4 can have much smaller short-interval error but is not symplectic and can show slow\n",
        "long-term drift. “Higher order” and “better conservation over arbitrarily long time” are\n",
        "not identical claims.\n",
        "\n",
        "No integrator guarantees energy conservation for every problem or step. A method must\n",
        "match the equation type, time scales, constraints, and intended duration.\n",
        "\n",
        "## Compute energy at one consistent state\n",
        "\n",
        "In a staggered or leapfrog scheme, positions and velocities may naturally live at\n",
        "different time levels. Combining\n",
        "$\\mathbf r_n$ with\n",
        "$\\mathbf v_{n+1/2}$ in the\n",
        "ordinary energy formula does not represent one physical instant unless the diagnostic\n",
        "is derived for that staggering.\n",
        "\n",
        "Likewise, after updating velocity but before updating position, an in-place program has\n",
        "a mixed-time state. Save old values or complete the integrator step before evaluating an\n",
        "endpoint energy."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-005",
      "metadata": {},
      "source": [
        "def oscillator_energy(position, velocity, mass=1.0, stiffness=1.0):\n",
        "    kinetic = 0.5 * mass * velocity**2\n",
        "    potential = 0.5 * stiffness * position**2\n",
        "    return kinetic + potential\n",
        "\n",
        "\n",
        "print(f\"Initial oscillator energy: {oscillator_energy(1.0, 0.0):.3f} J\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-006",
      "metadata": {},
      "source": [
        "The potential function must describe the same force model used by the dynamics.\n",
        "\n",
        "## Absolute, relative, and scaled residuals\n",
        "\n",
        "An absolute residual\n",
        "$|E(t)-E(0)|$ has joule units.\n",
        "A common relative residual is\n",
        "\n",
        "\n",
        "$$\n",
        "\\epsilon_E(t)=\\frac{E(t)-E(0)}{E_*}\n",
        "$$\n",
        "\n",
        "\n",
        "where $E_*$ is a declared\n",
        "nonzero scale. Dividing by initial total energy is unreliable when that value is near\n",
        "zero because large positive and negative terms may cancel.\n",
        "\n",
        "A scale-aware pass condition can use\n",
        "\n",
        "\n",
        "$$\n",
        "|r|\\le\\epsilon_{\\mathrm{abs}}+\\epsilon_{\\mathrm{rel}}\\max(|E_n|,|E_{n+1}|,E_*)\n",
        "$$\n",
        "\n",
        "\n",
        "Tolerance should reflect integrator order, step, duration, floating-point precision,\n",
        "and intended use. Choosing it after observing the result turns the check into a story\n",
        "rather than a test.\n",
        "\n",
        "## Drift, oscillation, and maximum error\n",
        "\n",
        "Report more than endpoint error. A calculation can drift far away and return near the\n",
        "initial energy by coincidence. Useful statistics include maximum absolute residual,\n",
        "root-mean-square residual, fitted drift rate, and the full signed trace.\n",
        "\n",
        "Oscillatory bounded error and monotonic secular drift have different long-term\n",
        "implications. A symplectic method can show visibly oscillating exact-energy error while\n",
        "preserving qualitative orbital structure better than a method with smaller early error\n",
        "but persistent drift.\n",
        "\n",
        "## Step refinement\n",
        "\n",
        "Run the same model and initial state to the same final physical time with steps\n",
        "$h$,\n",
        "$h/2$, and\n",
        "$h/4$."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-007",
      "metadata": {},
      "source": [
        "for steps in [100, 200, 400]:\n",
        "    x, v = 1.0, 0.0\n",
        "    dt = 10.0 / steps\n",
        "    largest_error = 0.0\n",
        "    for _ in range(steps):\n",
        "        v -= x * dt\n",
        "        x += v * dt\n",
        "        largest_error = max(largest_error, abs(oscillator_energy(x, v) - 0.5))\n",
        "    print(f\"dt={dt:.3f} s: largest energy error {largest_error:.6f} J\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-008",
      "metadata": {},
      "source": [
        "If a method has global order\n",
        "$p$, state error often scales like\n",
        "$h^p$ in the asymptotic regime. Energy\n",
        "error may show different structured behavior, so measure rather than assume its rate.\n",
        "\n",
        "Refinement that does not improve results may indicate instability, discontinuous events,\n",
        "an inconsistent energy formula, spatial discretization error, nonlinear-solver error, or\n",
        "roundoff dominance.\n",
        "\n",
        "## Work-force consistency\n",
        "\n",
        "For a conservative force,\n",
        "\n",
        "\n",
        "$$\n",
        "\\mathbf F=-\\nabla U\n",
        "$$\n",
        "\n",
        "\n",
        "Check the implemented force against a finite-difference gradient of the implemented\n",
        "potential away from singularities. A perfect integrator cannot conserve a total built\n",
        "from a potential that is inconsistent with its force.\n",
        "\n",
        "For velocity-dependent drag, calculate dissipated work from\n",
        "$\\int\\mathbf F_D\\cdot\\mathbf v\\,dt$\n",
        "and include it in the ledger. Approximation error in this work integral can be distinct\n",
        "from state-integration error.\n",
        "\n",
        "## Constraints and collisions\n",
        "\n",
        "An ideal fixed smooth constraint can do zero work when its force is perpendicular to\n",
        "allowed velocity. Position projection, however, may change velocity or configuration\n",
        "and inject or remove energy. Measure the change across the correction and report it.\n",
        "\n",
        "Elastic collision rules should conserve kinetic energy for the intended closed pair;\n",
        "inelastic collisions should not. For coefficient of restitution\n",
        "$e$ against a fixed wall,\n",
        "normal kinetic energy after impact is\n",
        "$e^2$ times its pre-impact value. Demanding\n",
        "conservation when $e<1$ would\n",
        "contradict the model.\n",
        "\n",
        "## Floating-point summation\n",
        "\n",
        "Large systems may sum many positive kinetic terms and signed potential terms spanning\n",
        "wide magnitudes. Summation order affects floating-point roundoff. Pairwise or compensated\n",
        "summation can reduce avoidable loss, but it cannot correct an incomplete energy model.\n",
        "\n",
        "Use full internal precision for diagnostics and round only reported values. Reusing a\n",
        "rounded displayed total as the next reference can manufacture drift.\n",
        "\n",
        "## Energy conservation is not sufficient\n",
        "\n",
        "A trajectory can have the correct energy and wrong phase, direction, or orbit. It may\n",
        "move on the wrong part of a constant-energy surface. Pair energy with independent checks\n",
        "such as analytic position and velocity, momentum, angular momentum, constraints, event\n",
        "times, reversibility, and convergence.\n",
        "\n",
        "Artificially rescaling velocity to force the exact energy after every step can hide\n",
        "errors and alter dynamics. Such a projection defines another algorithm and needs its own\n",
        "justification; it is not proof that the original method conserves energy.\n",
        "\n",
        "## Reproducible diagnostic record\n",
        "\n",
        "Store:\n",
        "\n",
        "- system boundary and reference frame;\n",
        "- every named energy store and its zero convention;\n",
        "- signed work, heat, and boundary transfers;\n",
        "- force and potential model versions;\n",
        "- integrator, step sizes, tolerances, and floating-point type;\n",
        "- checkpoint times and time-level conventions;\n",
        "- absolute residual, scaled residual, maximum error, and drift;\n",
        "- results from step refinement and analytic fixtures.\n",
        "\n",
        "## Required checks\n",
        "\n",
        "- Exact constant-velocity and constant-acceleration fixtures behave as predicted.\n",
        "- An ideal oscillator exchanges kinetic and potential energy with stable total behavior\n",
        "  appropriate to the chosen method.\n",
        "- Force agrees with the negative potential gradient.\n",
        "- Dissipative and driven cases close their transfer ledgers instead of demanding constant\n",
        "  mechanical energy.\n",
        "- Pair potentials are counted once and all bodies share one timestamp.\n",
        "- Collision and constraint corrections report their energy changes.\n",
        "- Errors are compared at fixed physical times under step refinement.\n",
        "- Tolerances use a meaningful scale even when total energy is near zero.\n",
        "- Energy is paired with other state and invariant checks.\n",
        "- All diagnostic values come from unrounded internal state.\n",
        "\n",
        "Numerical energy conservation is not one Boolean assertion. It is a source-backed\n",
        "ledger, a convergence experiment, and a long-time diagnostic that must match the actual\n",
        "physics and discrete method.\n",
        "\n",
        "## A worked Python notebook\n",
        "\n",
        "Inspect one part of the energy of a unit-mass, unit-stiffness oscillator. The question for this calculation is precise: how does **spring potential energy**\n",
        "change when we change **position**, 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",
        "Potential energy varies during motion; conservation applies to the sum of kinetic and potential energy. 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",
        "-2 to 2 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 position, expressed in m. The output is\n",
        "spring potential energy, expressed in J. 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) = \\frac{q^{2}}{2}\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 1 m, the expression gives 0.5 J. 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-009",
      "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**2/2\", locals={\"q\": q})\n",
        "reference_input = 1.0\n",
        "reference_output = float(expression.subs(q, reference_input))\n",
        "print(\"Input:\", reference_input, \"m\")\n",
        "print(\"Predicted spring potential energy:\", reference_output, \"J\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-010",
      "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",
        "2 J. The midpoint, at 0 m, gives\n",
        "0 J. The upper endpoint gives 2 J.\n",
        "Read these together with the assumptions: they describe different choices of position\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-011",
      "metadata": {},
      "source": [
        "evaluate = sp.lambdify(q, expression, modules=\"numpy\")\n",
        "inputs = np.array([-2.0, 0.0, 2.0])\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} J\")\n",
        "assert np.all(np.isfinite(outputs))\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-012",
      "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 position; the vertical axis shows spring potential energy. 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-013",
      "metadata": {},
      "source": [
        "input_grid = np.linspace(-2.0, 2.0, 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(\"Position (m)\")\n",
        "ax.set_ylabel(\"Spring potential energy (J)\")\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-014",
      "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",
        "spring potential energy change near the reference input? Its units are the output unit divided by\n",
        "the input unit. For this calculation, the derivative at 1 m is\n",
        "1 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) = q\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-015",
      "metadata": {},
      "source": [
        "slope_expression = sp.diff(expression, q)\n",
        "slope_at_reference = float(slope_expression.subs(q, reference_input))\n",
        "changed_input = 1.02\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, \"J\")\n",
        "print(\"Full expression:\", full_prediction, \"J\")\n",
        "print(\"Approximation difference:\", full_prediction - linear_prediction, \"J\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-016",
      "metadata": {},
      "source": [
        "Here the changed input is 1.02 m. The tangent estimate is\n",
        "0.52 J, while the full expression gives\n",
        "0.5202 J. 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-017",
      "metadata": {},
      "source": [
        "input_span = 4.0\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-018",
      "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",
        "position inside the stated interval, predict whether spring potential energy 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: Potential energy varies during motion; conservation applies to the sum of kinetic and potential energy. 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 J:\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-019",
      "metadata": {},
      "source": [
        "slope_function = sp.lambdify(q, slope_expression, modules=\"numpy\")\n",
        "endpoint_change = float(evaluate(2.0) - evaluate(-2.0))\n",
        "for points in [101, 201, 401]:\n",
        "    grid = np.linspace(-2.0, 2.0, 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-020",
      "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 8.3, \"Conservation of Energy\"](https://openstax.org/books/university-physics-volume-1/pages/8-3-conservation-of-energy).\n",
        "- [OpenStax, *University Physics Volume 1*, Section 15.2, \"Energy in Simple Harmonic Motion\"](https://openstax.org/books/university-physics-volume-1/pages/15-2-energy-in-simple-harmonic-motion).\n",
        "- [MIT OpenCourseWare, *8.01SC Classical Mechanics*, Chapter 14, \"Potential Energy and Conservation of Energy\"](https://ocw.mit.edu/courses/8-01sc-classical-mechanics-fall-2016/resources/mit8_01scs22_chapter14/).\n",
        "- [Physics LibreTexts, \"Numerical Approaches\"](https://phys.libretexts.org/Bookshelves/Classical_Mechanics/Essential_Graduate_Physics_-_Classical_Mechanics_%28Likharev%29/05%3A_Oscillations/5.07%3A_Numerical_Approaches).\n",
        "- [Benjamin Crowell, *Light and Matter*, Chapter 14, \"Conservation of Energy\"](https://open.umn.edu/opentextbooks/textbooks/light-and-matter)."
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.12"
    },
    "colab": {
      "name": "numerical-energy-conservation.ipynb",
      "provenance": []
    },
    "tirta": {
      "lesson": "https://tirta.co/a-byte-of-physics/numerical-energy-conservation",
      "source_sha256": "df4d6e8ad1d7381481896391b992bdc51cff44dd490f198c72044ad1537edbd5"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
