{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "markdown-000",
      "metadata": {},
      "source": [
        "# Piecewise motion models\n",
        "\n",
        "[Read the lesson](https://tirta.co/a-byte-of-physics/piecewise-motion-models). 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": [
        "Many journeys have distinct phases. A train accelerates, travels at nearly constant\n",
        "speed, and brakes. A thrown ball rises and falls under one acceleration but may follow a\n",
        "new rule after impact. A piecewise model assigns a relationship to each time interval\n",
        "and transfers the final state of one phase into the initial state of the next.\n",
        "\n",
        "## A three-phase journey\n",
        "\n",
        "Consider a vehicle moving along a straight track. Choose rightward as positive. It\n",
        "starts at rest at the origin, accelerates at\n",
        "$2.0\\,\\mathrm{m/s^2}$\n",
        "for four seconds, coasts for six seconds, and then brakes at\n",
        "$-4.0\\,\\mathrm{m/s^2}$\n",
        "until it stops two seconds later.\n",
        "\n",
        "The acceleration function is piecewise:\n",
        "\n",
        "\n",
        "$$\n",
        "a(t)=\\begin{cases}2.0\\,\\mathrm{m/s^2},&0\\le t<4\\,\\mathrm{s}\\\\0,&4\\le t<10\\,\\mathrm{s}\\\\-4.0\\,\\mathrm{m/s^2},&10\\le t\\le12\\,\\mathrm{s}\\end{cases}\n",
        "$$\n",
        "\n",
        "\n",
        "Half-open intervals assign each ordinary boundary time to exactly one branch. The\n",
        "physical values at a boundary are obtained from the continuous state, not from executing\n",
        "both acceleration rules simultaneously.\n",
        "\n",
        "## Compute the first handoff\n",
        "\n",
        "During the acceleration phase, with initial position and velocity zero,\n",
        "\n",
        "\n",
        "$$\n",
        "v(t)=2.0t,\\qquad x(t)=\\frac{1}{2}(2.0)t^2\n",
        "$$\n",
        "\n",
        "\n",
        "with SI units understood from the stated acceleration and time. At\n",
        "$t_1=4.0\\,\\mathrm{s}$,\n",
        "\n",
        "\n",
        "$$\n",
        "v_1=8.0\\,\\mathrm{m/s},\\qquad x_1=16.0\\,\\mathrm{m}\n",
        "$$\n",
        "\n",
        "\n",
        "These values are the initial conditions for coasting. The coast formula must not restart\n",
        "from the global origin.\n",
        "\n",
        "Define local elapsed time\n",
        "$\\tau_2=t-t_1$.\n",
        "Then the coast phase is\n",
        "\n",
        "\n",
        "$$\n",
        "v(t)=v_1,\\qquad x(t)=x_1+v_1\\tau_2\n",
        "$$\n",
        "\n",
        "\n",
        "At $t_2=10.0\\,\\mathrm{s}$,\n",
        "the coast has lasted six seconds, so\n",
        "\n",
        "\n",
        "$$\n",
        "v_2=8.0\\,\\mathrm{m/s},\\qquad x_2=64.0\\,\\mathrm{m}\n",
        "$$\n",
        "\n",
        "\n",
        "## Compute the braking phase\n",
        "\n",
        "Use local braking time\n",
        "$\\tau_3=t-t_2$. The final phase is\n",
        "\n",
        "\n",
        "$$\n",
        "v(t)=v_2-4.0\\tau_3,\\qquad x(t)=x_2+v_2\\tau_3-\\frac{1}{2}(4.0)\\tau_3^2\n",
        "$$\n",
        "\n",
        "\n",
        "At two seconds, velocity reaches zero and\n",
        "\n",
        "\n",
        "$$\n",
        "x_3=64.0+(8.0)(2.0)-\\frac{1}{2}(4.0)(2.0)^2=72.0\\,\\mathrm{m}\n",
        "$$\n",
        "\n",
        "\n",
        "The total distance equals the final position because velocity remained nonnegative\n",
        "throughout this example. That equality would fail if the vehicle reversed direction.\n",
        "\n",
        "## Translate the phase model vertically"
      ]
    },
    {
      "cell_type": "code",
      "id": "code-003",
      "metadata": {},
      "source": [
        "def phase_state(time_s):\n",
        "    if time_s < 0:\n",
        "        raise ValueError(\"Time must be at or after the start.\")\n",
        "    if time_s <= 4:\n",
        "        return 0.5 * 2 * time_s**2, 2 * time_s\n",
        "    if time_s <= 10:\n",
        "        return 16 + 8 * (time_s - 4), 8.0\n",
        "    braking_time = min(time_s - 10, 4)\n",
        "    return 64 + 8 * braking_time - braking_time**2, 8 - 2 * braking_time\n",
        "\n",
        "\n",
        "for time in [0, 4, 10, 12, 14, 16]:\n",
        "    position, velocity = phase_state(time)\n",
        "    print(f\"{time} s: {position:.1f} m, {velocity:.1f} m/s\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-004",
      "metadata": {},
      "source": [
        "The boundary states should be calculated once from the same rules used by the phases.\n",
        "Duplicating `16` and `64` as unrelated literals makes later parameter changes likely to\n",
        "break continuity."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-005",
      "metadata": {},
      "source": [
        "from dataclasses import dataclass\n",
        "\n",
        "\n",
        "@dataclass(frozen=True)\n",
        "class State:\n",
        "    position_metres: float\n",
        "    velocity_metres_per_second: float\n",
        "\n",
        "\n",
        "def advance_constant_acceleration(\n",
        "    state: State,\n",
        "    acceleration: float,\n",
        "    elapsed_time: float,\n",
        ") -> State:\n",
        "    return State(\n",
        "        position_metres=(\n",
        "            state.position_metres\n",
        "            + state.velocity_metres_per_second * elapsed_time\n",
        "            + 0.5 * acceleration * elapsed_time**2\n",
        "        ),\n",
        "        velocity_metres_per_second=(\n",
        "            state.velocity_metres_per_second + acceleration * elapsed_time\n",
        "        ),\n",
        "    )\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-006",
      "metadata": {},
      "source": [
        "A full implementation would use names that include units for acceleration and elapsed\n",
        "time too. The abbreviated parameters keep this helper readable beside the equations.\n",
        "\n",
        "## Continuity at a boundary\n",
        "\n",
        "At $t=t_1$, the left\n",
        "limit of position and the coast branch must both give\n",
        "$x_1$. The same must hold for\n",
        "velocity:\n",
        "\n",
        "\n",
        "$$\n",
        "x(t_1^-)=x(t_1^+)=x_1,\\qquad v(t_1^-)=v(t_1^+)=v_1\n",
        "$$\n",
        "\n",
        "\n",
        "Acceleration jumps from a positive value to zero. That idealized jump makes jerk, the\n",
        "time derivative of acceleration, undefined at the boundary. A real controller changes\n",
        "force over a finite interval. The piecewise model is adequate only when that transition\n",
        "detail is unimportant to the question.\n",
        "\n",
        "At the second boundary, position and velocity are again continuous while acceleration\n",
        "jumps. A test should evaluate just before, exactly at, and just after each boundary.\n",
        "Small tolerances may be required for floating-point results, but a large discontinuity\n",
        "must not be hidden by an arbitrary tolerance.\n",
        "\n",
        "## Local time prevents a common bug\n",
        "\n",
        "Substituting global time into the coast expression as\n",
        "$x=x_1+v_1t$\n",
        "would add ten seconds of coasting by the end of that phase instead of six. The result\n",
        "would jump at the first boundary. Each phase formula either needs local elapsed time or\n",
        "an algebraically equivalent global-time offset.\n",
        "\n",
        "Local time also improves numerical conditioning when global timestamps are very large\n",
        "but phase durations are small. Subtract the boundary time once, retain adequate\n",
        "precision, and document which clock the input uses.\n",
        "\n",
        "## Events may determine phases\n",
        "\n",
        "Not every phase duration is known beforehand. Braking may end when velocity reaches\n",
        "zero; a projectile phase may end when position crosses the ground. An event condition\n",
        "then determines the boundary.\n",
        "\n",
        "A time-stepping solver can step past the event. Clamping the state after overshoot makes\n",
        "the boundary time depend on step size and loses the remaining part of the step. A better\n",
        "solver locates the root within the interval, advances exactly to the event within a\n",
        "tolerance, applies the transition rule, and continues with any remaining time."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-007",
      "metadata": {},
      "source": [
        "velocity_m_per_s = 8.0\n",
        "braking_acceleration = -2.0\n",
        "requested_step_s = 6.0\n",
        "stopping_time_s = -velocity_m_per_s / braking_acceleration\n",
        "moving_time_s = min(requested_step_s, stopping_time_s)\n",
        "distance_m = (\n",
        "    velocity_m_per_s * moving_time_s + 0.5 * braking_acceleration * moving_time_s**2\n",
        ")\n",
        "final_velocity = max(0.0, velocity_m_per_s + braking_acceleration * moving_time_s)\n",
        "print(f\"Distance before stopping: {distance_m:.1f} m\")\n",
        "print(f\"Time at rest: {requested_step_s - moving_time_s:.1f} s\")\n",
        "assert final_velocity == 0.0\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-008",
      "metadata": {},
      "source": [
        "The event function, direction of crossing, and tolerance belong to the model's numerical\n",
        "contract.\n",
        "\n",
        "## Piecewise does not always mean discontinuous\n",
        "\n",
        "Piecewise definitions are often used simply because different formulas are convenient\n",
        "in different intervals. Position and several derivatives may remain continuous. Review\n",
        "each boundary and decide which quantities physics requires to match.\n",
        "\n",
        "An instantaneous collision may intentionally make velocity discontinuous while position\n",
        "stays continuous. A material interface may make one derivative discontinuous while a\n",
        "conserved flux remains continuous. Automatically requiring every field to match can be\n",
        "as wrong as ignoring boundaries entirely.\n",
        "\n",
        "## Checks for the full journey\n",
        "\n",
        "Useful checks include:\n",
        "\n",
        "- the initial branch reproduces the initial state;\n",
        "- adjacent branches agree on required state at every boundary;\n",
        "- local times are zero at their phase starts;\n",
        "- units remain consistent across all phases;\n",
        "- the final velocity is zero in the stated braking example;\n",
        "- integrating the acceleration changes velocity by the expected amount;\n",
        "- integrating velocity gives total displacement;\n",
        "- phase selection covers the domain once, with no gap or overlap;\n",
        "- event times remain stable when a numerical step is refined.\n",
        "\n",
        "A piecewise model is not a collection of isolated formulas. It is one trajectory whose\n",
        "handoffs carry physical state and whose boundary idealizations are explicit.\n",
        "\n",
        "## Derive boundary records instead of editing them\n",
        "\n",
        "Boundary records are derived state. If the first acceleration or duration changes, all\n",
        "later boundary positions and velocities must be recomputed in order. Editing a later\n",
        "boundary by hand can make the branches appear continuous at one displayed value while\n",
        "breaking the relationship between acceleration, velocity, and position.\n",
        "\n",
        "One reliable design builds an ordered list of phase definitions, then folds over it to\n",
        "produce start and end states. Each derived record stores its start time, duration,\n",
        "acceleration rule, and state at both ends. Evaluation first locates the relevant interval\n",
        "and then advances only from its stored start state.\n",
        "\n",
        "This representation also makes total checks easier. Summing phase durations must equal\n",
        "the modeled duration. Summing each phase's displacement must equal final position minus\n",
        "initial position. The change in velocity must equal the signed area under the complete\n",
        "acceleration-time function. If these disagree, the problem is in a phase rule, a handoff,\n",
        "or interval selection rather than in an unrelated rendering layer.\n",
        "\n",
        "For measured phase boundaries, retain timestamp uncertainty instead of pretending the\n",
        "switch happened at an exact grid point. That uncertainty can affect both the carried\n",
        "state and later event predictions.\n",
        "\n",
        "## A worked Python notebook\n",
        "\n",
        "The braking phase starts at 64 metres with speed 8 metres per second and acceleration minus 2 metres per second squared. The question for this calculation is precise: how does **position**\n",
        "change when we change **time within braking phase**, 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 branch ends after four seconds; extending it would make the stopped cart reverse direction. 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 4 s. 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 time within braking phase, expressed in s. The output is\n",
        "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^{2} + 8 q + 64\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 s, the expression gives 76 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(\"64+8*q-q**2\", locals={\"q\": q})\n",
        "reference_input = 2.0\n",
        "reference_output = float(expression.subs(q, reference_input))\n",
        "print(\"Input:\", reference_input, \"s\")\n",
        "print(\"Predicted 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",
        "64 m. The midpoint, at 2 s, gives\n",
        "76 m. The upper endpoint gives 80 m.\n",
        "Read these together with the assumptions: they describe different choices of time within braking phase\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([0.0, 2.0, 4.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} s -> {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 time within braking phase; the vertical axis shows 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(0.0, 4.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(\"Time within braking phase (s)\")\n",
        "ax.set_ylabel(\"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",
        "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 s is\n",
        "4 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) = 8 - 2 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 = 2.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, \"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.02 s. The tangent estimate is\n",
        "76.08 m, while the full expression gives\n",
        "76.0796 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 = 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",
        "time within braking phase inside the stated interval, predict whether 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: This branch ends after four seconds; extending it would make the stopped cart reverse direction. 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(4.0) - evaluate(0.0))\n",
        "for points in [101, 201, 401]:\n",
        "    grid = np.linspace(0.0, 4.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",
        "- [OpenStax, *University Physics Volume 1*, Section 3.4, \"Motion with Constant Acceleration\"](https://openstax.org/books/university-physics-volume-1/pages/3-4-motion-with-constant-acceleration).\n",
        "- [MIT OpenCourseWare, *8.01SC Classical Mechanics*, Chapter 4, \"One Dimensional Kinematics\"](https://ocw.mit.edu/courses/8-01sc-classical-mechanics-fall-2016/resources/mit8_01scs22_chapter4/).\n",
        "- [Benjamin Crowell, *Light and Matter*, Sections 3.4-3.6, varying and constant acceleration](https://open.umn.edu/opentextbooks/textbooks/light-and-matter).\n",
        "- [The Physics Hypertextbook, \"Kinematic Equations\"](https://physics.info/motion-equations/)."
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.12"
    },
    "colab": {
      "name": "piecewise-motion-models.ipynb",
      "provenance": []
    },
    "tirta": {
      "lesson": "https://tirta.co/a-byte-of-physics/piecewise-motion-models",
      "source_sha256": "72e8091c3f554dfe3bb53214d2c8a0e0897aef52bf43ef07cb9ca80c65373e40"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
