{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "markdown-000",
      "metadata": {},
      "source": [
        "# Vector fields\n",
        "\n",
        "[Read the lesson](https://tirta.co/a-byte-of-physics/vector-fields). 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 vector assigns one magnitude and direction. A vector field assigns a vector to every\n",
        "point in a stated region of space, and sometimes to every time as well. Wind velocity\n",
        "through the atmosphere, fluid velocity through a pipe, gravitational field, and\n",
        "electric field are examples. The arrows may vary from place to place even when the\n",
        "field is steady in time.\n",
        "\n",
        "## A field is a function over space\n",
        "\n",
        "A three-dimensional vector field can be written\n",
        "\n",
        "\n",
        "$$\n",
        "\\mathbf F(\\mathbf r,t)=F_x(x,y,z,t)\\hat{\\mathbf i}+F_y(x,y,z,t)\\hat{\\mathbf j}+F_z(x,y,z,t)\\hat{\\mathbf k}\n",
        "$$\n",
        "\n",
        "\n",
        "The input position is\n",
        "$\\mathbf r=(x,y,z)$.\n",
        "At one chosen position and time, evaluating the function returns one vector. A static\n",
        "or steady field has no explicit time dependence, so it may be written\n",
        "$\\mathbf F(\\mathbf r)$.\n",
        "\n",
        "The symbol $\\mathbf F$ is generic on\n",
        "this page and should not automatically be read as force. If it represents fluid\n",
        "velocity, its units are metres per second. If it represents electric field, its units\n",
        "are newtons per coulomb or volts per metre. Names, symbols, and units must identify what\n",
        "physical field is stored.\n",
        "\n",
        "## Field and force are different quantities\n",
        "\n",
        "The gravitational field\n",
        "$\\mathbf g$ gives force per\n",
        "unit test mass. The gravitational force on a sufficiently small test body of mass\n",
        "$m$ is\n",
        "\n",
        "\n",
        "$$\n",
        "\\mathbf F_g=m\\mathbf g\n",
        "$$\n",
        "\n",
        "\n",
        "Similarly, the electric field gives force per unit positive test charge:\n",
        "\n",
        "\n",
        "$$\n",
        "\\mathbf F_e=q\\mathbf E\n",
        "$$\n",
        "\n",
        "\n",
        "A negative charge feels a force opposite the electric-field direction. The field can\n",
        "exist at a point whether or not the chosen test object is placed there. Treating the\n",
        "field arrow as the force arrow would erase the dependence on mass or charge and would\n",
        "give the wrong direction for negative electric charge.\n",
        "\n",
        "## Radial inverse-square fields\n",
        "\n",
        "Outside an ideal point mass $M$, Newtonian\n",
        "gravity is\n",
        "\n",
        "\n",
        "$$\n",
        "\\mathbf g(\\mathbf r)=-\\frac{GM}{r^2}\\hat{\\mathbf r}=-GM\\frac{\\mathbf r}{|\\mathbf r|^3}\n",
        "$$\n",
        "\n",
        "\n",
        "Here $r=|\\mathbf r|$\n",
        "and $\\hat{\\mathbf r}=\\mathbf r/r$.\n",
        "The minus sign points the field toward the mass. The second form is convenient in\n",
        "Cartesian code, but it makes the singularity at\n",
        "$r=0$ especially important.\n",
        "\n",
        "The electric field of an ideal point charge\n",
        "$Q$ at the origin is\n",
        "\n",
        "\n",
        "$$\n",
        "\\mathbf E(\\mathbf r)=\\frac{1}{4\\pi\\epsilon_0}\\frac{Q}{r^2}\\hat{\\mathbf r}\n",
        "$$\n",
        "\n",
        "\n",
        "A positive source points outward; a negative source points inward. Both idealized\n",
        "point-source formulas are undefined at the source position. A program must not quietly\n",
        "return a zero arrow there. Zero would claim that the field is finite and absent, while\n",
        "the mathematical model actually has no defined value."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-003",
      "metadata": {},
      "source": [
        "import numpy as np\n",
        "\n",
        "G = 6.67430e-11\n",
        "\n",
        "\n",
        "def point_mass_field(position, mass, minimum_radius=1.0):\n",
        "    position = np.asarray(position, dtype=float)\n",
        "    radius = np.linalg.norm(position)\n",
        "    if radius < minimum_radius:\n",
        "        raise ValueError(\"Point is inside the excluded source region.\")\n",
        "    return -G * mass * position / radius**3\n",
        "\n",
        "\n",
        "print(\"Field (m/s^2):\", point_mass_field([6.371e6, 0, 0], 5.972e24))\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-004",
      "metadata": {},
      "source": [
        "The `modelLimit` is not merely a floating-point trick. If the source has a finite size,\n",
        "the point-source approximation eventually ceases to describe its interior. A softened\n",
        "denominator sometimes used in numerical graphics defines a different physical model\n",
        "and must disclose its softening length.\n",
        "\n",
        "## Superposition\n",
        "\n",
        "Newtonian gravitational fields and electrostatic fields obey superposition. For\n",
        "several point sources, calculate each source contribution at the same field point and\n",
        "add the vectors:\n",
        "\n",
        "\n",
        "$$\n",
        "\\mathbf E(\\mathbf r)=\\sum_i\\frac{1}{4\\pi\\epsilon_0}Q_i\\frac{\\mathbf r-\\mathbf r_i}{|\\mathbf r-\\mathbf r_i|^3}\n",
        "$$\n",
        "\n",
        "\n",
        "The displacement in each term is from source position\n",
        "$\\mathbf r_i$ to field point\n",
        "$\\mathbf r$. Reversing that\n",
        "subtraction reverses every contribution. All positions must use the same origin, basis,\n",
        "frame, and length unit."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-005",
      "metadata": {},
      "source": [
        "def field_from_sources(point, sources):\n",
        "    total = np.zeros(3)\n",
        "    for source_position, mass in sources:\n",
        "        total += point_mass_field(np.asarray(point) - source_position, mass)\n",
        "    return total\n",
        "\n",
        "\n",
        "sources = [(np.array([-2.0, 0, 0]), 1e10), (np.array([2.0, 0, 0]), 1e10)]\n",
        "print(\"Midpoint field:\", field_from_sources([0.0, 0.0, 0.0], sources))\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-006",
      "metadata": {},
      "source": [
        "Superposition adds vectors, so equal source magnitudes do not imply equal field\n",
        "magnitudes everywhere. At a symmetry point, contributions may cancel. A zero total\n",
        "field means the vector sum is zero at that point; it does not mean each source stopped\n",
        "producing a field.\n",
        "\n",
        "## Continuous source distributions\n",
        "\n",
        "When mass or charge is spread continuously, a sum becomes an integral. For a charge\n",
        "density $\\rho(\\mathbf r')$,\n",
        "\n",
        "\n",
        "$$\n",
        "\\mathbf E(\\mathbf r)=\\frac{1}{4\\pi\\epsilon_0}\\int \\rho(\\mathbf r')\\frac{\\mathbf r-\\mathbf r'}{|\\mathbf r-\\mathbf r'|^3}\\,d^3r'\n",
        "$$\n",
        "\n",
        "\n",
        "The primed coordinate labels the source location being integrated over; the unprimed\n",
        "coordinate is the observation point. Confusing them makes the direction or integration\n",
        "variable ambiguous. Depending on the source geometry, the density and measure may be\n",
        "linear, surface, or volume quantities with different units.\n",
        "\n",
        "Numerical integration divides the source into finite elements, computes each element's\n",
        "contribution, and adds them. Accuracy should be checked by refining the elements and\n",
        "comparing at the same observation points. Near a source, ordinary uniform subdivision\n",
        "may converge slowly or mishandle a singular kernel, so specialized quadrature or an\n",
        "analytic treatment may be required.\n",
        "\n",
        "## Fields stored on a grid\n",
        "\n",
        "Measured and computed fields are often available only at discrete grid points. The\n",
        "stored data is then a sampled approximation, not the continuous field itself. To query\n",
        "between samples, software chooses an interpolation rule.\n",
        "\n",
        "Nearest-neighbor interpolation creates abrupt jumps. Bilinear interpolation in two\n",
        "dimensions blends the four surrounding grid values and is continuous across most cell\n",
        "boundaries, though its derivatives may not be. Higher-order interpolation can be\n",
        "smoother but may overshoot measured values. No interpolation can reconstruct spatial\n",
        "features that were never resolved by the sampling grid."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-007",
      "metadata": {},
      "source": [
        "# Corner fields on a unit square, ordered bottom-left, bottom-right,\n",
        "# top-left, top-right. Components use the same Cartesian basis.\n",
        "corners = np.array([[0, 0], [1, 0], [0, 1], [1, 1]], dtype=float)\n",
        "x, y = 0.25, 0.75\n",
        "weights = np.array([(1 - x) * (1 - y), x * (1 - y), (1 - x) * y, x * y])\n",
        "interpolated = weights @ corners\n",
        "print(\"Interpolated field:\", interpolated)\n",
        "assert np.allclose(interpolated, [x, y])\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-008",
      "metadata": {},
      "source": [
        "The domain rule must be explicit. Clamping an outside query to the boundary, wrapping\n",
        "it periodically, extrapolating, and returning an error describe different systems.\n",
        "Boundary behavior should never be an accidental consequence of array indexing.\n",
        "\n",
        "## Following a field is not always following a particle\n",
        "\n",
        "A field line is a curve whose tangent points along the field:\n",
        "\n",
        "\n",
        "$$\n",
        "\\frac{d\\mathbf r}{ds}\\parallel\\mathbf F(\\mathbf r)\n",
        "$$\n",
        "\n",
        "\n",
        "Field lines help display direction and relative strength, but they are not material\n",
        "threads. Electric field lines are not generally trajectories of charged particles. A\n",
        "particle has inertia, and its acceleration follows force through Newton's second law.\n",
        "Its velocity need not remain parallel to the electric field. Streamlines coincide with\n",
        "instantaneous fluid-velocity directions, but in a time-dependent flow they can differ\n",
        "from pathlines traced by fluid parcels.\n",
        "\n",
        "## Local behavior: divergence and curl\n",
        "\n",
        "Two derivatives describe important local patterns. Divergence measures local source or\n",
        "sink behavior, while curl measures local circulation tendency:\n",
        "\n",
        "\n",
        "$$\n",
        "\\nabla\\cdot\\mathbf F,\\qquad \\nabla\\times\\mathbf F\n",
        "$$\n",
        "\n",
        "\n",
        "These are local differential quantities, not conclusions based only on how a few arrows\n",
        "look. An inverse-square radial field can have zero divergence everywhere away from its\n",
        "point source even though its arrows spread visually, because the increasing spherical\n",
        "area exactly offsets the decreasing magnitude. The source requires separate treatment.\n",
        "The later vector-calculus lesson develops component formulas and numerical estimates.\n",
        "\n",
        "## Validation by symmetry, units, and limits\n",
        "\n",
        "A field implementation should be checked with predictions that do not depend on its\n",
        "own output:\n",
        "\n",
        "- verify output units from the physical definition;\n",
        "- test known symmetry points where components cancel;\n",
        "- confirm an attractive radial field points toward its source;\n",
        "- confirm inverse-square magnitude falls by a factor of four when distance doubles;\n",
        "- compare a many-source sum with a hand-computed small case;\n",
        "- reject or specially handle source singularities;\n",
        "- rotate the whole source configuration and confirm the field rotates with it;\n",
        "- refine a source discretization or sampling grid and check convergence;\n",
        "- test each boundary policy intentionally;\n",
        "- keep field and test-particle force as separate quantities.\n",
        "\n",
        "Vector fields compactly express how physical influence or flow varies through space.\n",
        "Their arrows are only samples of a function. Correct reasoning depends on the function's\n",
        "domain, units, source model, coordinate frame, and singularities as much as on its\n",
        "component values.\n",
        "\n",
        "## A worked Python notebook\n",
        "\n",
        "Take a radial slice through a point-mass field with gravitational parameter 10 cubic metres per second squared. The question for this calculation is precise: how does **inward field magnitude**\n",
        "change when we change **distance from a source**, 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 point-source expression is excluded at zero distance. 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",
        "1 to 5 m. It gives us a specific domain to discuss\n",
        "instead of leaving the graph's range to a software default.\n",
        "\n",
        "Use the notebook link above the lesson, run the setup cell, and then run the cells in\n",
        "order. The code below is also included there. NumPy handles the arrays of numerical\n",
        "values, SymPy keeps the equation symbolic, and Matplotlib draws the results. If these\n",
        "libraries or notebook cells are unfamiliar, start with\n",
        "[Your first physics notebook](https://tirta.co/a-byte-of-physics/your-first-physics-notebook).\n",
        "\n",
        "### State the relationship before choosing a graph\n",
        "\n",
        "In this small example, `q` stands for distance from a source, expressed in m. The output is\n",
        "inward field magnitude, expressed in m/s^2. 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) = \\frac{10}{q^{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 2 m, the expression gives 2.5 m/s^2. This is our\n",
        "reference calculation. It is a prediction of the stated example, not a new measurement.\n",
        "Its displayed digits help us compare implementations. They should not be read as a\n",
        "claim that physical inputs are known to six significant figures."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-009",
      "metadata": {},
      "source": [
        "import numpy as np\n",
        "import sympy as sp\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "q = sp.Symbol(\"q\", real=True)\n",
        "expression = sp.sympify(\"10/q**2\", locals={\"q\": q})\n",
        "reference_input = 2.0\n",
        "reference_output = float(expression.subs(q, reference_input))\n",
        "print(\"Input:\", reference_input, \"m\")\n",
        "print(\"Predicted inward field magnitude:\", reference_output, \"m/s^2\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-010",
      "metadata": {},
      "source": [
        "`sp.Symbol` declares a mathematical symbol. It does not assign a numerical measurement\n",
        "to that symbol. `subs` then replaces the symbol with our chosen input, and `float`\n",
        "converts the resulting symbolic number into a standard Python numerical value.\n",
        "Keeping these steps separate lets us inspect the equation before numerical substitution.\n",
        "It also prevents a later plot from becoming the only surviving record of the model.\n",
        "\n",
        "### Compare a few cases you can explain\n",
        "\n",
        "Before drawing hundreds of points, calculate three. The lower endpoint gives\n",
        "10 m/s^2. The midpoint, at 3 m, gives\n",
        "1.11111 m/s^2. The upper endpoint gives 0.4 m/s^2.\n",
        "Read these together with the assumptions: they describe different choices of distance from a source\n",
        "within the same example, with the other inputs held fixed.\n",
        "\n",
        "These three values are a useful first check, but they do not establish the shape between\n",
        "them. Two endpoints can be equal even when the curve bends or oscillates in between.\n",
        "Likewise, a large change between endpoints does not tell us whether the relationship is\n",
        "linear. We need the equation and intermediate samples to answer those questions."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-011",
      "metadata": {},
      "source": [
        "evaluate = sp.lambdify(q, expression, modules=\"numpy\")\n",
        "inputs = np.array([1.0, 3.0, 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(f\"{input_value:.6g} m -> {output_value:.6g} m/s^2\")\n",
        "assert np.all(np.isfinite(outputs))\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-012",
      "metadata": {},
      "source": [
        "`lambdify` turns the symbolic expression into a numerical function. We explicitly select\n",
        "NumPy as its numerical backend so it can accept an array. The same expression now has\n",
        "two useful forms: one for algebra and one for calculating many cases. The assertion\n",
        "checks that the chosen inputs produce finite outputs. It would catch an infinity or an\n",
        "undefined numerical result, but a finite value can still be physically inappropriate.\n",
        "\n",
        "### Make a graph that answers the question\n",
        "\n",
        "The horizontal axis shows distance from a source; the vertical axis shows inward field magnitude. Every plotted\n",
        "point is a prediction of the same expression. We mark the reference case separately\n",
        "so that a reader can connect the earlier printed value to its place on the curve.\n",
        "The axis labels include units because a shape without a scale cannot tell us the size\n",
        "of a physical effect."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-013",
      "metadata": {},
      "source": [
        "input_grid = np.linspace(1.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(\"Distance from a source (m)\")\n",
        "ax.set_ylabel(\"Inward field magnitude (m/s^2)\")\n",
        "ax.legend()\n",
        "ax.grid(alpha=0.25)\n",
        "fig.tight_layout()\n",
        "plt.show()\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-014",
      "metadata": {},
      "source": [
        "Look for a sign change, a turning point, or a region where the curve becomes steep.\n",
        "Connect each feature to the expression rather than to the colour of the line. If the\n",
        "curve has a minimum or maximum, changing the input in opposite directions may have\n",
        "similar effects on the output near that point. If it is nearly straight over a short\n",
        "interval, a local linear approximation may be useful even when the complete expression\n",
        "is nonlinear.\n",
        "\n",
        "Increasing the number of samples makes the line smoother and may reveal features that\n",
        "a coarse grid missed. It does not improve the physical inputs or enlarge the model's\n",
        "validity range. For quantities that can take only discrete values, use the line as a\n",
        "guide to the relationship and interpret only the allowed input values. A plotting\n",
        "function does not enforce such restrictions for you.\n",
        "\n",
        "### Measure the local sensitivity\n",
        "\n",
        "A derivative asks a more specific question than the whole graph: how quickly does\n",
        "inward field magnitude change near the reference input? Its units are the output unit divided by\n",
        "the input unit. For this calculation, the derivative at 2 m is\n",
        "-2.5 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) = - \\frac{20}{q^{3}}\n",
        "$$\n",
        "\n",
        "\n",
        "For a small input change, multiply the derivative by that change to estimate the output\n",
        "change. Then compare that estimate with a fresh evaluation of the full expression.\n",
        "The distinction between these two calculations matters: the derivative gives a tangent\n",
        "approximation, while substitution evaluates the chosen expression at the new point."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-015",
      "metadata": {},
      "source": [
        "slope_expression = sp.diff(expression, q)\n",
        "slope_at_reference = float(slope_expression.subs(q, reference_input))\n",
        "changed_input = 2.02\n",
        "linear_prediction = reference_output + slope_at_reference * (\n",
        "    changed_input - reference_input\n",
        ")\n",
        "full_prediction = float(evaluate(changed_input))\n",
        "print(\"Symbolic derivative:\", slope_expression)\n",
        "print(\"Tangent prediction:\", linear_prediction, \"m/s^2\")\n",
        "print(\"Full expression:\", full_prediction, \"m/s^2\")\n",
        "print(\"Approximation difference:\", full_prediction - linear_prediction, \"m/s^2\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-016",
      "metadata": {},
      "source": [
        "Here the changed input is 2.02 m. The tangent estimate is\n",
        "2.45 m/s^2, while the full expression gives\n",
        "2.45074 m/s^2. If the two values are close, it means the chosen\n",
        "input change is small enough for this local approximation at this point. It does not\n",
        "mean the entire model is linear. If the slope is zero, a quadratic or higher-order term\n",
        "may supply the leading change instead.\n",
        "\n",
        "This is also the beginning of uncertainty propagation. If the input has a small stated\n",
        "standard uncertainty, the magnitude of the slope times that uncertainty estimates one\n",
        "contribution to output uncertainty. Do not automatically use the same rule for a wide\n",
        "interval, a discontinuity, a turning point with zero first derivative, or several\n",
        "correlated uncertain inputs. Those situations need more of the model than one slope.\n",
        "\n",
        "### Check the derivative with numerical differences\n",
        "\n",
        "We can estimate the same slope from values on either side of the reference point.\n",
        "Subtract the lower output from the upper output and divide by twice the input step.\n",
        "Parentheses are essential: the entire output difference must be divided by the entire\n",
        "input interval. Without them, Python can execute a different mathematical expression\n",
        "while still producing a plausible number.\n",
        "\n",
        "The calculation below uses three decreasing step sizes. Each estimate is compared with\n",
        "the symbolic derivative, so the reference is independent of the numerical difference\n",
        "formula. Near an endpoint, it is acceptable here to evaluate a small extension only\n",
        "because the displayed mathematical expression is smooth there; such a check does not\n",
        "assert that extrapolated values describe additional physical cases."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-017",
      "metadata": {},
      "source": [
        "input_span = 4.0\n",
        "for fraction in [1e-2, 1e-3, 1e-4]:\n",
        "    step = input_span * fraction\n",
        "    upper = float(evaluate(reference_input + step))\n",
        "    lower = float(evaluate(reference_input - step))\n",
        "    numerical_slope = (upper - lower) / (2 * step)\n",
        "    difference = numerical_slope - slope_at_reference\n",
        "    print(f\"step={step:.6g}: slope={numerical_slope:.6g}, difference={difference:.6g}\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-018",
      "metadata": {},
      "source": [
        "For a smooth function, reducing the step often reduces the approximation error at first.\n",
        "Very small steps can eventually make subtraction of nearly equal floating-point values\n",
        "less reliable. Therefore “smaller” is not an unlimited guarantee of “better.” Compare\n",
        "the observed behaviour over a useful range of steps instead of choosing the smallest\n",
        "number the computer can represent.\n",
        "\n",
        "An absolute slope difference is useful when the expected slope is near zero. A relative\n",
        "difference would divide by a very small reference and could look enormous even when the\n",
        "absolute discrepancy is tiny. Away from zero, a relative difference can help compare\n",
        "quantities with very different scales. The tolerance should reflect the question and\n",
        "the numerical method, rather than a universal decimal threshold copied into every test.\n",
        "\n",
        "### Change the example and preserve the reasoning\n",
        "\n",
        "Make one copy of the reference calculation before editing it. Choose a second value of\n",
        "distance from a source inside the stated interval, predict whether inward field magnitude 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 point-source expression is excluded at zero distance. Describe one change\n",
        "to the setup that would violate that limit. State what new input, equation, or observation\n",
        "would be needed before trusting an answer in the changed situation. This last step\n",
        "connects the Python experiment to the physics instead of treating successful execution\n",
        "as the only criterion for a useful result.\n",
        "\n",
        "Before saving, restart the runtime and run all cells in order. A result that depends on\n",
        "an earlier, now-deleted input cell is not reproducible from the saved notebook. Keep\n",
        "unrounded values for later calculations, round only the reported output, and label any\n",
        "new data as measured, assumed, or generated. The graph and printed values should remain\n",
        "traceable to the same expression and the same choices of inputs.\n",
        "\n",
        "### Recover the output change by integrating the slope\n",
        "\n",
        "There is another way to check that the expression and its derivative describe the same\n",
        "relationship. Add up the small output changes predicted by the slope across the chosen\n",
        "input interval. In the continuous limit, this integral equals the output at the upper\n",
        "endpoint minus the output at the lower endpoint. The result has units of m/s^2:\n",
        "the input unit in the integration cancels the input unit in the denominator of the slope.\n",
        "\n",
        "This statement is about the mathematics of this particular relationship. It does not\n",
        "assign a new physical meaning to an arbitrary area under a graph. For example, an area\n",
        "under force versus distance represents work, while an area under a different pair of\n",
        "quantities may represent something else or have no standard name. Always carry the\n",
        "axis units through the calculation before naming an integral."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-019",
      "metadata": {},
      "source": [
        "slope_function = sp.lambdify(q, slope_expression, modules=\"numpy\")\n",
        "endpoint_change = float(evaluate(5.0) - evaluate(1.0))\n",
        "for points in [101, 201, 401]:\n",
        "    grid = np.linspace(1.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-020",
      "metadata": {},
      "source": [
        "The trapezoidal rule joins neighbouring slope samples with straight segments and adds\n",
        "their signed areas. A negative contribution remains negative; replacing every slope\n",
        "by its magnitude would calculate a different quantity. Increasing the sample count\n",
        "provides a practical refinement check. If the values do not settle toward the endpoint\n",
        "difference, first inspect the interval, singularities, and array ordering.\n",
        "\n",
        "Do not conclude that two agreeing calculations prove the model is physically complete.\n",
        "Both use the same selected relationship, so an omitted effect would be omitted from\n",
        "both. Their agreement is evidence that the numerical tools implement that relationship\n",
        "consistently. Comparing with an independent experiment or a more appropriate physical\n",
        "model is a separate test.\n",
        "\n",
        "Keep this comparison in the notebook when you change the expression. It is particularly\n",
        "useful after adding a coefficient, changing a sign convention, or converting an input\n",
        "unit. A code cell that produces a smooth graph can conceal these mistakes; a second\n",
        "calculation of the same output change gives you another place to notice them.\n",
        "\n",
        "## Sources\n",
        "\n",
        "- [OpenStax, *University Physics Volume 2*, Section 5.4, \"Electric Field\"](https://openstax.org/books/university-physics-volume-2/pages/5-4-electric-field).\n",
        "- [OpenStax, *University Physics Volume 2*, Section 5.5, \"Calculating Electric Fields of Charge Distributions\"](https://openstax.org/books/university-physics-volume-2/pages/5-5-calculating-electric-fields-of-charge-distributions).\n",
        "- [OpenStax, *University Physics Volume 1*, Section 13.2, \"Gravitation Near Earth's Surface\"](https://openstax.org/books/university-physics-volume-1/pages/13-2-gravitation-near-earths-surface).\n",
        "- [Benjamin Crowell, *Light and Matter*, Chapter 22, \"Fields of Force\"](https://open.umn.edu/opentextbooks/textbooks/light-and-matter).\n",
        "- [The Physics Hypertextbook, \"Electric Field\"](https://physics.info/electric-field/)."
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.12"
    },
    "colab": {
      "name": "vector-fields.ipynb",
      "provenance": []
    },
    "tirta": {
      "lesson": "https://tirta.co/a-byte-of-physics/vector-fields",
      "source_sha256": "78f02dfaba80dd7dbb255f445ff85117103fb2eca9e46539c57e7cc7437beb50"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
