{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "markdown-000",
      "metadata": {},
      "source": [
        "# Wave packets\n",
        "\n",
        "[Read the lesson](https://tirta.co/a-byte-of-physics/wave-packets). 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 perfectly sinusoidal wave extends forever in space and time. It has a precise wave\n",
        "number and frequency, but it cannot represent a localized pulse or finite message. A wave\n",
        "packet combines a range of wave numbers with carefully related phases so that they add\n",
        "constructively in one region and mostly cancel elsewhere.\n",
        "\n",
        "## Localization requires multiple components\n",
        "\n",
        "A one-dimensional linear packet can be written as a continuous superposition\n",
        "\n",
        "\n",
        "$$\n",
        "\\psi(x,t)=\\frac{1}{2\\pi}\\int_{-\\infty}^{\\infty}\\widetilde{\\psi}(k,0)e^{i[kx-\\omega(k)t]}\\,dk\n",
        "$$\n",
        "\n",
        "\n",
        "The complex coefficient $\\widetilde{\\psi}(k,0)$\n",
        "sets the amplitude and phase of wave-number component\n",
        "$k$. The dispersion relation\n",
        "$\\omega(k)$\n",
        "sets how that component's phase develops.\n",
        "\n",
        "At a location where many phases line up, the sum is large. Far away, components point in\n",
        "different complex directions and largely cancel. The packet is therefore not a separate\n",
        "particle-like ingredient added to sinusoidal waves; it is the interference pattern made\n",
        "by them.\n",
        "\n",
        "## Two nearby waves reveal an envelope\n",
        "\n",
        "Add two equal waves with nearby wave numbers and angular frequencies:\n",
        "\n",
        "\n",
        "$$\n",
        "\\cos(k_1x-\\omega_1t)+\\cos(k_2x-\\omega_2t)=2\\cos\\left(\\frac{\\Delta k\\,x-\\Delta\\omega\\,t}{2}\\right)\\cos\\left(\\bar{k}x-\\bar{\\omega}t\\right)\n",
        "$$\n",
        "\n",
        "\n",
        "Here\n",
        "$\\Delta k=k_2-k_1$,\n",
        "$\\Delta\\omega=\\omega_2-\\omega_1$,\n",
        "$\\bar{k}=(k_1+k_2)/2$, and\n",
        "$\\bar{\\omega}=(\\omega_1+\\omega_2)/2$.\n",
        "The rapidly varying second cosine is the carrier. The slowly varying first cosine is its\n",
        "envelope.\n",
        "\n",
        "Holding the envelope phase constant gives its speed:\n",
        "\n",
        "\n",
        "$$\n",
        "v_{\\mathrm{envelope}}=\\frac{\\Delta\\omega}{\\Delta k}\n",
        "$$\n",
        "\n",
        "\n",
        "As the two components become arbitrarily close in wave number, this becomes group\n",
        "velocity:\n",
        "\n",
        "\n",
        "$$\n",
        "v_g=\\left.\\frac{d\\omega}{dk}\\right|_{k_0}\n",
        "$$\n",
        "\n",
        "\n",
        "The carrier crests move with phase velocity\n",
        "\n",
        "\n",
        "$$\n",
        "v_p=\\frac{\\omega(k_0)}{k_0}\n",
        "$$\n",
        "\n",
        "\n",
        "These velocities are equal only for special dispersion relations. A crest can move\n",
        "through an envelope without carrying the packet center along with it.\n",
        "\n",
        "## A Gaussian packet with defined widths\n",
        "\n",
        "Width statements are meaningless unless they say whether width belongs to amplitude,\n",
        "intensity, energy density, or probability density. One convenient normalized complex\n",
        "packet is\n",
        "\n",
        "\n",
        "$$\n",
        "\\psi(x,0)=\\frac{1}{(2\\pi\\sigma_x^2)^{1/4}}\\exp\\left[-\\frac{(x-x_0)^2}{4\\sigma_x^2}\\right]e^{ik_0(x-x_0)}\n",
        "$$\n",
        "\n",
        "\n",
        "With this definition, $|\\psi|^2$\n",
        "is a Gaussian whose standard deviation in position is\n",
        "$\\sigma_x$. Using the\n",
        "spatial transform convention in the previous lesson, its spectral squared magnitude is\n",
        "Gaussian with standard deviation\n",
        "$\\sigma_k$ and\n",
        "\n",
        "\n",
        "$$\n",
        "\\sigma_x\\sigma_k=\\frac12\n",
        "$$\n",
        "\n",
        "\n",
        "The central wave number $k_0$ controls\n",
        "the carrier spacing. The spectral width controls localization. Making\n",
        "$\\sigma_k$ four times\n",
        "larger makes $\\sigma_x$\n",
        "four times smaller under this definition.\n",
        "\n",
        "The real part may be drawn as a Gaussian envelope multiplying a cosine, but calculations\n",
        "should retain the complex packet or both quadratures. Taking only the real part changes\n",
        "some normalization and spectral bookkeeping because it introduces positive and negative\n",
        "wave-number components.\n",
        "\n",
        "## Spectral time evolution\n",
        "\n",
        "In a linear, time-independent medium, evolve every spectral component by a unit-magnitude\n",
        "phase:\n",
        "\n",
        "\n",
        "$$\n",
        "\\widetilde{\\psi}(k,t)=\\widetilde{\\psi}(k,0)e^{-i\\omega(k)t}\n",
        "$$\n",
        "\n",
        "\n",
        "For a lossless model this multiplication preserves\n",
        "$|\\widetilde{\\psi}(k,t)|$.\n",
        "The inverse transform then builds the new position-space packet."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-003",
      "metadata": {},
      "source": [
        "import numpy as np\n",
        "\n",
        "N, length = 1024, 100.0\n",
        "x = (np.arange(N) - N / 2) * length / N\n",
        "dx = length / N\n",
        "wave_numbers = 2 * np.pi * np.fft.fftfreq(N, d=dx)\n",
        "initial = np.exp(-(x**2) / 8) * np.exp(2j * x)\n",
        "spectrum = np.fft.fft(initial)\n",
        "frequency = wave_numbers**2 / 2  # Scaled dispersive model.\n",
        "packet = np.fft.ifft(spectrum * np.exp(-1j * frequency * 2.0))\n",
        "print(\"Peak location:\", x[np.argmax(abs(packet))])\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-004",
      "metadata": {},
      "source": [
        "This method keeps material physics in\n",
        "$\\omega(k)$ and numerical\n",
        "representation in the grid and transform. A loss model would also change spectral\n",
        "magnitudes and must be stated separately.\n",
        "\n",
        "## Translation in a nondispersive medium\n",
        "\n",
        "For a right-moving nondispersive relation\n",
        "$\\omega(k)=vk$, the phase\n",
        "factor combines with $e^{ikx}$\n",
        "to give $e^{ik(x-vt)}$. Therefore\n",
        "\n",
        "\n",
        "$$\n",
        "\\psi(x,t)=\\psi(x-vt,0)\n",
        "$$\n",
        "\n",
        "\n",
        "The entire ideal packet translates at speed $v$\n",
        "without changing shape. A numerical calculation may still broaden it because of grid\n",
        "dispersion or a dissipative interpolation method; that is numerical behavior, not\n",
        "physical dispersion.\n",
        "\n",
        "## Dispersion and packet spreading\n",
        "\n",
        "Near the central wave number, expand the dispersion relation:\n",
        "\n",
        "\n",
        "$$\n",
        "\\omega(k)\\approx\\omega_0+\\omega'_0(k-k_0)+\\frac12\\omega''_0(k-k_0)^2+\\cdots\n",
        "$$\n",
        "\n",
        "\n",
        "The constant term advances the overall phase. The first derivative\n",
        "$\\omega'_0$ moves the\n",
        "envelope at group velocity. The second derivative\n",
        "$\\omega''_0$ makes\n",
        "different parts of the spectrum accumulate nonlinear relative phase, usually broadening\n",
        "and chirping the packet.\n",
        "\n",
        "Group velocity is a local, narrow-band approximation. In strongly dispersive, absorptive,\n",
        "or reshaping media, the position of a packet maximum can behave strangely and need not\n",
        "equal the speed of information or energy. A true signal front is constrained by the full\n",
        "causal medium response, not by one derivative evaluated at\n",
        "$k_0$.\n",
        "\n",
        "## Measuring center and width\n",
        "\n",
        "For a nonnegative weight\n",
        "$w(x,t)=|\\psi(x,t)|^2$, define\n",
        "\n",
        "\n",
        "$$\n",
        "\\langle x\\rangle=\\frac{\\int xw\\,dx}{\\int w\\,dx},\\qquad \\sigma_x^2=\\frac{\\int(x-\\langle x\\rangle)^2w\\,dx}{\\int w\\,dx}\n",
        "$$\n",
        "\n",
        "\n",
        "For a quantum wavefunction, normalized\n",
        "$|\\psi|^2$ has a\n",
        "probability interpretation. For a classical displacement field, squared displacement is\n",
        "not generally the complete energy density. Use the actual kinetic and elastic energy\n",
        "when the desired center is an energy centroid.\n",
        "\n",
        "On a periodic numerical domain, ordinary coordinate averages fail when a packet straddles\n",
        "the wrap point. Use circular statistics or unwrap the packet around a tracked center.\n",
        "\n",
        "## Packet, pulse, and envelope are related but distinct\n",
        "\n",
        "A pulse is a disturbance localized in time, space, or both. A packet is a pulse described\n",
        "through a band of Fourier components. The envelope is a smooth curve used to characterize\n",
        "the packet's slowly varying amplitude. It is not normally another physical field added to\n",
        "the carrier. Multiplying a carrier by an envelope in position space corresponds to\n",
        "convolving their spectra, which is why stronger localization requires broader spectral\n",
        "content.\n",
        "\n",
        "An envelope is clearest when its bandwidth is small compared with its central wave number.\n",
        "Then several carrier oscillations fit beneath it and the split into “fast carrier” and\n",
        "“slow envelope” is useful. For a pulse containing only one or two oscillations, different\n",
        "envelope definitions can give noticeably different centers and widths. Report the\n",
        "definition used instead of treating the drawn outline as unique.\n",
        "\n",
        "Classical and quantum packets share Fourier mathematics but not every interpretation. A\n",
        "classical string displacement may be positive or negative, and its mechanical energy\n",
        "requires displacement derivatives and velocity. A quantum wavefunction is complex, and\n",
        "its squared magnitude is a probability density after normalization. A classical packet\n",
        "does not become a particle because it is localized, and a quantum packet is not a tiny\n",
        "classical wave blob following one definite path.\n",
        "\n",
        "Measurements also have finite bandwidth. A sensor records its own filtered version of the\n",
        "field, so a measured packet width can combine source width, medium dispersion, detector\n",
        "response, and sampling. Calibrate or model those stages before attributing all broadening\n",
        "to propagation.\n",
        "\n",
        "## Grid, domain, and boundary constraints\n",
        "\n",
        "With spatial spacing $\\Delta x$,\n",
        "the largest distinct wave-number magnitude is associated with the spatial Nyquist limit,\n",
        "approximately\n",
        "\n",
        "\n",
        "$$\n",
        "|k|\\le\\frac{\\pi}{\\Delta x}\n",
        "$$\n",
        "\n",
        "\n",
        "A carrier too close to this limit has too few samples per wavelength and is highly\n",
        "sensitive to numerical dispersion. The domain must also be several packet widths across.\n",
        "Because a DFT implies periodic boundaries, a packet leaving one side reappears on the\n",
        "other. That wraparound is correct for a ring and wrong for an intended open line."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-005",
      "metadata": {},
      "source": [
        "initial_norm = np.sum(abs(initial) ** 2) * dx\n",
        "assert 2.0 + 3 * 0.5 < 0.8 * np.pi / dx\n",
        "for time in [0.0, 1.0, 2.0]:\n",
        "    packet = np.fft.ifft(spectrum * np.exp(-1j * frequency * time))\n",
        "    norm = np.sum(abs(packet) ** 2) * dx\n",
        "    centre = np.sum(x * abs(packet) ** 2) * dx / norm\n",
        "    assert np.isclose(norm, initial_norm)\n",
        "    print(time, centre, norm)\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-006",
      "metadata": {},
      "source": [
        "## Verification\n",
        "\n",
        "Construct two Gaussian spectra with the same\n",
        "$k_0$ but spectral widths in a\n",
        "ratio of four. Their initial position widths should have the inverse ratio. Multiply the\n",
        "spectrum by $e^{-ikx_s}$\n",
        "and verify that the reconstructed packet shifts by\n",
        "$x_s$ without changing width or\n",
        "norm.\n",
        "\n",
        "Under $\\omega=vk$, the\n",
        "measured center should move linearly with slope\n",
        "$v$ and width should remain fixed\n",
        "up to numerical error. Under a relation with nonzero curvature, verify the predicted\n",
        "initial group velocity and observe convergence of width evolution as spatial resolution\n",
        "and domain size increase.\n",
        "\n",
        "Real wave packets can experience loss, nonlinear self-interaction, scattering, boundaries,\n",
        "and multiple dimensions. A quantum packet additionally requires a Hamiltonian,\n",
        "normalization, and measurement interpretation. The Fourier construction supplies the\n",
        "kinematics of localization; it does not by itself choose the physical medium.\n",
        "\n",
        "## A worked Python notebook\n",
        "\n",
        "Follow the standard deviation of a freely spreading minimum-uncertainty Gaussian with initial width one. The question for this calculation is precise: how does **Gaussian position width**\n",
        "change when we change **time**, 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 example uses mass and reduced Planck constant equal to one and an effectively unbounded domain. 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 5 scaled time units. 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, expressed in scaled time units. The output is\n",
        "Gaussian position width, expressed in scaled length units. 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) = \\sqrt{\\frac{q^{2}}{4} + 1}\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 scaled time units, the expression gives 1.41421 scaled length units. 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-007",
      "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(\"sqrt(1+q**2/4)\", locals={\"q\": q})\n",
        "reference_input = 2.0\n",
        "reference_output = float(expression.subs(q, reference_input))\n",
        "print(\"Input:\", reference_input, \"scaled time units\")\n",
        "print(\"Predicted Gaussian position width:\", reference_output, \"scaled length units\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-008",
      "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",
        "1 scaled length units. The midpoint, at 2.5 scaled time units, gives\n",
        "1.60078 scaled length units. The upper endpoint gives 2.69258 scaled length units.\n",
        "Read these together with the assumptions: they describe different choices of time\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-009",
      "metadata": {},
      "source": [
        "evaluate = sp.lambdify(q, expression, modules=\"numpy\")\n",
        "inputs = np.array([0.0, 2.5, 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(\n",
        "        f\"{input_value:.6g} scaled time units -> \"\n",
        "        f\"{output_value:.6g} scaled length units\"\n",
        "    )\n",
        "assert np.all(np.isfinite(outputs))\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-010",
      "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; the vertical axis shows Gaussian position width. 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-011",
      "metadata": {},
      "source": [
        "input_grid = np.linspace(0.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(\"Time (scaled time units)\")\n",
        "ax.set_ylabel(\"Gaussian position width (scaled length units)\")\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-012",
      "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",
        "Gaussian position width change near the reference input? Its units are the output unit divided by\n",
        "the input unit. For this calculation, the derivative at 2 scaled time units is\n",
        "0.353553 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) = \\frac{q}{4 \\sqrt{\\frac{q^{2}}{4} + 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-013",
      "metadata": {},
      "source": [
        "slope_expression = sp.diff(expression, q)\n",
        "slope_at_reference = float(slope_expression.subs(q, reference_input))\n",
        "changed_input = 2.025\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, \"scaled length units\")\n",
        "print(\"Full expression:\", full_prediction, \"scaled length units\")\n",
        "print(\n",
        "    \"Approximation difference:\",\n",
        "    full_prediction - linear_prediction,\n",
        "    \"scaled length units\",\n",
        ")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-014",
      "metadata": {},
      "source": [
        "Here the changed input is 2.025 scaled time units. The tangent estimate is\n",
        "1.42305 scaled length units, while the full expression gives\n",
        "1.42308 scaled length units. 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-015",
      "metadata": {},
      "source": [
        "input_span = 5.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-016",
      "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 inside the stated interval, predict whether Gaussian position width 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 example uses mass and reduced Planck constant equal to one and an effectively unbounded domain. 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 scaled length units:\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-017",
      "metadata": {},
      "source": [
        "slope_function = sp.lambdify(q, slope_expression, modules=\"numpy\")\n",
        "endpoint_change = float(evaluate(5.0) - evaluate(0.0))\n",
        "for points in [101, 201, 401]:\n",
        "    grid = np.linspace(0.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-018",
      "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*, wave packets, Fourier analysis, and group velocity](https://open.umn.edu/opentextbooks/textbooks/light-and-matter).\n",
        "- [Paul A. Tipler and Ralph A. Llewellyn, *Modern Physics*, wave and wave-packet discussions](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": "wave-packets.ipynb",
      "provenance": []
    },
    "tirta": {
      "lesson": "https://tirta.co/a-byte-of-physics/wave-packets",
      "source_sha256": "c24f0e30aebd415d7ff495210d8f74a67fb0cd0b5babea3dea66a0876bcabb54"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
