{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "markdown-000",
      "metadata": {},
      "source": [
        "# Dispersion\n",
        "\n",
        "[Read the lesson](https://tirta.co/a-byte-of-physics/dispersion). 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": [
        "Dispersion means that the relation between angular frequency and wave number is not simply\n",
        "one constant speed for every component. A localized packet contains many wave numbers.\n",
        "When their phases advance differently, the packet can broaden, compress, chirp, or change\n",
        "shape even in a perfectly linear medium.\n",
        "\n",
        "## A dispersion relation is the starting point\n",
        "\n",
        "A plane-wave component can be written\n",
        "\n",
        "\n",
        "$$\n",
        "y(x,t)=A\\cos(kx-\\omega t+\\phi)\n",
        "$$\n",
        "\n",
        "\n",
        "where $A$ is amplitude,\n",
        "$k$ is wave number,\n",
        "$\\omega$ is angular frequency, and\n",
        "$\\phi$ is phase. Substitution into the\n",
        "governing equation supplies an allowed relation\n",
        "\n",
        "\n",
        "$$\n",
        "\\omega=\\omega(k)\n",
        "$$\n",
        "\n",
        "\n",
        "The word “dispersion” sometimes refers to this relation itself and sometimes specifically\n",
        "to the packet reshaping produced when it is nonlinear in\n",
        "$k$. State which meaning is intended.\n",
        "\n",
        "For the ideal nondispersive wave equation,\n",
        "\n",
        "\n",
        "$$\n",
        "\\omega^2=v^2k^2\n",
        "$$\n",
        "\n",
        "\n",
        "On the positive-frequency, right-moving branch,\n",
        "$\\omega=vk$.\n",
        "Every positive wave-number component travels with the same speed\n",
        "$v$, so an ideal packet translates\n",
        "without changing shape.\n",
        "\n",
        "## Phase velocity and group velocity\n",
        "\n",
        "The phase of a single component is constant when\n",
        "$kx-\\omega t$ is constant. Its\n",
        "phase velocity is\n",
        "\n",
        "\n",
        "$$\n",
        "v_p=\\frac{\\omega}{k}\n",
        "$$\n",
        "\n",
        "\n",
        "Phase velocity follows a crest of a monochromatic component. A narrow packet's envelope\n",
        "moves approximately with group velocity\n",
        "\n",
        "\n",
        "$$\n",
        "v_g=\\frac{d\\omega}{dk}\n",
        "$$\n",
        "\n",
        "\n",
        "These are different mathematical questions: one uses the ratio from the origin to a point\n",
        "on the dispersion curve, while the other uses the curve's local slope. They agree for\n",
        "$\\omega=vk$ and generally\n",
        "differ for a curved relation.\n",
        "\n",
        "For two nearby components, group velocity comes directly from the envelope:\n",
        "\n",
        "\n",
        "$$\n",
        "v_{\\mathrm{envelope}}=\\frac{\\Delta\\omega}{\\Delta k}\\longrightarrow\\frac{d\\omega}{dk}\n",
        "$$\n",
        "\n",
        "\n",
        "The derivative approximation is most meaningful when the packet spectrum is narrow enough\n",
        "that one local slope represents most of its components.\n",
        "\n",
        "## A transparent cubic test relation\n",
        "\n",
        "A useful mathematical fixture is\n",
        "\n",
        "\n",
        "$$\n",
        "\\omega(k)=vk+\\alpha k^3\n",
        "$$\n",
        "\n",
        "\n",
        "Here $v$ has units of speed and\n",
        "$\\alpha$ has units that make\n",
        "$\\alpha k^3$ an angular frequency.\n",
        "The two velocities are\n",
        "\n",
        "\n",
        "$$\n",
        "v_p=v+\\alpha k^2,\\qquad v_g=v+3\\alpha k^2\n",
        "$$\n",
        "\n",
        "\n",
        "When $\\alpha=0$, both return\n",
        "exactly $v$. For positive\n",
        "$\\alpha$ and\n",
        "nonzero $k$, group velocity exceeds\n",
        "phase velocity in this fixture."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-003",
      "metadata": {},
      "source": [
        "import numpy as np\n",
        "\n",
        "k, base_speed, cubic = 2.0, 1.0, 0.1\n",
        "omega = base_speed * k + cubic * k**3\n",
        "phase_speed = omega / k\n",
        "group_speed = base_speed + 3 * cubic * k**2\n",
        "print(\"Phase and group speeds:\", phase_speed, group_speed)\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-004",
      "metadata": {},
      "source": [
        "At $k=0$, do not calculate phase velocity\n",
        "by dividing zero by zero. Use an analytic limit when it exists.\n",
        "\n",
        "## Physical examples\n",
        "\n",
        "Electromagnetic waves in ideal vacuum obey\n",
        "$\\omega=ck$\n",
        "and are nondispersive. In transparent matter, polarization responds differently at\n",
        "different frequencies, so the refractive index can depend on frequency. Phase speed then\n",
        "depends on frequency, and a broadband optical pulse can spread.\n",
        "\n",
        "Surface water waves provide a strongly visible example. In sufficiently deep water with\n",
        "gravity as the restoring influence and negligible surface tension,\n",
        "\n",
        "\n",
        "$$\n",
        "\\omega^2=gk\n",
        "$$\n",
        "\n",
        "\n",
        "so\n",
        "\n",
        "\n",
        "$$\n",
        "v_p=\\sqrt{\\frac{g}{k}},\\qquad v_g=\\frac12\\sqrt{\\frac{g}{k}}=\\frac12v_p\n",
        "$$\n",
        "\n",
        "\n",
        "Longer wavelengths have smaller $k$ and\n",
        "larger phase and group speeds in this limit. This formula does not apply to shallow water,\n",
        "where depth matters and long waves can be approximately nondispersive.\n",
        "\n",
        "Waveguides, lattices, plasmas, elastic beams, and quantum matter waves have their own\n",
        "relations. There is no universal statement that higher frequencies always move faster or\n",
        "slower; the curve must come from the governing model or measurement.\n",
        "\n",
        "## Measuring a dispersion curve\n",
        "\n",
        "A dispersion relation can be inferred by exciting several nearly monochromatic waves and\n",
        "measuring their spatial and temporal phase. At a fixed time, the phase change per unit\n",
        "distance estimates wave number. At a fixed position, the phase change per unit time\n",
        "estimates angular frequency. Pair these estimates for the same component; combining a\n",
        "frequency from one mode with a wave number from another produces a meaningless point.\n",
        "\n",
        "For sampled data, a two-dimensional Fourier transform can reveal power across temporal\n",
        "frequency and spatial wave number. Ridges in that spectrum trace the allowed branches.\n",
        "Finite duration broadens frequency estimates, finite length broadens wave-number estimates,\n",
        "and reflections can add an opposite-traveling branch. Windowing and sensor spacing should\n",
        "therefore be reported with the fitted curve.\n",
        "\n",
        "Uncertainty grows when a packet contains only a few carrier cycles or when attenuation\n",
        "removes it before much phase accumulates. Fit the relation over a region where the signal\n",
        "is resolved, then propagate measurement errors into the derived velocities. Differentiation\n",
        "amplifies noise, so a group-velocity estimate from a fitted smooth curve is often more\n",
        "stable than subtracting adjacent noisy points.\n",
        "\n",
        "Direct arrival-time measurements offer an independent check. Launch packets with several\n",
        "central wave numbers but comparable fractional bandwidth, measure their energy-centroid\n",
        "arrival at two positions, and compare the resulting speeds with the slope of the fitted\n",
        "dispersion relation. Agreement within stated uncertainty supports the narrow-band group\n",
        "interpretation. Disagreement may reveal reshaping, absorption, boundary contamination, or\n",
        "an incorrect branch assignment rather than a simple arithmetic error.\n",
        "\n",
        "## Why a packet spreads\n",
        "\n",
        "Expand the relation around the packet's central wave number\n",
        "$k_0$:\n",
        "\n",
        "\n",
        "$$\n",
        "\\omega(k)\\approx\\omega_0+\\omega'_0(k-k_0)+\\frac12\\omega''_0(k-k_0)^2+\\frac16\\omega'''_0(k-k_0)^3+\\cdots\n",
        "$$\n",
        "\n",
        "\n",
        "The constant term rotates the overall carrier phase. The first derivative transports the\n",
        "envelope at $v_g=\\omega'_0$.\n",
        "The second and higher derivatives change relative phases across the spectrum and therefore\n",
        "reshape the envelope. If the spectrum is broad, retaining only the second derivative may\n",
        "be inadequate."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-005",
      "metadata": {},
      "source": [
        "x = np.linspace(-20, 20, 512, endpoint=False)\n",
        "dx = x[1] - x[0]\n",
        "k_grid = 2 * np.pi * np.fft.fftfreq(len(x), d=dx)\n",
        "initial = np.exp(-x * x / 4) * np.exp(2j * x)\n",
        "spectrum = np.fft.fft(initial)\n",
        "omega = base_speed * k_grid + cubic * k_grid**3\n",
        "field = np.fft.ifft(spectrum * np.exp(-1j * omega * 2.0))\n",
        "assert np.isclose(np.sum(abs(field) ** 2), np.sum(abs(initial) ** 2))\n",
        "print(\"Peak location after 2 time units:\", x[np.argmax(abs(field))])\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-006",
      "metadata": {},
      "source": [
        "For a lossless real relation, every multiplier has magnitude one. Any loss of spectral\n",
        "magnitude would come from an added attenuation model or numerical error, not dispersion\n",
        "alone.\n",
        "\n",
        "## Group velocity is not always signal velocity\n",
        "\n",
        "In weakly dispersive, low-loss media, group velocity often tracks pulse energy and\n",
        "information well. In strongly absorptive or rapidly varying regions, a packet can reshape\n",
        "so severely that its maximum advances anomalously or group velocity exceeds\n",
        "$c$. This does not imply that a new\n",
        "causal signal outruns light. The signal front and the full causal response determine how\n",
        "new information propagates.\n",
        "\n",
        "Avoid announcing superluminal communication from one slope or one moving maximum. Record\n",
        "the medium's absorption, bandwidth, and how the arrival time was defined.\n",
        "\n",
        "## Numerical dispersion\n",
        "\n",
        "A numerical wave solver can be dispersive even when the physical equation is not. For the\n",
        "centered explicit finite-difference update of the one-dimensional wave equation, a sampled\n",
        "plane wave obeys\n",
        "\n",
        "\n",
        "$$\n",
        "\\sin^2\\left(\\frac{\\omega_{\\mathrm{num}}\\Delta t}{2}\\right)=r^2\\sin^2\\left(\\frac{k\\Delta x}{2}\\right),\\qquad r=\\frac{v\\Delta t}{\\Delta x}\n",
        "$$\n",
        "\n",
        "\n",
        "Except in special cases, the numerical angular frequency is not exactly\n",
        "$vk$. Short waves\n",
        "near the grid scale receive the largest phase-speed error. A smooth numerical packet can\n",
        "therefore spread even though the intended medium is nondispersive.\n",
        "\n",
        "Physical and numerical parameters must remain separate:"
      ]
    },
    {
      "cell_type": "code",
      "id": "code-007",
      "metadata": {},
      "source": [
        "speed, wave_number, courant = 1.0, 2.0, 0.5\n",
        "for dx in [0.2, 0.1, 0.05]:\n",
        "    dt = courant * dx / speed\n",
        "    numerical_omega = 2 / dt * np.arcsin(courant * np.sin(wave_number * dx / 2))\n",
        "    print(dx, \"frequency error:\", numerical_omega - speed * wave_number)\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-008",
      "metadata": {},
      "source": [
        "Refine space and time while holding the physical packet fixed. Numerical spreading should\n",
        "decrease toward the physical prediction. If changing grid spacing changes the claimed\n",
        "material dispersion, the calculation is conflating model and method.\n",
        "\n",
        "## Verification\n",
        "\n",
        "For any analytic relation, compare a numerical derivative with the known group velocity\n",
        "away from singular points. Repeat with several derivative step sizes: an excessively large\n",
        "step has truncation error, while an extremely small step can expose floating-point\n",
        "cancellation.\n",
        "\n",
        "Propagate a packet under $\\omega=vk$.\n",
        "Its center should move at $v$ and its\n",
        "width should stay constant in a spectral evolution. Propagate the same initial spectrum\n",
        "with a curved relation and measure center and variance. Reverse the sign of time; a\n",
        "lossless exact spectral phase update should return to its initial state within\n",
        "floating-point and transform error.\n",
        "\n",
        "Check units, branches, and signs. A relation written as\n",
        "$\\omega^2=F(k)$\n",
        "may have positive and negative frequency branches. Choosing one branch determines\n",
        "propagation convention. Complex frequencies or wave numbers represent growth or\n",
        "attenuation and require a different interpretation from the real lossless discussion\n",
        "here.\n",
        "\n",
        "## A worked Python notebook\n",
        "\n",
        "Use a declared cubic dispersion relation and compare phase and group speed. The question for this calculation is precise: how does **angular frequency**\n",
        "change when we change **wave number**, 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 is a transparent mathematical test relation; a real material needs its measured or derived dispersion law. 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.1 to 4 1/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 wave number, expressed in 1/m. The output is\n",
        "angular frequency, expressed in rad/s. The equation below uses the numerical values in those\n",
        "units. Any fixed coefficients therefore carry the units needed to make the relation\n",
        "consistent. A value supplied in another unit must be converted before it enters this\n",
        "expression.\n",
        "\n",
        "\n",
        "$$\n",
        "f(q) = 0.1 q^{3} + q\n",
        "$$\n",
        "\n",
        "\n",
        "This is a function of one changing input. It is not a statement that the physical\n",
        "system has only one variable. We deliberately hold the other inputs fixed so that one\n",
        "cause of variation is visible. Changing several inputs at once would make it harder\n",
        "to tell which change produced the output difference. Write down the held-fixed choices\n",
        "before trying a different experiment.\n",
        "\n",
        "At 2 1/m, the expression gives 2.8 rad/s. This is our\n",
        "reference calculation. It is a prediction of the stated example, not a new measurement.\n",
        "Its displayed digits help us compare implementations. They should not be read as a\n",
        "claim that physical inputs are known to six significant figures."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-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+0.1*q**3\", locals={\"q\": q})\n",
        "reference_input = 2.0\n",
        "reference_output = float(expression.subs(q, reference_input))\n",
        "print(\"Input:\", reference_input, \"1/m\")\n",
        "print(\"Predicted angular frequency:\", reference_output, \"rad/s\")\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",
        "0.1001 rad/s. The midpoint, at 2.05 1/m, gives\n",
        "2.91151 rad/s. The upper endpoint gives 10.4 rad/s.\n",
        "Read these together with the assumptions: they describe different choices of wave number\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.1, 2.05, 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} 1/m -> {output_value:.6g} rad/s\")\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 wave number; the vertical axis shows angular frequency. 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.1, 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(\"Wave number (1/m)\")\n",
        "ax.set_ylabel(\"Angular frequency (rad/s)\")\n",
        "ax.legend()\n",
        "ax.grid(alpha=0.25)\n",
        "fig.tight_layout()\n",
        "plt.show()\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-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",
        "angular frequency change near the reference input? Its units are the output unit divided by\n",
        "the input unit. For this calculation, the derivative at 2 1/m is\n",
        "2.2 in those ratio units. Locally, the output increases as the\n",
        "input increases. This statement is local; the sign or size of the slope can be different\n",
        "elsewhere on the curve.\n",
        "\n",
        "\n",
        "$$\n",
        "f'(q) = 0.3 q^{2} + 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.0195\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, \"rad/s\")\n",
        "print(\"Full expression:\", full_prediction, \"rad/s\")\n",
        "print(\"Approximation difference:\", full_prediction - linear_prediction, \"rad/s\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-016",
      "metadata": {},
      "source": [
        "Here the changed input is 2.0195 1/m. The tangent estimate is\n",
        "2.8429 rad/s, while the full expression gives\n",
        "2.84313 rad/s. If the two values are close, it means the chosen\n",
        "input change is small enough for this local approximation at this point. It does not\n",
        "mean the entire model is linear. If the slope is zero, a quadratic or higher-order term\n",
        "may supply the leading change instead.\n",
        "\n",
        "This is also the beginning of uncertainty propagation. If the input has a small stated\n",
        "standard uncertainty, the magnitude of the slope times that uncertainty estimates one\n",
        "contribution to output uncertainty. Do not automatically use the same rule for a wide\n",
        "interval, a discontinuity, a turning point with zero first derivative, or several\n",
        "correlated uncertain inputs. Those situations need more of the model than one slope.\n",
        "\n",
        "### Check the derivative with numerical differences\n",
        "\n",
        "We can estimate the same slope from values on either side of the reference point.\n",
        "Subtract the lower output from the upper output and divide by twice the input step.\n",
        "Parentheses are essential: the entire output difference must be divided by the entire\n",
        "input interval. Without them, Python can execute a different mathematical expression\n",
        "while still producing a plausible number.\n",
        "\n",
        "The calculation below uses three decreasing step sizes. Each estimate is compared with\n",
        "the symbolic derivative, so the reference is independent of the numerical difference\n",
        "formula. Near an endpoint, it is acceptable here to evaluate a small extension only\n",
        "because the displayed mathematical expression is smooth there; such a check does not\n",
        "assert that extrapolated values describe additional physical cases."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-017",
      "metadata": {},
      "source": [
        "input_span = 3.9\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",
        "wave number inside the stated interval, predict whether angular frequency 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 is a transparent mathematical test relation; a real material needs its measured or derived dispersion law. 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 rad/s:\n",
        "the input unit in the integration cancels the input unit in the denominator of the slope.\n",
        "\n",
        "This statement is about the mathematics of this particular relationship. It does not\n",
        "assign a new physical meaning to an arbitrary area under a graph. For example, an area\n",
        "under force versus distance represents work, while an area under a different pair of\n",
        "quantities may represent something else or have no standard name. Always carry the\n",
        "axis units through the calculation before naming an integral."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-019",
      "metadata": {},
      "source": [
        "slope_function = sp.lambdify(q, slope_expression, modules=\"numpy\")\n",
        "endpoint_change = float(evaluate(4.0) - evaluate(0.1))\n",
        "for points in [101, 201, 401]:\n",
        "    grid = np.linspace(0.1, 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",
        "\n",
        "- [Benjamin Crowell, *Light and Matter*, dispersion, wave packets, and group velocity](https://open.umn.edu/opentextbooks/textbooks/light-and-matter).\n",
        "- [Paul A. Tipler and Ralph A. Llewellyn, *Modern Physics*, matter-wave packets and dispersion](https://web.pdx.edu/~pmoeck/books/Tipler_Llewellyn.pdf).\n",
        "- [The Physics Hypertextbook, “Periodic Waves”](https://physics.info/waves-periodic/).\n",
        "- [Physics LibreTexts, *The Physics of Waves*, Chapter 10, “Signals and Fourier Analysis”](https://phys.libretexts.org/Bookshelves/Waves_and_Acoustics/The_Physics_of_Waves_%28Goergi%29/10%3A_Signals_and_Fourier_Analysis)."
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.12"
    },
    "colab": {
      "name": "dispersion.ipynb",
      "provenance": []
    },
    "tirta": {
      "lesson": "https://tirta.co/a-byte-of-physics/dispersion",
      "source_sha256": "9154b27d02680788dedc2e46da42f46299be1769ee06ceb1eb66525dfc3acbd8"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
