{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "markdown-000",
      "metadata": {},
      "source": [
        "# Symmetry and conservation\n",
        "\n",
        "[Read the lesson](https://tirta.co/a-byte-of-physics/symmetry-and-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": [
        "A symmetry is a transformation that changes the description of a physical situation\n",
        "without changing the relevant laws. A conservation law states that a quantity remains\n",
        "constant for a specified system. These ideas meet precisely in Noether's theorem: under\n",
        "its assumptions, every continuous differentiable symmetry of an action corresponds to a\n",
        "conserved quantity.\n",
        "\n",
        "## Symmetry means invariance of the law\n",
        "\n",
        "Consider an isolated experiment performed today and repeated tomorrow with the same\n",
        "preparation. If the governing law has no preferred time origin, shifting every event by\n",
        "the same amount does not change its predictions. This is time-translation symmetry. If\n",
        "moving the entire isolated apparatus by the same displacement does not change the\n",
        "internal motion, the law has spatial-translation symmetry. If rotating the whole setup\n",
        "preserves the predictions after the result is rotated with it, the law has rotational\n",
        "symmetry.\n",
        "\n",
        "The initial conditions need not themselves look symmetric. A projectile launched east\n",
        "does not have to produce the same untransformed trajectory after the apparatus is\n",
        "rotated north. The correct comparison transforms the inputs and then transforms the\n",
        "output in the corresponding way. This behavior is often called equivariance.\n",
        "\n",
        "For a state transformation\n",
        "$T$ and evolution map\n",
        "$\\Phi_t$, the comparison\n",
        "has the form\n",
        "\n",
        "\n",
        "$$\n",
        "\\Phi_t(T\\mathbf y_0)=T\\Phi_t(\\mathbf y_0)\n",
        "$$\n",
        "\n",
        "\n",
        "when the transformation is a symmetry and all boundary conditions are transformed too.\n",
        "A fixed wall, external field, or laboratory support can break a symmetry that the\n",
        "isolated microscopic law would otherwise possess."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-003",
      "metadata": {},
      "source": [
        "import numpy as np\n",
        "\n",
        "\n",
        "def evolve(position, velocity, duration):\n",
        "    return np.asarray(position) + np.asarray(velocity) * duration\n",
        "\n",
        "\n",
        "position, velocity = np.array([1.0, 2.0]), np.array([3.0, -1.0])\n",
        "shift = np.array([7.0, 4.0])\n",
        "assert np.allclose(\n",
        "    evolve(position + shift, velocity, 2), evolve(position, velocity, 2) + shift\n",
        ")\n",
        "print(\"Free motion respects a translation of the origin.\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-004",
      "metadata": {},
      "source": [
        "## The action and Noether's theorem\n",
        "\n",
        "For generalized coordinates\n",
        "$q_i$, velocities\n",
        "$\\dot q_i$, and a\n",
        "Lagrangian\n",
        "$L(\\mathbf q,\\dot{\\mathbf q},t)$,\n",
        "the action between two times is\n",
        "\n",
        "\n",
        "$$\n",
        "S=\\int_{t_1}^{t_2}L(\\mathbf q,\\dot{\\mathbf q},t)\\,dt\n",
        "$$\n",
        "\n",
        "\n",
        "The physical path makes the action stationary under appropriate endpoint conditions,\n",
        "leading to the Euler-Lagrange equations:\n",
        "\n",
        "\n",
        "$$\n",
        "\\frac{d}{dt}\\left(\\frac{\\partial L}{\\partial\\dot q_i}\\right)-\\frac{\\partial L}{\\partial q_i}=0\n",
        "$$\n",
        "\n",
        "\n",
        "Noether's theorem applies to a continuous family of transformations that leaves the\n",
        "action invariant, or changes the Lagrangian only by a total time derivative under the\n",
        "more general statement. It is not the claim that every visual symmetry, every discrete\n",
        "reflection, or every convenient code transformation automatically creates a new scalar\n",
        "conservation law.\n",
        "\n",
        "## Time translation and energy\n",
        "\n",
        "If the Lagrangian has no explicit time dependence, the quantity\n",
        "\n",
        "\n",
        "$$\n",
        "E_L=\\sum_i\\dot q_i\\frac{\\partial L}{\\partial\\dot q_i}-L\n",
        "$$\n",
        "\n",
        "\n",
        "is conserved along solutions. For ordinary particles with\n",
        "\n",
        "\n",
        "$$\n",
        "L=T-U\n",
        "$$\n",
        "\n",
        "\n",
        "and standard velocity-independent potential energy, this quantity is the mechanical\n",
        "energy\n",
        "$E=T+U$.\n",
        "\n",
        "The key condition is no explicit dependence on time. A trajectory still changes with\n",
        "time, and its coordinates appear in the Lagrangian; that does not break time-translation\n",
        "symmetry. A moving support, prescribed time-varying field, or external drive does. In\n",
        "that case energy may enter or leave the chosen mechanical system.\n",
        "\n",
        "Adding a constant to potential energy changes the numerical zero of\n",
        "$E$ but not forces, energy differences, or\n",
        "conservation. That freedom is a reference convention, not the time-translation symmetry\n",
        "that produces energy conservation.\n",
        "\n",
        "## Spatial translation and linear momentum\n",
        "\n",
        "If the Lagrangian is unchanged by translating an isolated system in some direction, the\n",
        "corresponding component of total linear momentum is conserved. Generalized momentum is\n",
        "defined by\n",
        "\n",
        "\n",
        "$$\n",
        "p_i=\\frac{\\partial L}{\\partial\\dot q_i}\n",
        "$$\n",
        "\n",
        "\n",
        "For Cartesian coordinates of ordinary nonrelativistic particles,\n",
        "$\\mathbf p=m\\mathbf v$.\n",
        "If a Cartesian coordinate does not appear in the Lagrangian, it is cyclic, and its\n",
        "conjugate momentum is constant:\n",
        "\n",
        "\n",
        "$$\n",
        "\\frac{\\partial L}{\\partial q_i}=0\\quad\\Rightarrow\\quad\\frac{dp_i}{dt}=0\n",
        "$$\n",
        "\n",
        "\n",
        "For a system of particles, internal forces can exchange momentum among parts while total\n",
        "momentum remains constant. The practical balance law is\n",
        "\n",
        "\n",
        "$$\n",
        "\\frac{d\\mathbf P}{dt}=\\mathbf F_{\\mathrm{external}}\n",
        "$$\n",
        "\n",
        "\n",
        "Momentum conservation therefore depends on the chosen system boundary. A person walking\n",
        "inside a boat exchanges momentum with the boat; considering only the person hides the\n",
        "compensating momentum. Considering person, boat, and relevant expelled or incoming mass\n",
        "restores the appropriate balance.\n",
        "\n",
        "## Rotational symmetry and angular momentum\n",
        "\n",
        "If an isolated system's Lagrangian is invariant under continuous rotations about an\n",
        "axis, the corresponding angular-momentum component is conserved. Full rotational\n",
        "invariance gives conservation of the angular-momentum vector. For a particle about an\n",
        "origin,\n",
        "\n",
        "\n",
        "$$\n",
        "\\mathbf L=\\mathbf r\\times\\mathbf p\n",
        "$$\n",
        "\n",
        "\n",
        "and the balance law is\n",
        "\n",
        "\n",
        "$$\n",
        "\\frac{d\\mathbf L}{dt}=\\boldsymbol\\tau_{\\mathrm{external}}\n",
        "$$\n",
        "\n",
        "\n",
        "A central force points along\n",
        "$\\mathbf r$, so its torque about the\n",
        "force center is zero and angular momentum about that point is conserved. The result\n",
        "depends on the origin and on external torques. Angular momentum about one point need not\n",
        "equal angular momentum about another.\n",
        "\n",
        "In a central-force orbit, conserved angular momentum implies equal areas are swept in\n",
        "equal times. This connects rotational symmetry to Kepler's second law without requiring\n",
        "the orbit to be circular.\n",
        "\n",
        "## Continuous and discrete symmetries\n",
        "\n",
        "Translations and rotations can vary by an arbitrarily small parameter, so they are\n",
        "continuous. Reflection is usually discrete: there is no chain of infinitesimal\n",
        "reflections connecting it to the identity in ordinary space. A reflection symmetry can\n",
        "still constrain solutions and produce useful parity labels, but the elementary Noether\n",
        "correspondence above is specifically about continuous symmetries.\n",
        "\n",
        "Some transformations change the mathematical description while leaving every physical\n",
        "state unchanged. These gauge redundancies require special care; they are not simply\n",
        "ordinary motions through distinct physical configurations. This lesson uses mechanical\n",
        "translations and rotations, where the distinction is easier to see.\n",
        "\n",
        "## Conservation is a balance statement\n",
        "\n",
        "A conserved quantity remains constant only for the system to which the law applies. An\n",
        "open subsystem can gain energy, momentum, or angular momentum through its boundary. The\n",
        "more general accounting form is\n",
        "\n",
        "\n",
        "$$\n",
        "\\text{change inside}=\\text{transfer in}-\\text{transfer out}+\\text{sources}\n",
        "$$\n",
        "\n",
        "\n",
        "Friction does not destroy total energy. It transfers organized mechanical energy into\n",
        "thermal and internal forms. Mechanical energy alone decreases if those forms are outside\n",
        "the bookkeeping. Momentum can be transferred to Earth through friction or supports.\n",
        "Always name the system before claiming a violation."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-005",
      "metadata": {},
      "source": [
        "initial_momentum = 5.0\n",
        "impulse_in, impulse_out = 2.0, 0.5\n",
        "final_momentum = 6.5\n",
        "residual = final_momentum - initial_momentum - (impulse_in - impulse_out)\n",
        "print(f\"Momentum balance residual: {residual:.3g} kg m/s\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-006",
      "metadata": {},
      "source": [
        "The residual must have units and a scale. A fixed absolute tolerance can be too strict\n",
        "for large systems and too loose near zero, so combine physically justified absolute and\n",
        "relative tolerances.\n",
        "\n",
        "## Symmetry breaking\n",
        "\n",
        "Symmetry can be absent in the law, absent only in the environment, or present in the law\n",
        "but not in a chosen state. A uniform gravitational field selects a vertical direction\n",
        "and breaks full rotational symmetry. A circular bowl may have a rotationally symmetric\n",
        "potential while a ball resting at one off-center location does not share that symmetry.\n",
        "This last case is a property of the state, not necessarily of the governing law.\n",
        "\n",
        "Approximate symmetry can produce approximate conservation over a limited interval. A\n",
        "planet perturbed weakly by other planets may have orbital quantities that change slowly\n",
        "rather than remain exactly fixed. Report the scale and duration of the approximation\n",
        "instead of replacing \"approximately conserved\" with \"conserved.\"\n",
        "\n",
        "## Numerical conservation tests\n",
        "\n",
        "A continuous model can possess an exact invariant while its discrete update does not.\n",
        "Forward Euler, for example, generally adds energy to an ideal harmonic oscillator. A\n",
        "small invariant error over a short trace does not guarantee acceptable long-time\n",
        "behavior. Some geometric integrators preserve a modified structure and keep errors\n",
        "bounded without keeping the exact physical energy constant at every step.\n",
        "\n",
        "Test the physical law and the numerical method separately. Use an analytic trajectory\n",
        "when available, transform the initial data, and compare at matching physical times.\n",
        "Then reduce time step and spatial resolution independently. If symmetry and conservation\n",
        "residuals shrink at the expected rate, the discrepancy is likely discretization error.\n",
        "A residual that does not shrink can reveal inconsistent boundaries, a missing force, or\n",
        "a mistaken conserved quantity."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-007",
      "metadata": {},
      "source": [
        "for steps in [20, 40, 80]:\n",
        "    dt = 2.0 / steps\n",
        "    x, shifted_x = position.copy(), position + shift\n",
        "    for _ in range(steps):\n",
        "        x += dt * velocity\n",
        "        shifted_x += dt * velocity\n",
        "    print(steps, np.linalg.norm(shifted_x - (x + shift)))\n",
        "    assert np.allclose(shifted_x, x + shift)\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-008",
      "metadata": {},
      "source": [
        "Sampling can create false confidence. Measuring only once per period may hide oscillating\n",
        "energy error, and rounded output may conceal drift. Inspect the full-resolution internal\n",
        "values and report the maximum, final, and characteristic pattern of the residual.\n",
        "\n",
        "## A disciplined reasoning sequence\n",
        "\n",
        "When using symmetry to predict conservation, first state the action or equations and the\n",
        "system boundary. Name the continuous transformation and its parameter. Verify that the\n",
        "law, external fields, constraints, and boundary conditions have the claimed invariance.\n",
        "Then identify the corresponding quantity and confirm its balance equation.\n",
        "\n",
        "When checking computed data, do not infer the theorem backward from a nearly flat graph.\n",
        "A quantity may look constant over a short interval by coincidence or inadequate\n",
        "precision. Use the governing equations and symmetry argument first; use the numerical\n",
        "trace as verification.\n",
        "\n",
        "## Reliability checks\n",
        "\n",
        "- Specify whether the transformation acts on the law, the state, or both.\n",
        "- Transform initial and boundary conditions consistently.\n",
        "- Confirm that the symmetry is continuous before invoking Noether's theorem.\n",
        "- Distinguish invariance of the action from visual symmetry of a plotted solution.\n",
        "- Name the system boundary and every relevant external force or torque.\n",
        "- Separate total energy conservation from mechanical energy conservation.\n",
        "- Treat reference-level changes as conventions, not new physical transformations.\n",
        "- Track symmetry residuals separately from conservation residuals.\n",
        "- Refine numerical resolution and compare at fixed physical times.\n",
        "- Report approximate conservation with a scale, tolerance, and time interval.\n",
        "\n",
        "Symmetry gives conservation laws their structural explanation, while balance laws show\n",
        "how those quantities move across a boundary. Used together, they provide both a deep\n",
        "theoretical connection and a practical way to detect incomplete models, inconsistent\n",
        "conditions, and numerical drift.\n",
        "\n",
        "## A worked Python notebook\n",
        "\n",
        "A freely moving body reaches 7 metres before a constant change of coordinate origin is applied. The question for this calculation is precise: how does **shifted final position**\n",
        "change when we change **coordinate shift**, 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",
        "The shift changes position labels but leaves velocity and displacement unchanged. 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",
        "-5 to 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 coordinate shift, expressed in m. The output is\n",
        "shifted final position, expressed in m. 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) = q + 7\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 2 m, the expression gives 9 m. 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(\"7+q\", locals={\"q\": q})\n",
        "reference_input = 2.0\n",
        "reference_output = float(expression.subs(q, reference_input))\n",
        "print(\"Input:\", reference_input, \"m\")\n",
        "print(\"Predicted shifted final position:\", reference_output, \"m\")\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 m. The midpoint, at 0 m, gives\n",
        "7 m. The upper endpoint gives 12 m.\n",
        "Read these together with the assumptions: they describe different choices of coordinate shift\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([-5.0, 0.0, 5.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} m\")\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 coordinate shift; the vertical axis shows shifted final position. 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(-5.0, 5.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(\"Coordinate shift (m)\")\n",
        "ax.set_ylabel(\"Shifted final position (m)\")\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",
        "shifted final position change near the reference input? Its units are the output unit divided by\n",
        "the input unit. For this calculation, the derivative at 2 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) = 1\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 = 2.05\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, \"m\")\n",
        "print(\"Full expression:\", full_prediction, \"m\")\n",
        "print(\"Approximation difference:\", full_prediction - linear_prediction, \"m\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-016",
      "metadata": {},
      "source": [
        "Here the changed input is 2.05 m. The tangent estimate is\n",
        "9.05 m, while the full expression gives\n",
        "9.05 m. 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 = 10.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",
        "coordinate shift inside the stated interval, predict whether shifted final position 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: The shift changes position labels but leaves velocity and displacement unchanged. 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 m:\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(5.0) - evaluate(-5.0))\n",
        "for points in [101, 201, 401]:\n",
        "    grid = np.linspace(-5.0, 5.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 9.3, \"Conservation of Linear Momentum\"](https://openstax.org/books/university-physics-volume-1/pages/9-3-conservation-of-linear-momentum).\n",
        "- [OpenStax, *University Physics Volume 1*, Section 11.3, \"Conservation of Angular Momentum\"](https://openstax.org/books/university-physics-volume-1/pages/11-3-conservation-of-angular-momentum).\n",
        "- [MIT OpenCourseWare, *8.01SC Classical Mechanics*, Chapter 10, \"Momentum, System of Particles, and Conservation of Momentum\"](https://ocw.mit.edu/courses/8-01sc-classical-mechanics-fall-2016/resources/mit8_01scs22_chapter10/).\n",
        "- [MIT OpenCourseWare, *8.01SC Classical Mechanics*, Chapter 19, \"Angular Momentum\"](https://ocw.mit.edu/courses/8-01sc-classical-mechanics-fall-2016/resources/mit8_01scs22_chapter19/).\n",
        "- [MIT OpenCourseWare, *8.01SC Classical Mechanics*, Chapter 25, Section 25.3, \"Energy and Angular Momentum, Constants of the Motion\"](https://ocw.mit.edu/courses/8-01sc-classical-mechanics-fall-2016/resources/mit8_01scs22_chapter25/).\n",
        "- [Benjamin Crowell, *Light and Matter*, Chapters 4 and 14](https://open.umn.edu/opentextbooks/textbooks/light-and-matter).\n",
        "- [The Physics Hypertextbook, \"Conservation Laws\"](https://physics.info/conservation/)."
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.12"
    },
    "colab": {
      "name": "symmetry-and-conservation.ipynb",
      "provenance": []
    },
    "tirta": {
      "lesson": "https://tirta.co/a-byte-of-physics/symmetry-and-conservation",
      "source_sha256": "cab1f54e81d82d37ea62227e7070084b53d27c7debe44f98988f5254cf5ac6fe"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
