{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "markdown-000",
      "metadata": {},
      "source": [
        "# Electromagnetic induction\n",
        "\n",
        "[Read the lesson](https://tirta.co/a-byte-of-physics/electromagnetic-induction). 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 changing magnetic flux through a loop produces an electromotive force, or emf. The\n",
        "word “force” is historical: emf is measured in volts and represents energy transferred\n",
        "per unit charge around a circuit. The change can come from a changing magnetic field, a\n",
        "changing loop area, a rotating loop, or motion of a conductor through a field.\n",
        "\n",
        "Induction is directional. A loop must have an oriented surface normal and a compatible\n",
        "positive traversal direction. Reversing both conventions changes the signs used in the\n",
        "calculation but not the physical prediction.\n",
        "\n",
        "## Magnetic flux\n",
        "\n",
        "Magnetic flux through an oriented surface $S$\n",
        "is\n",
        "\n",
        "\n",
        "$$\n",
        "\\Phi_B=\\int_S\\mathbf B\\cdot d\\mathbf A\n",
        "$$\n",
        "\n",
        "\n",
        "The area vector points along the chosen normal. Only the magnetic-field component normal\n",
        "to the surface contributes. For a uniform field across a flat loop,\n",
        "\n",
        "\n",
        "$$\n",
        "\\Phi_B=BA\\cos\\theta\n",
        "$$\n",
        "\n",
        "\n",
        "The angle $\\theta$\n",
        "is between the magnetic field and the surface normal, not between the field and the\n",
        "plane. Flux is greatest in magnitude when the field is perpendicular to the plane and\n",
        "zero when the field lies in the plane.\n",
        "\n",
        "The SI unit of magnetic flux is the weber:\n",
        "\n",
        "\n",
        "$$\n",
        "1\\ \\mathrm{Wb}=1\\ \\mathrm{T\\,m^2}=1\\ \\mathrm{V\\,s}\n",
        "$$\n",
        "\n",
        "\n",
        "Reversing the normal reverses signed flux. It does not reverse the magnetic field or\n",
        "change the amount of physical field passing through the surface.\n",
        "\n",
        "## Faraday's law\n",
        "\n",
        "For one conducting loop, Faraday's law is\n",
        "\n",
        "\n",
        "$$\n",
        "\\mathcal E=-\\frac{d\\Phi_B}{dt}\n",
        "$$\n",
        "\n",
        "\n",
        "For a tightly wound coil of $N$\n",
        "identical turns linking the same flux,\n",
        "\n",
        "\n",
        "$$\n",
        "\\mathcal E=-N\\frac{d\\Phi_B}{dt}\n",
        "$$\n",
        "\n",
        "\n",
        "More generally, use the derivative of total flux linkage rather than multiplying by\n",
        "$N$ when different turns link different\n",
        "amounts of flux.\n",
        "\n",
        "The negative sign is Lenz's law. The induced response has the direction that opposes the\n",
        "change in magnetic flux. It opposes the change, not necessarily the original field. If\n",
        "positive flux is increasing, the induced field points in the negative-normal direction.\n",
        "If positive flux is decreasing, the induced field points in the positive-normal\n",
        "direction in an attempt to sustain it.\n",
        "\n",
        "## Choosing signs without guessing\n",
        "\n",
        "Choose a surface normal. Use the right-hand rule to define positive traversal: curled\n",
        "fingers follow the loop when the thumb follows the normal. Compute signed flux with that\n",
        "normal, differentiate it, and apply the negative sign. A positive emf then points along\n",
        "the chosen traversal; a negative result points opposite it."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-003",
      "metadata": {},
      "source": [
        "import sympy as sp\n",
        "\n",
        "t = sp.Symbol(\"t\", real=True)\n",
        "turns, area = 100, sp.Rational(1, 100)\n",
        "field = sp.Rational(1, 10) * sp.cos(2 * t)\n",
        "flux = area * field\n",
        "emf = -turns * sp.diff(flux, t)\n",
        "print(\"Induced emf with positive loop normal along B:\", emf)\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-004",
      "metadata": {},
      "source": [
        "This procedure works for either direction of field change. It avoids adding a second\n",
        "informal sign reversal after “using Lenz's law.”\n",
        "\n",
        "## A changing uniform field\n",
        "\n",
        "Suppose a single flat loop of area\n",
        "$0.020\\ \\mathrm{m^2}$\n",
        "has its normal aligned with a uniform magnetic field. If the field increases from\n",
        "$0.10\\ \\mathrm T$ to\n",
        "$0.50\\ \\mathrm T$ in\n",
        "$0.20\\ \\mathrm s$, the average\n",
        "emf is\n",
        "\n",
        "\n",
        "$$\n",
        "\\mathcal E_{\\mathrm{avg}}\n",
        "       =-\\frac{A\\Delta B}{\\Delta t}\n",
        "       =-\\frac{(0.020\\ \\mathrm{m^2})(0.40\\ \\mathrm T)}\n",
        "                    {0.20\\ \\mathrm s}\n",
        "       =-0.040\\ \\mathrm V\n",
        "$$\n",
        "\n",
        "\n",
        "The magnitude is forty millivolts. The negative sign means the emf points opposite the\n",
        "chosen positive traversal. A ten-turn coil with identical linkage would produce ten times\n",
        "the emf magnitude.\n",
        "\n",
        "## Rotating loop and generator emf\n",
        "\n",
        "A loop of area $A$ rotating at constant angular\n",
        "speed $\\omega$ in a uniform field can have\n",
        "\n",
        "\n",
        "$$\n",
        "\\Phi_B(t)=BA\\cos(\\omega t)\n",
        "$$\n",
        "\n",
        "\n",
        "Faraday's law gives\n",
        "\n",
        "\n",
        "$$\n",
        "\\mathcal E(t)=NBA\\omega\\sin(\\omega t)\n",
        "$$\n",
        "\n",
        "\n",
        "The emf is zero when flux is momentarily at a maximum or minimum because its rate of\n",
        "change is zero. The emf magnitude is greatest when flux passes through zero most rapidly.\n",
        "Mechanical work maintains the rotation against electromagnetic torque when power is\n",
        "delivered to a load; energy is converted rather than created.\n",
        "\n",
        "## Motional emf\n",
        "\n",
        "Charges in a conductor moving through a magnetic field experience magnetic force. For a\n",
        "conductor moving with local velocity $\\mathbf u$,\n",
        "the motional contribution around a circuit is\n",
        "\n",
        "\n",
        "$$\n",
        "\\mathcal E\n",
        "       =\\oint\\left(\\mathbf u\\times\\mathbf B\\right)\n",
        "       \\cdot d\\boldsymbol\\ell\n",
        "$$\n",
        "\n",
        "\n",
        "For a straight rod of length $\\ell$ moving\n",
        "perpendicular to both its length and a uniform magnetic field,\n",
        "\n",
        "\n",
        "$$\n",
        "|\\mathcal E|=B\\ell u\n",
        "$$\n",
        "\n",
        "\n",
        "The sign follows from the direction of\n",
        "$\\mathbf u\\times\\mathbf B$\n",
        "and the chosen path orientation. Charges separate until the electric force balances the\n",
        "magnetic deflection in an open rod. If the rod completes a conducting circuit, a current\n",
        "can flow and magnetic forces oppose the externally driven motion.\n",
        "\n",
        "## Flux rule for changing and moving circuits\n",
        "\n",
        "For a circuit that may move or deform, the compact flux rule remains\n",
        "\n",
        "\n",
        "$$\n",
        "\\mathcal E=-\\frac{d}{dt}\n",
        "       \\int_{S(t)}\\mathbf B\\cdot d\\mathbf A\n",
        "$$\n",
        "\n",
        "\n",
        "The total derivative includes changes in the field and changes in the surface. Care is\n",
        "needed because a time-varying magnetic field creates a circulating electric field, while\n",
        "motion through a magnetic field produces magnetic force on charges in the conductor.\n",
        "Both can contribute to the measured emf.\n",
        "\n",
        "## Induced electric fields are nonconservative\n",
        "\n",
        "A changing magnetic field produces an electric field even where there is no wire.\n",
        "Maxwell–Faraday's equation in integral form is\n",
        "\n",
        "\n",
        "$$\n",
        "\\oint_C\\mathbf E\\cdot d\\boldsymbol\\ell\n",
        "       =-\\frac{d}{dt}\\int_S\\mathbf B\\cdot d\\mathbf A\n",
        "$$\n",
        "\n",
        "\n",
        "Unlike an electrostatic field, this induced electric field can have a nonzero closed-loop\n",
        "integral. A single-valued electrostatic potential cannot describe the entire circulating\n",
        "field. The wire is a probe and current path; it is not what creates the induced electric\n",
        "field when the magnetic field itself changes.\n",
        "\n",
        "The differential form is\n",
        "\n",
        "\n",
        "$$\n",
        "\\boldsymbol\\nabla\\times\\mathbf E\n",
        "       =-\\frac{\\partial\\mathbf B}{\\partial t}\n",
        "$$\n",
        "\n",
        "\n",
        "## From emf to current\n",
        "\n",
        "An induced emf is not automatically an induced current. Current depends on the complete\n",
        "circuit. For a loop with resistance and negligible self-inductance,\n",
        "\n",
        "\n",
        "$$\n",
        "I=\\frac{\\mathcal E}{R}\n",
        "$$\n",
        "\n",
        "\n",
        "If self-inductance matters, the current obeys a differential equation and cannot change\n",
        "instantaneously. Capacitance, load behavior, source impedance, and switching also affect\n",
        "the response. A zero-resistance loop cannot be handled by dividing the emf by zero; it\n",
        "requires its inductance and material physics.\n",
        "\n",
        "## Eddy currents and energy\n",
        "\n",
        "Changing flux in a bulk conductor can drive circulating eddy currents. Their magnetic\n",
        "effects oppose the flux change, and electrical resistance converts energy into heat.\n",
        "Eddy currents enable induction heating and magnetic braking but can be unwanted in\n",
        "transformer cores. Laminating a conductive core interrupts large current loops and\n",
        "reduces loss.\n",
        "\n",
        "The opposition described by Lenz's law follows energy conservation. If induced current\n",
        "reinforced the change that created it without an external energy input, the field and\n",
        "current could grow on their own. In generators, mechanical work supplies electrical\n",
        "energy. In magnetic braking, mechanical kinetic energy becomes internal energy.\n",
        "\n",
        "## Differentiating sampled flux\n",
        "\n",
        "For sampled data, an interval-average emf can be estimated as\n",
        "\n",
        "\n",
        "$$\n",
        "\\mathcal E_{n-1/2}\n",
        "       \\approx-N\\frac{\\Phi_{B,n}-\\Phi_{B,n-1}}\n",
        "                        {t_n-t_{n-1}}\n",
        "$$\n",
        "\n",
        "\n",
        "The estimate belongs to the interval between the samples, not automatically to either\n",
        "endpoint. A centered difference estimates the derivative at a different time. Record the\n",
        "timestamp convention before comparing results."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-005",
      "metadata": {},
      "source": [
        "import numpy as np\n",
        "\n",
        "times = np.linspace(0, 2, 201)\n",
        "flux = 0.01 * 0.1 * np.cos(2 * times)\n",
        "interval_emf = -100 * np.diff(flux) / np.diff(times)\n",
        "interval_midpoints = (times[:-1] + times[1:]) / 2\n",
        "print(\"First interval emf (V):\", interval_emf[0])\n",
        "print(\n",
        "    \"Maximum midpoint error:\",\n",
        "    np.max(abs(interval_emf - 0.2 * np.sin(2 * interval_midpoints))),\n",
        ")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-006",
      "metadata": {},
      "source": [
        "Differentiation amplifies measurement noise. Filtering can reduce noise but also changes\n",
        "amplitude and phase, so the filter must be documented. For a smooth prescribed flux,\n",
        "reduce the time step and compare with the analytic derivative at matching times.\n",
        "\n",
        "## Verification and limits\n",
        "\n",
        "A constant flux must give zero induced emf even if that flux is large. Reversing the loop\n",
        "normal and traversal together changes the sign representation consistently. Reversing\n",
        "the rate of flux change reverses the emf. Multiplying the number of identical linked\n",
        "turns multiplies the emf. Check that webers per second reduce to volts.\n",
        "\n",
        "The ideal flux model can omit nonuniform-field integration error, finite wire thickness,\n",
        "self-inductance, capacitance, magnetic material hysteresis, eddy currents, skin effect,\n",
        "radiation, and propagation delay. Rapid or spatially large systems require a distributed\n",
        "electromagnetic model. Numerical differentiation adds timing, noise, and resolution\n",
        "errors that must be separated from physical-model error.\n",
        "\n",
        "## A worked Python notebook\n",
        "\n",
        "A 100-turn loop of area 0.01 square metres sees a uniform field of 0.1 cosine of twice time tesla. The question for this calculation is precise: how does **induced emf**\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 loop normal and positive circulation are related by the right-hand rule. 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 3.14159 s. It gives us a specific domain to discuss\n",
        "instead of leaving the graph's range to a software default.\n",
        "\n",
        "Use the notebook link above the lesson, run the setup cell, and then run the cells in\n",
        "order. The code below is also included there. NumPy handles the arrays of numerical\n",
        "values, SymPy keeps the equation symbolic, and Matplotlib draws the results. If these\n",
        "libraries or notebook cells are unfamiliar, start with\n",
        "[Your first physics notebook](https://tirta.co/a-byte-of-physics/your-first-physics-notebook).\n",
        "\n",
        "### State the relationship before choosing a graph\n",
        "\n",
        "In this small example, `q` stands for time, expressed in s. The output is\n",
        "induced emf, expressed in V. 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.2 \\sin{\\left(2 q \\right)}\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 0.785398 s, the expression gives 0.2 V. 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(\"0.2*sin(2*q)\", locals={\"q\": q})\n",
        "reference_input = 0.7853981633974483\n",
        "reference_output = float(expression.subs(q, reference_input))\n",
        "print(\"Input:\", reference_input, \"s\")\n",
        "print(\"Predicted induced emf:\", reference_output, \"V\")\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",
        "0 V. The midpoint, at 1.5708 s, gives\n",
        "2.44929e-17 V. The upper endpoint gives -4.89859e-17 V.\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, 1.5707963267948966, 3.141592653589793])\n",
        "outputs = np.asarray(evaluate(inputs), dtype=float)\n",
        "outputs = np.broadcast_to(outputs, inputs.shape)\n",
        "for input_value, output_value in zip(inputs, outputs):\n",
        "    print(f\"{input_value:.6g} s -> {output_value:.6g} V\")\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 induced emf. 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, 3.141592653589793, 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 (s)\")\n",
        "ax.set_ylabel(\"Induced emf (V)\")\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",
        "induced emf change near the reference input? Its units are the output unit divided by\n",
        "the input unit. For this calculation, the derivative at 0.785398 s is\n",
        "2.44929e-17 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.4 \\cos{\\left(2 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-013",
      "metadata": {},
      "source": [
        "slope_expression = sp.diff(expression, q)\n",
        "slope_at_reference = float(slope_expression.subs(q, reference_input))\n",
        "changed_input = 0.8011061266653973\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, \"V\")\n",
        "print(\"Full expression:\", full_prediction, \"V\")\n",
        "print(\"Approximation difference:\", full_prediction - linear_prediction, \"V\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-014",
      "metadata": {},
      "source": [
        "Here the changed input is 0.801106 s. The tangent estimate is\n",
        "0.2 V, while the full expression gives\n",
        "0.199901 V. 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 = 3.141592653589793\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 induced emf 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 loop normal and positive circulation are related by the right-hand rule. 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 V:\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(3.141592653589793) - evaluate(0.0))\n",
        "for points in [101, 201, 401]:\n",
        "    grid = np.linspace(0.0, 3.141592653589793, 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",
        "- [OpenStax, *University Physics Volume 2*, Section 13.1, “Faraday’s Law”](https://openstax.org/books/university-physics-volume-2/pages/13-1-faradays-law).\n",
        "- [OpenStax, *University Physics Volume 2*, Section 13.2, “Lenz’s Law”](https://openstax.org/books/university-physics-volume-2/pages/13-2-lenzs-law).\n",
        "- [OpenStax, *University Physics Volume 2*, Section 13.3, “Motional Emf”](https://openstax.org/books/university-physics-volume-2/pages/13-3-motional-emf).\n",
        "- [OpenStax, *University Physics Volume 2*, Section 13.4, “Induced Electric Fields”](https://openstax.org/books/university-physics-volume-2/pages/13-4-induced-electric-fields).\n",
        "- [OpenStax, *University Physics Volume 2*, Section 13.5, “Eddy Currents”](https://openstax.org/books/university-physics-volume-2/pages/13-5-eddy-currents).\n",
        "- [Benjamin Crowell, *Light and Matter*](https://open.umn.edu/opentextbooks/textbooks/light-and-matter).\n",
        "- [Physics LibreTexts, “Electricity and Magnetism”](https://phys.libretexts.org/Bookshelves/Electricity_and_Magnetism)."
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.12"
    },
    "colab": {
      "name": "electromagnetic-induction.ipynb",
      "provenance": []
    },
    "tirta": {
      "lesson": "https://tirta.co/a-byte-of-physics/electromagnetic-induction",
      "source_sha256": "d033cb3891f1a7118fbc9de9332afae4088d6d2313c0b0f191bd6c05f69777ec"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
