{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "markdown-000",
      "metadata": {},
      "source": [
        "# Symbolic vector calculus\n",
        "\n",
        "[Read the lesson](https://tirta.co/a-byte-of-physics/symbolic-vector-calculus). 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": [
        "Vector calculus describes how scalar and vector fields change from point to point.\n",
        "Gradient, divergence, curl, and the Laplacian answer different questions and return\n",
        "different types of quantities. Their compact notation is useful only when the field,\n",
        "coordinates, units, and differentiability assumptions are clear.\n",
        "\n",
        "## Partial derivatives and the del operator\n",
        "\n",
        "For Cartesian coordinates, the differential operator pronounced “del” is written\n",
        "\n",
        "\n",
        "$$\n",
        "\\nabla=\\hat{\\mathbf i}\\frac{\\partial}{\\partial x}+\\hat{\\mathbf j}\\frac{\\partial}{\\partial y}+\\hat{\\mathbf k}\\frac{\\partial}{\\partial z}\n",
        "$$\n",
        "\n",
        "\n",
        "A partial derivative changes one coordinate while holding the others fixed. For a\n",
        "temperature field $T(x,y,z)$,\n",
        "the quantity $\\partial T/\\partial x$\n",
        "has units of temperature per length. It is a local rate of change, not a finite\n",
        "temperature difference by itself.\n",
        "\n",
        "The symbolic expression for $\\nabla$\n",
        "looks like a vector, but it is a differential operator. Its dot and cross combinations\n",
        "must act on a sufficiently smooth field. Formulas on this page use a fixed orthonormal\n",
        "Cartesian basis. Cylindrical, spherical, and other curvilinear systems require scale\n",
        "factors and derivatives of position-dependent basis vectors.\n",
        "\n",
        "## Gradient: from a scalar to a vector\n",
        "\n",
        "For a scalar field $f(x,y,z)$,\n",
        "\n",
        "\n",
        "$$\n",
        "\\nabla f=\\frac{\\partial f}{\\partial x}\\hat{\\mathbf i}+\\frac{\\partial f}{\\partial y}\\hat{\\mathbf j}+\\frac{\\partial f}{\\partial z}\\hat{\\mathbf k}\n",
        "$$\n",
        "\n",
        "\n",
        "The gradient points in the direction of greatest local increase of the scalar field. Its\n",
        "dot product with a small displacement gives the first-order field change:\n",
        "\n",
        "\n",
        "$$\n",
        "df=\\nabla f\\cdot d\\mathbf r\n",
        "$$\n",
        "\n",
        "\n",
        "For a unit direction $\\hat{\\mathbf n}$,\n",
        "the directional derivative is\n",
        "$D_{\\hat{\\mathbf n}}f=\\nabla f\\cdot\\hat{\\mathbf n}$.\n",
        "The gradient therefore contains all first-order directional change at a point.\n",
        "\n",
        "Potential energy and conservative force are related by\n",
        "\n",
        "\n",
        "$$\n",
        "\\mathbf F=-\\nabla U\n",
        "$$\n",
        "\n",
        "\n",
        "The negative sign says force points toward decreasing potential energy. If\n",
        "$U$ is measured in joules and\n",
        "position in metres, the gradient has joules per metre, equivalent to newtons.\n",
        "\n",
        "## Divergence: local outward flux density\n",
        "\n",
        "For a vector field\n",
        "$\\mathbf F=(F_x,F_y,F_z)$,\n",
        "\n",
        "\n",
        "$$\n",
        "\\nabla\\cdot\\mathbf F=\\frac{\\partial F_x}{\\partial x}+\\frac{\\partial F_y}{\\partial y}+\\frac{\\partial F_z}{\\partial z}\n",
        "$$\n",
        "\n",
        "\n",
        "Divergence is a scalar. Positive divergence means a small region has net outward flux\n",
        "to first order; negative divergence indicates net inward flux. Zero divergence means\n",
        "the local outward and inward flux balance. It does not require the field itself to be\n",
        "zero.\n",
        "\n",
        "For the linear field\n",
        "$\\mathbf F=(2x,-y,3z)$,\n",
        "\n",
        "\n",
        "$$\n",
        "\\nabla\\cdot\\mathbf F=2-1+3=4\n",
        "$$\n",
        "\n",
        "\n",
        "If the field has units $[F]$ and\n",
        "coordinates have length units, divergence has units\n",
        "$[F]/\\mathrm{length}$.\n",
        "\n",
        "The divergence theorem connects this local derivative to total flux through a closed\n",
        "surface:\n",
        "\n",
        "\n",
        "$$\n",
        "\\iiint_V(\\nabla\\cdot\\mathbf F)\\,dV=\\oiint_{\\partial V}\\mathbf F\\cdot d\\mathbf A\n",
        "$$\n",
        "\n",
        "\n",
        "The boundary normal points outward. This theorem explains the source interpretation of\n",
        "divergence and underlies Gauss's law, subject to the field's regularity and any singular\n",
        "sources.\n",
        "\n",
        "## Curl: local circulation density\n",
        "\n",
        "The Cartesian curl is\n",
        "\n",
        "\n",
        "$$\n",
        "\\nabla\\times\\mathbf F=\\left(\\frac{\\partial F_z}{\\partial y}-\\frac{\\partial F_y}{\\partial z}\\right)\\hat{\\mathbf i}+\\left(\\frac{\\partial F_x}{\\partial z}-\\frac{\\partial F_z}{\\partial x}\\right)\\hat{\\mathbf j}+\\left(\\frac{\\partial F_y}{\\partial x}-\\frac{\\partial F_x}{\\partial y}\\right)\\hat{\\mathbf k}\n",
        "$$\n",
        "\n",
        "\n",
        "Curl is an axial vector. Its direction gives the positive local circulation axis by the\n",
        "right-hand rule. Its magnitude measures circulation per area in the shrinking-loop\n",
        "limit. A field can curve visually yet have zero curl, and a sparse arrow plot cannot\n",
        "prove a curl value.\n",
        "\n",
        "For a two-dimensional field\n",
        "$\\mathbf F=(F_x(x,y),F_y(x,y),0)$,\n",
        "only the perpendicular component can be nonzero:\n",
        "\n",
        "\n",
        "$$\n",
        "(\\nabla\\times\\mathbf F)_z=\\frac{\\partial F_y}{\\partial x}-\\frac{\\partial F_x}{\\partial y}\n",
        "$$\n",
        "\n",
        "\n",
        "For the rigid-rotation-like field\n",
        "$\\mathbf F=(-\\omega y,\\omega x,0)$,\n",
        "the curl is\n",
        "$(0,0,2\\omega)$.\n",
        "The factor two is important: local angular velocity in rigid rotation is one half of the\n",
        "vorticity.\n",
        "\n",
        "Stokes' theorem relates curl to circulation around a boundary curve:\n",
        "\n",
        "\n",
        "$$\n",
        "\\iint_S(\\nabla\\times\\mathbf F)\\cdot d\\mathbf A=\\oint_{\\partial S}\\mathbf F\\cdot d\\mathbf l\n",
        "$$\n",
        "\n",
        "\n",
        "The surface normal and traversal direction must follow the right-hand orientation.\n",
        "\n",
        "## The Laplacian\n",
        "\n",
        "Applying divergence to the gradient of a scalar field gives the scalar Laplacian:\n",
        "\n",
        "\n",
        "$$\n",
        "\\nabla^2 f=\\nabla\\cdot(\\nabla f)=\\frac{\\partial^2f}{\\partial x^2}+\\frac{\\partial^2f}{\\partial y^2}+\\frac{\\partial^2f}{\\partial z^2}\n",
        "$$\n",
        "\n",
        "\n",
        "The Laplacian compares a value with its local spatial neighborhood. It appears in the\n",
        "heat equation, wave equation, Poisson equation, and Schrödinger equation. Its units are\n",
        "the scalar field's units per length squared.\n",
        "\n",
        "For a Cartesian vector field, a vector Laplacian may be applied component by component,\n",
        "but that simple component statement does not carry unchanged into every coordinate\n",
        "system. Naming whether an operator acts on a scalar or vector avoids ambiguous code.\n",
        "\n",
        "## Symbolic differentiation as an expression transformation\n",
        "\n",
        "A symbolic algebra system represents a formula as an expression tree rather than as a\n",
        "single evaluated number. Differentiation recursively applies rules such as linearity,\n",
        "the product rule, and the chain rule. For the gradient, it differentiates one scalar\n",
        "expression with respect to each coordinate. For divergence and curl, it differentiates\n",
        "selected component expressions and combines them with the required signs."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-003",
      "metadata": {},
      "source": [
        "import sympy as sp\n",
        "\n",
        "x, y, z = sp.symbols(\"x y z\", real=True)\n",
        "coordinates = (x, y, z)\n",
        "scalar_field = x**2 + y**2 + z**2\n",
        "gradient = sp.Matrix([sp.diff(scalar_field, q) for q in coordinates])\n",
        "print(\"Gradient:\", gradient)\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "id": "code-004",
      "metadata": {},
      "source": [
        "vector_field = sp.Matrix([x**2, y**2, z**2])\n",
        "divergence = sum(sp.diff(vector_field[i], q) for i, q in enumerate(coordinates))\n",
        "print(\"Divergence:\", sp.simplify(divergence))\n",
        "assert sp.simplify(divergence - 2 * (x + y + z)) == 0\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-005",
      "metadata": {},
      "source": [
        "Symbolic simplification can expose an exact zero, but it needs assumptions. Expressions\n",
        "involving absolute values, square roots, piecewise rules, or division can change form\n",
        "depending on whether variables are real, positive, or nonzero. A result should preserve\n",
        "its domain restrictions instead of cancelling factors across excluded points.\n",
        "\n",
        "## Estimating derivatives from sampled fields\n",
        "\n",
        "When only numerical samples are available, a centered finite difference approximates\n",
        "a first derivative:\n",
        "\n",
        "\n",
        "$$\n",
        "\\frac{\\partial F_x}{\\partial x}(x,y)\\approx\\frac{F_x(x+h,y)-F_x(x-h,y)}{2h}\n",
        "$$\n",
        "\n",
        "\n",
        "In two dimensions, central estimates of divergence and perpendicular curl are\n",
        "\n",
        "\n",
        "$$\n",
        "\\nabla\\cdot\\mathbf F\\approx\\frac{F_x(x+h,y)-F_x(x-h,y)}{2h}+\\frac{F_y(x,y+h)-F_y(x,y-h)}{2h}\n",
        "$$\n",
        "\n",
        "\n",
        "and\n",
        "\n",
        "\n",
        "$$\n",
        "(\\nabla\\times\\mathbf F)_z\\approx\\frac{F_y(x+h,y)-F_y(x-h,y)}{2h}-\\frac{F_x(x,y+h)-F_x(x,y-h)}{2h}\n",
        "$$"
      ]
    },
    {
      "cell_type": "code",
      "id": "code-006",
      "metadata": {},
      "source": [
        "import numpy as np\n",
        "\n",
        "\n",
        "def field(point):\n",
        "    x, y = point\n",
        "    return np.array([x**2, y**2])\n",
        "\n",
        "\n",
        "def divergence_2d(point, step):\n",
        "    dx, dy = np.array([step, 0.0]), np.array([0.0, step])\n",
        "    derivative_x = (field(point + dx)[0] - field(point - dx)[0]) / (2 * step)\n",
        "    derivative_y = (field(point + dy)[1] - field(point - dy)[1]) / (2 * step)\n",
        "    return derivative_x + derivative_y\n",
        "\n",
        "\n",
        "print(divergence_2d(np.array([1.0, 2.0]), 1e-3))\n",
        "assert np.isclose(divergence_2d(np.array([1.0, 2.0]), 1e-3), 6.0)\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-007",
      "metadata": {},
      "source": [
        "Smaller $h$ usually reduces\n",
        "truncation error at first, but it increases sensitivity to measurement noise and\n",
        "floating-point cancellation. At boundaries, a centered stencil may query outside the\n",
        "domain; one-sided differences, ghost values, or physical boundary conditions must be\n",
        "chosen deliberately. Different coordinate spacings require separate denominators.\n",
        "\n",
        "## Identities and their assumptions\n",
        "\n",
        "For fields with sufficiently continuous mixed derivatives,\n",
        "\n",
        "\n",
        "$$\n",
        "\\nabla\\times(\\nabla f)=\\mathbf 0,\\qquad \\nabla\\cdot(\\nabla\\times\\mathbf F)=0\n",
        "$$\n",
        "\n",
        "\n",
        "These identities are excellent symbolic and numerical checks. Finite-difference\n",
        "implementations should approach them under grid refinement when compatible discrete\n",
        "operators and boundary treatments are used. Failure near a singularity or discontinuity\n",
        "does not automatically mean the algebraic identity is wrong; the smoothness assumptions\n",
        "may not apply there.\n",
        "\n",
        "A curl-free field is locally expressible as a gradient under suitable conditions, but\n",
        "global conclusions also depend on the domain's topology. A hole or excluded singularity\n",
        "can allow nonzero circulation around a loop even where local curl vanishes. “Curl zero\n",
        "means conservative everywhere” is therefore incomplete without domain assumptions.\n",
        "\n",
        "## Checks for an implementation\n",
        "\n",
        "Use analytic fields with known derivatives before trusting complicated data:\n",
        "\n",
        "- constant scalar fields have zero gradient;\n",
        "- constant vector fields have zero divergence and curl;\n",
        "- linear fields give constant first derivatives;\n",
        "- the gradient of\n",
        "  $x^2+y^2+z^2$\n",
        "  is $(2x,2y,2z)$;\n",
        "- the divergence of\n",
        "  $(x,y,z)$ is\n",
        "  $3$;\n",
        "- the rigid-rotation field has zero divergence and the expected constant curl;\n",
        "- symbolic results preserve domain restrictions;\n",
        "- numerical derivatives converge over a useful range of step sizes;\n",
        "- boundary and singular points return deliberate results or diagnostics;\n",
        "- output units follow field units divided by the required power of length.\n",
        "\n",
        "Vector-calculus notation compresses many component derivatives into a few symbols. The\n",
        "best way to keep it understandable is to track input and output types, explain the local\n",
        "physical meaning, expand the Cartesian components when checking signs, and separate\n",
        "exact symbolic identities from approximate numerical estimates.\n",
        "\n",
        "## A worked Python notebook\n",
        "\n",
        "Take one slice of the scalar field x squared plus y squared and compare its derivative with the gradient component. The question for this calculation is precise: how does **scalar potential along y=1**\n",
        "change when we change **horizontal coordinate**, 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",
        "A one-dimensional slice cannot determine the entire gradient without the other coordinate derivatives. 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",
        "-2 to 2 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 horizontal coordinate, expressed in m. The output is\n",
        "scalar potential along y=1, expressed in arbitrary potential units. The equation below uses the numerical values in those\n",
        "units. Any fixed coefficients therefore carry the units needed to make the relation\n",
        "consistent. A value supplied in another unit must be converted before it enters this\n",
        "expression.\n",
        "\n",
        "\n",
        "$$\n",
        "f(q) = q^{2} + 1\n",
        "$$\n",
        "\n",
        "\n",
        "This is a function of one changing input. It is not a statement that the physical\n",
        "system has only one variable. We deliberately hold the other inputs fixed so that one\n",
        "cause of variation is visible. Changing several inputs at once would make it harder\n",
        "to tell which change produced the output difference. Write down the held-fixed choices\n",
        "before trying a different experiment.\n",
        "\n",
        "At 1 m, the expression gives 2 arbitrary potential units. This is our\n",
        "reference calculation. It is a prediction of the stated example, not a new measurement.\n",
        "Its displayed digits help us compare implementations. They should not be read as a\n",
        "claim that physical inputs are known to six significant figures."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-008",
      "metadata": {},
      "source": [
        "import numpy as np\n",
        "import sympy as sp\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "q = sp.Symbol(\"q\", real=True)\n",
        "expression = sp.sympify(\"q**2+1\", locals={\"q\": q})\n",
        "reference_input = 1.0\n",
        "reference_output = float(expression.subs(q, reference_input))\n",
        "print(\"Input:\", reference_input, \"m\")\n",
        "print(\n",
        "    \"Predicted scalar potential along y=1:\",\n",
        "    reference_output,\n",
        "    \"arbitrary potential units\",\n",
        ")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-009",
      "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",
        "5 arbitrary potential units. The midpoint, at 0 m, gives\n",
        "1 arbitrary potential units. The upper endpoint gives 5 arbitrary potential units.\n",
        "Read these together with the assumptions: they describe different choices of horizontal coordinate\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-010",
      "metadata": {},
      "source": [
        "evaluate = sp.lambdify(q, expression, modules=\"numpy\")\n",
        "inputs = np.array([-2.0, 0.0, 2.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} arbitrary potential units\")\n",
        "assert np.all(np.isfinite(outputs))\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-011",
      "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 horizontal coordinate; the vertical axis shows scalar potential along y=1. 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-012",
      "metadata": {},
      "source": [
        "input_grid = np.linspace(-2.0, 2.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(\"Horizontal coordinate (m)\")\n",
        "ax.set_ylabel(\"Scalar potential along y=1 (arbitrary potential units)\")\n",
        "ax.legend()\n",
        "ax.grid(alpha=0.25)\n",
        "fig.tight_layout()\n",
        "plt.show()\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-013",
      "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",
        "scalar potential along y=1 change near the reference input? Its units are the output unit divided by\n",
        "the input unit. For this calculation, the derivative at 1 m is\n",
        "2 in those ratio units. Locally, the output increases as the\n",
        "input increases. This statement is local; the sign or size of the slope can be different\n",
        "elsewhere on the curve.\n",
        "\n",
        "\n",
        "$$\n",
        "f'(q) = 2 q\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-014",
      "metadata": {},
      "source": [
        "slope_expression = sp.diff(expression, q)\n",
        "slope_at_reference = float(slope_expression.subs(q, reference_input))\n",
        "changed_input = 1.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, \"arbitrary potential units\")\n",
        "print(\"Full expression:\", full_prediction, \"arbitrary potential units\")\n",
        "print(\n",
        "    \"Approximation difference:\",\n",
        "    full_prediction - linear_prediction,\n",
        "    \"arbitrary potential units\",\n",
        ")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-015",
      "metadata": {},
      "source": [
        "Here the changed input is 1.02 m. The tangent estimate is\n",
        "2.04 arbitrary potential units, while the full expression gives\n",
        "2.0404 arbitrary potential units. If the two values are close, it means the chosen\n",
        "input change is small enough for this local approximation at this point. It does not\n",
        "mean the entire model is linear. If the slope is zero, a quadratic or higher-order term\n",
        "may supply the leading change instead.\n",
        "\n",
        "This is also the beginning of uncertainty propagation. If the input has a small stated\n",
        "standard uncertainty, the magnitude of the slope times that uncertainty estimates one\n",
        "contribution to output uncertainty. Do not automatically use the same rule for a wide\n",
        "interval, a discontinuity, a turning point with zero first derivative, or several\n",
        "correlated uncertain inputs. Those situations need more of the model than one slope.\n",
        "\n",
        "### Check the derivative with numerical differences\n",
        "\n",
        "We can estimate the same slope from values on either side of the reference point.\n",
        "Subtract the lower output from the upper output and divide by twice the input step.\n",
        "Parentheses are essential: the entire output difference must be divided by the entire\n",
        "input interval. Without them, Python can execute a different mathematical expression\n",
        "while still producing a plausible number.\n",
        "\n",
        "The calculation below uses three decreasing step sizes. Each estimate is compared with\n",
        "the symbolic derivative, so the reference is independent of the numerical difference\n",
        "formula. Near an endpoint, it is acceptable here to evaluate a small extension only\n",
        "because the displayed mathematical expression is smooth there; such a check does not\n",
        "assert that extrapolated values describe additional physical cases."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-016",
      "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-017",
      "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",
        "horizontal coordinate inside the stated interval, predict whether scalar potential along y=1 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: A one-dimensional slice cannot determine the entire gradient without the other coordinate derivatives. 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 arbitrary potential units:\n",
        "the input unit in the integration cancels the input unit in the denominator of the slope.\n",
        "\n",
        "This statement is about the mathematics of this particular relationship. It does not\n",
        "assign a new physical meaning to an arbitrary area under a graph. For example, an area\n",
        "under force versus distance represents work, while an area under a different pair of\n",
        "quantities may represent something else or have no standard name. Always carry the\n",
        "axis units through the calculation before naming an integral."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-018",
      "metadata": {},
      "source": [
        "slope_function = sp.lambdify(q, slope_expression, modules=\"numpy\")\n",
        "endpoint_change = float(evaluate(2.0) - evaluate(-2.0))\n",
        "for points in [101, 201, 401]:\n",
        "    grid = np.linspace(-2.0, 2.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-019",
      "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",
        "- [Physics LibreTexts, \"Math\" appendix: fields, gradient, divergence, and curl](https://phys.libretexts.org/Bookshelves/University_Physics/Mechanics_and_Relativity_%28Idema%29/16%3A_Appendices/16.A%3A_Math).\n",
        "- [Physics LibreTexts, \"Nabla, Gradient and Divergence\"](https://phys.libretexts.org/Bookshelves/Astronomy__Cosmology/Celestial_Mechanics_%28Tatum%29/05%3A_Gravitational_Field_and_Potential/5.10%3A_Nabla_Gradient_and_Divergence).\n",
        "- [OpenStax, *University Physics Volume 2*, Section 6.2, \"Explaining Gauss's Law\"](https://openstax.org/books/university-physics-volume-2/pages/6-2-explaining-gausss-law).\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",
        "- [Benjamin Crowell, *Light and Matter*, Chapter 22, \"Fields of Force\"](https://open.umn.edu/opentextbooks/textbooks/light-and-matter)."
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.12"
    },
    "colab": {
      "name": "symbolic-vector-calculus.ipynb",
      "provenance": []
    },
    "tirta": {
      "lesson": "https://tirta.co/a-byte-of-physics/symbolic-vector-calculus",
      "source_sha256": "24117551cbce52522b58305d24026ea294636c2a2134373685bfe2923c8003ea"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
