{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "markdown-000",
      "metadata": {},
      "source": [
        "# Interference\n",
        "\n",
        "[Read the lesson](https://tirta.co/a-byte-of-physics/interference). 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": [
        "Interference occurs when waves overlap and their amplitudes add. Intensity is calculated\n",
        "only after the fields have been combined. Adding intensities first discards relative phase\n",
        "and removes the mechanism that creates bright and dark fringes.\n",
        "\n",
        "Interference does not violate energy conservation. Regions of constructive interference\n",
        "receive more energy while regions of destructive interference receive less. Across a\n",
        "complete pattern, energy is redistributed according to the sources and boundaries.\n",
        "\n",
        "## Superposition of two waves\n",
        "\n",
        "At one observation point, let two monochromatic scalar components have the same angular\n",
        "frequency:\n",
        "\n",
        "\n",
        "$$\n",
        "E_1(t)=A_1\\cos(\\omega t+\\phi_1),\\qquad\n",
        "       E_2(t)=A_2\\cos(\\omega t+\\phi_2)\n",
        "$$\n",
        "\n",
        "\n",
        "Linear superposition gives\n",
        "\n",
        "\n",
        "$$\n",
        "E_{\\mathrm{total}}(t)=E_1(t)+E_2(t)\n",
        "$$\n",
        "\n",
        "\n",
        "The phase difference is\n",
        "\n",
        "\n",
        "$$\n",
        "\\Delta\\phi=\\phi_2-\\phi_1\n",
        "$$\n",
        "\n",
        "\n",
        "For equal amplitudes, trigonometric addition gives\n",
        "\n",
        "\n",
        "$$\n",
        "E_{\\mathrm{total}}\n",
        "       =2A\\cos\\left(\\frac{\\Delta\\phi}{2}\\right)\n",
        "        \\cos\\left(\\omega t+\n",
        "        \\frac{\\phi_1+\\phi_2}{2}\\right)\n",
        "$$\n",
        "\n",
        "\n",
        "The resultant amplitude depends on relative phase. At zero phase difference it is\n",
        "$2A$. At phase difference\n",
        "$\\pi$, it is zero for equal contributions.\n",
        "\n",
        "## Intensity formula\n",
        "\n",
        "Time-averaged intensity is proportional to squared field amplitude. For two mutually\n",
        "coherent contributions with compatible polarization,\n",
        "\n",
        "\n",
        "$$\n",
        "I=I_1+I_2+2\\sqrt{I_1I_2}\\cos\\Delta\\phi\n",
        "$$\n",
        "\n",
        "\n",
        "The last term is the interference term. If phase varies randomly much faster than the\n",
        "detector averaging time, its average cosine is zero and intensities add. Stable fringes\n",
        "therefore require sufficient temporal and spatial coherence.\n",
        "\n",
        "For equal individual intensities\n",
        "$I_1=I_2=I_0$,\n",
        "\n",
        "\n",
        "$$\n",
        "I=4I_0\\cos^2\\left(\\frac{\\Delta\\phi}{2}\\right)\n",
        "$$\n",
        "\n",
        "\n",
        "The bright maximum is four times one beam's intensity because the field amplitude doubles\n",
        "and intensity squares it. Comparing that maximum with the sum of two separate beam\n",
        "intensities requires remembering that dark regions compensate elsewhere.\n",
        "\n",
        "## Complex-amplitude method\n",
        "\n",
        "Represent a sinusoidal contribution by a complex phasor\n",
        "$\\tilde E_j=A_je^{i\\phi_j}$. Then\n",
        "\n",
        "\n",
        "$$\n",
        "\\tilde E_{\\mathrm{total}}\n",
        "       =\\sum_j\\tilde E_j,\n",
        "       \\qquad\n",
        "       I\\propto|\\tilde E_{\\mathrm{total}}|^2\n",
        "$$"
      ]
    },
    {
      "cell_type": "code",
      "id": "code-003",
      "metadata": {},
      "source": [
        "import numpy as np\n",
        "\n",
        "phases = np.array([0.0, np.pi / 2])\n",
        "amplitudes = np.array([1.0, 1.0])\n",
        "combined = np.sum(amplitudes * np.exp(1j * phases))\n",
        "intensity = abs(combined) ** 2\n",
        "print(\"Coherent relative intensity:\", intensity)\n",
        "print(\"Incoherent intensity sum:\", np.sum(amplitudes**2))\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-004",
      "metadata": {},
      "source": [
        "Group only mutually coherent and polarization-compatible contributions in the amplitude\n",
        "sum. Statistically independent groups contribute intensities after their internal\n",
        "coherent sums are evaluated.\n",
        "\n",
        "## Path difference and phase\n",
        "\n",
        "For waves of vacuum or medium wavelength\n",
        "$\\lambda$, a geometric path difference\n",
        "$\\Delta L$ produces phase difference\n",
        "\n",
        "\n",
        "$$\n",
        "\\Delta\\phi=\\frac{2\\pi}{\\lambda}\\Delta L+\\Delta\\phi_0\n",
        "$$\n",
        "\n",
        "\n",
        "The term $\\Delta\\phi_0$ includes\n",
        "source and interface phase changes. Constructive interference occurs when total phase\n",
        "difference is an integer multiple of\n",
        "$2\\pi$. Destructive interference for\n",
        "equal amplitudes occurs at an odd multiple of $\\pi$.\n",
        "\n",
        "Equivalent path conditions, when there is no extra phase shift, are\n",
        "\n",
        "\n",
        "$$\n",
        "\\Delta L=m\\lambda\\quad\\text{for maxima}\n",
        "$$\n",
        "\n",
        "\n",
        "and\n",
        "\n",
        "\n",
        "$$\n",
        "\\Delta L=\\left(m+\\frac{1}{2}\\right)\\lambda\n",
        "       \\quad\\text{for minima}\n",
        "$$\n",
        "\n",
        "\n",
        "## Young's double slit\n",
        "\n",
        "Two narrow coherent slits separated by distance\n",
        "$d$ produce a path difference at screen\n",
        "angle $\\theta$ of\n",
        "\n",
        "\n",
        "$$\n",
        "\\Delta L=d\\sin\\theta\n",
        "$$\n",
        "\n",
        "\n",
        "Bright fringes satisfy\n",
        "\n",
        "\n",
        "$$\n",
        "d\\sin\\theta_m=m\\lambda\n",
        "$$\n",
        "\n",
        "\n",
        "and ideal equal-amplitude dark fringes satisfy\n",
        "\n",
        "\n",
        "$$\n",
        "d\\sin\\theta_m\n",
        "       =\\left(m+\\frac{1}{2}\\right)\\lambda\n",
        "$$\n",
        "\n",
        "\n",
        "For a distant screen a distance $L$ away\n",
        "and small angles, $\\sin\\theta\\approx\\tan\\theta\\approx y/L$.\n",
        "The bright-fringe positions are approximately\n",
        "\n",
        "\n",
        "$$\n",
        "y_m\\approx\\frac{m\\lambda L}{d}\n",
        "$$\n",
        "\n",
        "\n",
        "The spacing between neighboring bright fringes is\n",
        "\n",
        "\n",
        "$$\n",
        "\\Delta y\\approx\\frac{\\lambda L}{d}\n",
        "$$\n",
        "\n",
        "\n",
        "Longer wavelength or greater screen distance increases spacing; greater slit separation\n",
        "decreases it.\n",
        "\n",
        "## Worked fringe spacing\n",
        "\n",
        "Let $\\lambda=600\\ \\mathrm{nm}$,\n",
        "$L=2.0\\ \\mathrm m$, and\n",
        "$d=0.50\\ \\mathrm{mm}$.\n",
        "Then\n",
        "\n",
        "\n",
        "$$\n",
        "\\Delta y\n",
        "       =\\frac{(600\\times10^{-9}\\ \\mathrm m)(2.0\\ \\mathrm m)}\n",
        "              {0.50\\times10^{-3}\\ \\mathrm m}\n",
        "       =2.4\\times10^{-3}\\ \\mathrm m\n",
        "$$\n",
        "\n",
        "\n",
        "The neighboring bright fringes are about\n",
        "$2.4\\ \\mathrm{mm}$ apart.\n",
        "\n",
        "## Finite slit width creates an envelope\n",
        "\n",
        "Real slits have width $a$. Each slit\n",
        "diffracts, so the two-slit interference fringes are multiplied by a single-slit\n",
        "diffraction envelope. For identical narrow rectangular slits,\n",
        "\n",
        "\n",
        "$$\n",
        "I(\\theta)=I_{\\max}\n",
        "       \\left(\\frac{\\sin\\beta}{\\beta}\\right)^2\n",
        "       \\cos^2\\alpha\n",
        "$$\n",
        "\n",
        "\n",
        "where\n",
        "\n",
        "\n",
        "$$\n",
        "\\beta=\\frac{\\pi a\\sin\\theta}{\\lambda},\n",
        "       \\qquad\n",
        "       \\alpha=\\frac{\\pi d\\sin\\theta}{\\lambda}\n",
        "$$\n",
        "\n",
        "\n",
        "Some nominal interference maxima can disappear where the diffraction envelope is zero.\n",
        "A model that treats each finite slit as a point misses this modulation.\n",
        "\n",
        "## Thin-film phase changes\n",
        "\n",
        "Light reflected from the front and back surfaces of a thin film can interfere. The optical\n",
        "path difference for a film of thickness $t$\n",
        "and index $n$ is approximately\n",
        "$2nt$ at\n",
        "normal incidence. Reflection from a boundary to a higher-index medium adds a phase shift\n",
        "of pi; reflection toward a lower-index medium does not.\n",
        "\n",
        "Therefore thin-film bright and dark conditions cannot be selected from\n",
        "$2nt$ alone. Count the\n",
        "reflection phase reversals first. Coatings use this interference to enhance or suppress\n",
        "reflection over selected wavelengths and angles.\n",
        "\n",
        "## Coherence and visibility\n",
        "\n",
        "Temporal coherence limits the path difference over which a stable phase relation remains.\n",
        "A narrow spectral bandwidth has a longer coherence time and length. Spatial coherence\n",
        "describes phase correlation across different parts of an extended source; a large\n",
        "incoherent source can wash out double-slit fringes.\n",
        "\n",
        "Fringe visibility is\n",
        "\n",
        "\n",
        "$$\n",
        "\\mathcal V\n",
        "       =\\frac{I_{\\max}-I_{\\min}}\n",
        "              {I_{\\max}+I_{\\min}}\n",
        "$$\n",
        "\n",
        "\n",
        "Unequal amplitudes reduce visibility even for perfect coherence, and orthogonal\n",
        "polarizations do not produce the same scalar interference term at an ordinary detector.\n",
        "\n",
        "## Energy is redistributed, not destroyed\n",
        "\n",
        "At a dark fringe, the field contributions cancel locally, but energy has not disappeared\n",
        "from the experiment. The sources and apertures determine an angular distribution in which\n",
        "neighboring bright regions carry more energy than they would without interference. A\n",
        "complete calculation integrates intensity across the observation surface and includes\n",
        "energy that may be reflected, absorbed, or sent outside the measured window.\n",
        "\n",
        "This point prevents a tempting but incorrect bookkeeping method. One cannot assign a\n",
        "fixed parcel of energy from each slit to each screen position and then say the parcels\n",
        "annihilate at a dark fringe. The wave propagates as one combined field after the slits.\n",
        "Energy flow depends on that total field and its magnetic partner, not on two separately\n",
        "detectable classical paths at the same point.\n",
        "\n",
        "The same caution applies to finite numerical domains. A computed screen may show fewer\n",
        "total counts simply because its edges exclude wide-angle fringes or because the source\n",
        "normalization changed with aperture width. Normalize the incident power consistently,\n",
        "keep the physical screen size fixed, and integrate at sufficient resolution before using\n",
        "total detected intensity as a conservation check.\n",
        "\n",
        "Destructive interference can be complete only when the relevant field components have\n",
        "equal amplitude, compatible polarization, stable coherence, and opposite phase at the\n",
        "observation point. If amplitudes differ, the minimum retains the squared difference of\n",
        "their field magnitudes. If polarizations are perpendicular, a polarization-insensitive\n",
        "detector adds the separate intensities and no ordinary fringe contrast appears. These\n",
        "conditions explain why “out of phase” alone is not enough to guarantee darkness.\n",
        "\n",
        "Interference also depends on what the detector averages. A detector that resolves neither\n",
        "optical periods nor rapid phase noise reports a time average. Two sources with slightly\n",
        "different frequencies produce a phase difference that changes in time, leading to beats\n",
        "or washed-out fringes depending on detector bandwidth and exposure. Measurement timing is\n",
        "therefore part of the physical problem, not only a display setting.\n",
        "\n",
        "## Verification and limits\n",
        "\n",
        "Equal amplitudes in phase must produce doubled amplitude and fourfold peak intensity.\n",
        "Equal amplitudes separated by pi must cancel in the ideal scalar model. Swapping the two\n",
        "paths changes the sign of phase difference but not intensity. Double-slit fringe spacing\n",
        "must scale with wavelength and screen distance and inversely with slit separation.\n",
        "\n",
        "The formulas assume linear waves, stable coherence, ideal geometry, and a detector that\n",
        "averages many optical cycles. Finite source size, bandwidth, polarization, slit width,\n",
        "material dispersion, absorption, scattering, detector resolution, and vibration can\n",
        "reduce or reshape fringes. At very low light, detection events are discrete, but their\n",
        "probability distribution still builds the interference pattern.\n",
        "\n",
        "## A worked Python notebook\n",
        "\n",
        "Add two coherent complex amplitudes of magnitude one and vary their phase difference. The question for this calculation is precise: how does **relative intensity of equal beams**\n",
        "change when we change **relative 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",
        "The beams must overlap with compatible polarization and maintain a stable relative phase. 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 6.28319 rad. 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 relative phase, expressed in rad. The output is\n",
        "relative intensity of equal beams, expressed in dimensionless. 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) = 2 \\cos{\\left(q \\right)} + 2\n",
        "$$\n",
        "\n",
        "\n",
        "This is a function of one changing input. It is not a statement that the physical\n",
        "system has only one variable. We deliberately hold the other inputs fixed so that one\n",
        "cause of variation is visible. Changing several inputs at once would make it harder\n",
        "to tell which change produced the output difference. Write down the held-fixed choices\n",
        "before trying a different experiment.\n",
        "\n",
        "At 1.5708 rad, the expression gives 2 dimensionless. 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-005",
      "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(\"2+2*cos(q)\", locals={\"q\": q})\n",
        "reference_input = 1.5707963267948966\n",
        "reference_output = float(expression.subs(q, reference_input))\n",
        "print(\"Input:\", reference_input, \"rad\")\n",
        "print(\"Predicted relative intensity of equal beams:\", reference_output, \"dimensionless\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-006",
      "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",
        "4 dimensionless. The midpoint, at 3.14159 rad, gives\n",
        "0 dimensionless. The upper endpoint gives 4 dimensionless.\n",
        "Read these together with the assumptions: they describe different choices of relative 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-007",
      "metadata": {},
      "source": [
        "evaluate = sp.lambdify(q, expression, modules=\"numpy\")\n",
        "inputs = np.array([0.0, 3.141592653589793, 6.283185307179586])\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} rad -> {output_value:.6g} dimensionless\")\n",
        "assert np.all(np.isfinite(outputs))\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-008",
      "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 relative phase; the vertical axis shows relative intensity of equal beams. 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-009",
      "metadata": {},
      "source": [
        "input_grid = np.linspace(0.0, 6.283185307179586, 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(\"Relative phase (rad)\")\n",
        "ax.set_ylabel(\"Relative intensity of equal beams (dimensionless)\")\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-010",
      "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",
        "relative intensity of equal beams change near the reference input? Its units are the output unit divided by\n",
        "the input unit. For this calculation, the derivative at 1.5708 rad is\n",
        "-2 in those ratio units. Locally, the output decreases 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) = - 2 \\sin{\\left(q \\right)}\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-011",
      "metadata": {},
      "source": [
        "slope_expression = sp.diff(expression, q)\n",
        "slope_at_reference = float(slope_expression.subs(q, reference_input))\n",
        "changed_input = 1.6022122533307945\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, \"dimensionless\")\n",
        "print(\"Full expression:\", full_prediction, \"dimensionless\")\n",
        "print(\"Approximation difference:\", full_prediction - linear_prediction, \"dimensionless\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-012",
      "metadata": {},
      "source": [
        "Here the changed input is 1.60221 rad. The tangent estimate is\n",
        "1.93717 dimensionless, while the full expression gives\n",
        "1.93718 dimensionless. 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-013",
      "metadata": {},
      "source": [
        "input_span = 6.283185307179586\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-014",
      "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",
        "relative phase inside the stated interval, predict whether relative intensity of equal beams 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 beams must overlap with compatible polarization and maintain a stable relative phase. 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 dimensionless:\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-015",
      "metadata": {},
      "source": [
        "slope_function = sp.lambdify(q, slope_expression, modules=\"numpy\")\n",
        "endpoint_change = float(evaluate(6.283185307179586) - evaluate(0.0))\n",
        "for points in [101, 201, 401]:\n",
        "    grid = np.linspace(0.0, 6.283185307179586, 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-016",
      "metadata": {},
      "source": [
        "The trapezoidal rule joins neighbouring slope samples with straight segments and adds\n",
        "their signed areas. A negative contribution remains negative; replacing every slope\n",
        "by its magnitude would calculate a different quantity. Increasing the sample count\n",
        "provides a practical refinement check. If the values do not settle toward the endpoint\n",
        "difference, first inspect the interval, singularities, and array ordering.\n",
        "\n",
        "Do not conclude that two agreeing calculations prove the model is physically complete.\n",
        "Both use the same selected relationship, so an omitted effect would be omitted from\n",
        "both. Their agreement is evidence that the numerical tools implement that relationship\n",
        "consistently. Comparing with an independent experiment or a more appropriate physical\n",
        "model is a separate test.\n",
        "\n",
        "Keep this comparison in the notebook when you change the expression. It is particularly\n",
        "useful after adding a coefficient, changing a sign convention, or converting an input\n",
        "unit. A code cell that produces a smooth graph can conceal these mistakes; a second\n",
        "calculation of the same output change gives you another place to notice them.\n",
        "\n",
        "## Sources\n",
        "\n",
        "- [OpenStax, *University Physics Volume 3*, Chapter 3, “Interference”](https://openstax.org/books/university-physics-volume-3/pages/3-introduction).\n",
        "- [OpenStax, *University Physics Volume 3*](https://openstax.org/details/books/university-physics-volume-3).\n",
        "- [Benjamin Crowell, *Light and Matter*](https://open.umn.edu/opentextbooks/textbooks/light-and-matter).\n",
        "- [Ralph A. Llewellyn and Paul A. Tipler, *Modern Physics*](https://web.pdx.edu/~pmoeck/books/Tipler_Llewellyn.pdf).\n",
        "- [Physics LibreTexts, “Optics”](https://phys.libretexts.org/Bookshelves/Optics)."
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.12"
    },
    "colab": {
      "name": "interference.ipynb",
      "provenance": []
    },
    "tirta": {
      "lesson": "https://tirta.co/a-byte-of-physics/interference",
      "source_sha256": "e2490f93bf65af519463e1155d4e948933c8db02bcd32e1e216d4b22aa1e9c6b"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
