A Byte of PhysicsLogo

Symbolic vector calculus

Vector calculus describes how scalar and vector fields change from point to point. Gradient, divergence, curl, and the Laplacian answer different questions and return different types of quantities. Their compact notation is useful only when the field, coordinates, units, and differentiability assumptions are clear.

Partial derivatives and the del operator

For Cartesian coordinates, the differential operator pronounced “del” is written

\[\nabla=\hat{\mathbf i}\frac{\partial}{\partial x}+\hat{\mathbf j}\frac{\partial}{\partial y}+\hat{\mathbf k}\frac{\partial}{\partial z}\]

A partial derivative changes one coordinate while holding the others fixed. For a temperature field \(T(x,y,z)\), the quantity \(\partial T/\partial x\) has units of temperature per length. It is a local rate of change, not a finite temperature difference by itself.

The symbolic expression for \(\nabla\) looks like a vector, but it is a differential operator. Its dot and cross combinations must act on a sufficiently smooth field. Formulas on this page use a fixed orthonormal Cartesian basis. Cylindrical, spherical, and other curvilinear systems require scale factors and derivatives of position-dependent basis vectors.

Gradient: from a scalar to a vector

For a scalar field \(f(x,y,z)\),

\[\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}\]

The gradient points in the direction of greatest local increase of the scalar field. Its dot product with a small displacement gives the first-order field change:

\[df=\nabla f\cdot d\mathbf r\]

For a unit direction \(\hat{\mathbf n}\), the directional derivative is \(D_{\hat{\mathbf n}}f=\nabla f\cdot\hat{\mathbf n}\). The gradient therefore contains all first-order directional change at a point.

Potential energy and conservative force are related by

\[\mathbf F=-\nabla U\]

The negative sign says force points toward decreasing potential energy. If \(U\) is measured in joules and position in metres, the gradient has joules per metre, equivalent to newtons.

Divergence: local outward flux density

For a vector field \(\mathbf F=(F_x,F_y,F_z)\),

\[\nabla\cdot\mathbf F=\frac{\partial F_x}{\partial x}+\frac{\partial F_y}{\partial y}+\frac{\partial F_z}{\partial z}\]

Divergence is a scalar. Positive divergence means a small region has net outward flux to first order; negative divergence indicates net inward flux. Zero divergence means the local outward and inward flux balance. It does not require the field itself to be zero.

For the linear field \(\mathbf F=(2x,-y,3z)\),

\[\nabla\cdot\mathbf F=2-1+3=4\]

If the field has units \([F]\) and coordinates have length units, divergence has units \([F]/\mathrm{length}\).

The divergence theorem connects this local derivative to total flux through a closed surface:

\[\iiint_V(\nabla\cdot\mathbf F)\,dV=\oiint_{\partial V}\mathbf F\cdot d\mathbf A\]

The boundary normal points outward. This theorem explains the source interpretation of divergence and underlies Gauss's law, subject to the field's regularity and any singular sources.

Curl: local circulation density

The Cartesian curl is

\[\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}\]

Curl is an axial vector. Its direction gives the positive local circulation axis by the right-hand rule. Its magnitude measures circulation per area in the shrinking-loop limit. A field can curve visually yet have zero curl, and a sparse arrow plot cannot prove a curl value.

For a two-dimensional field \(\mathbf F=(F_x(x,y),F_y(x,y),0)\), only the perpendicular component can be nonzero:

\[(\nabla\times\mathbf F)_z=\frac{\partial F_y}{\partial x}-\frac{\partial F_x}{\partial y}\]

For the rigid-rotation-like field \(\mathbf F=(-\omega y,\omega x,0)\), the curl is \((0,0,2\omega)\). The factor two is important: local angular velocity in rigid rotation is one half of the vorticity.

Stokes' theorem relates curl to circulation around a boundary curve:

\[\iint_S(\nabla\times\mathbf F)\cdot d\mathbf A=\oint_{\partial S}\mathbf F\cdot d\mathbf l\]

The surface normal and traversal direction must follow the right-hand orientation.

The Laplacian

Applying divergence to the gradient of a scalar field gives the scalar Laplacian:

\[\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}\]

The Laplacian compares a value with its local spatial neighborhood. It appears in the heat equation, wave equation, Poisson equation, and Schrödinger equation. Its units are the scalar field's units per length squared.

For a Cartesian vector field, a vector Laplacian may be applied component by component, but that simple component statement does not carry unchanged into every coordinate system. Naming whether an operator acts on a scalar or vector avoids ambiguous code.

Symbolic differentiation as an expression transformation

A symbolic algebra system represents a formula as an expression tree rather than as a single evaluated number. Differentiation recursively applies rules such as linearity, the product rule, and the chain rule. For the gradient, it differentiates one scalar expression with respect to each coordinate. For divergence and curl, it differentiates selected component expressions and combines them with the required signs.

import sympy as sp

x, y, z = sp.symbols("x y z", real=True)
coordinates = (x, y, z)
scalar_field = x**2 + y**2 + z**2
gradient = sp.Matrix([sp.diff(scalar_field, q) for q in coordinates])
print("Gradient:", gradient)
vector_field = sp.Matrix([x**2, y**2, z**2])
divergence = sum(sp.diff(vector_field[i], q) for i, q in enumerate(coordinates))
print("Divergence:", sp.simplify(divergence))
assert sp.simplify(divergence - 2 * (x + y + z)) == 0

Symbolic simplification can expose an exact zero, but it needs assumptions. Expressions involving absolute values, square roots, piecewise rules, or division can change form depending on whether variables are real, positive, or nonzero. A result should preserve its domain restrictions instead of cancelling factors across excluded points.

Estimating derivatives from sampled fields

When only numerical samples are available, a centered finite difference approximates a first derivative:

\[\frac{\partial F_x}{\partial x}(x,y)\approx\frac{F_x(x+h,y)-F_x(x-h,y)}{2h}\]

In two dimensions, central estimates of divergence and perpendicular curl are

\[\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}\]

and

\[(\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}\]
import numpy as np


def field(point):
    x, y = point
    return np.array([x**2, y**2])


def divergence_2d(point, step):
    dx, dy = np.array([step, 0.0]), np.array([0.0, step])
    derivative_x = (field(point + dx)[0] - field(point - dx)[0]) / (2 * step)
    derivative_y = (field(point + dy)[1] - field(point - dy)[1]) / (2 * step)
    return derivative_x + derivative_y


print(divergence_2d(np.array([1.0, 2.0]), 1e-3))
assert np.isclose(divergence_2d(np.array([1.0, 2.0]), 1e-3), 6.0)

Smaller \(h\) usually reduces truncation error at first, but it increases sensitivity to measurement noise and floating-point cancellation. At boundaries, a centered stencil may query outside the domain; one-sided differences, ghost values, or physical boundary conditions must be chosen deliberately. Different coordinate spacings require separate denominators.

Identities and their assumptions

For fields with sufficiently continuous mixed derivatives,

\[\nabla\times(\nabla f)=\mathbf 0,\qquad \nabla\cdot(\nabla\times\mathbf F)=0\]

These identities are excellent symbolic and numerical checks. Finite-difference implementations should approach them under grid refinement when compatible discrete operators and boundary treatments are used. Failure near a singularity or discontinuity does not automatically mean the algebraic identity is wrong; the smoothness assumptions may not apply there.

A curl-free field is locally expressible as a gradient under suitable conditions, but global conclusions also depend on the domain's topology. A hole or excluded singularity can allow nonzero circulation around a loop even where local curl vanishes. “Curl zero means conservative everywhere” is therefore incomplete without domain assumptions.

Checks for an implementation

Use analytic fields with known derivatives before trusting complicated data:

Vector-calculus notation compresses many component derivatives into a few symbols. The best way to keep it understandable is to track input and output types, explain the local physical meaning, expand the Cartesian components when checking signs, and separate exact symbolic identities from approximate numerical estimates.

A worked Python notebook

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 change when we change horizontal coordinate, while keeping the other choices fixed? The earlier sections explain the physical relationship. Here we turn one part of that relationship into a calculation that you can run, inspect, and change in Google Colab.

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 its useful range, and a plotting library will usually draw that number without asking whether the physical assumptions still hold. The selected interval is from -2 to 2 m. It gives us a specific domain to discuss instead of leaving the graph's range to a software default.

Use the notebook link above the lesson, run the setup cell, and then run the cells in order. The code below is also included there. NumPy handles the arrays of numerical values, SymPy keeps the equation symbolic, and Matplotlib draws the results. If these libraries or notebook cells are unfamiliar, start with Your first physics notebook.

State the relationship before choosing a graph

In this small example, q stands for horizontal coordinate, expressed in m. The output is scalar potential along y=1, expressed in arbitrary potential units. The equation below uses the numerical values in those units. Any fixed coefficients therefore carry the units needed to make the relation consistent. A value supplied in another unit must be converted before it enters this expression.

\[f(q) = q^{2} + 1\]

This is a function of one changing input. It is not a statement that the physical system has only one variable. We deliberately hold the other inputs fixed so that one cause of variation is visible. Changing several inputs at once would make it harder to tell which change produced the output difference. Write down the held-fixed choices before trying a different experiment.

At 1 m, the expression gives 2 arbitrary potential units. This is our reference calculation. It is a prediction of the stated example, not a new measurement. Its displayed digits help us compare implementations. They should not be read as a claim that physical inputs are known to six significant figures.

import numpy as np
import sympy as sp
import matplotlib.pyplot as plt

q = sp.Symbol("q", real=True)
expression = sp.sympify("q**2+1", locals={"q": q})
reference_input = 1.0
reference_output = float(expression.subs(q, reference_input))
print("Input:", reference_input, "m")
print(
    "Predicted scalar potential along y=1:",
    reference_output,
    "arbitrary potential units",
)

sp.Symbol declares a mathematical symbol. It does not assign a numerical measurement to that symbol. subs then replaces the symbol with our chosen input, and float converts the resulting symbolic number into a standard Python numerical value. Keeping these steps separate lets us inspect the equation before numerical substitution. It also prevents a later plot from becoming the only surviving record of the model.

Compare a few cases you can explain

Before drawing hundreds of points, calculate three. The lower endpoint gives 5 arbitrary potential units. The midpoint, at 0 m, gives 1 arbitrary potential units. The upper endpoint gives 5 arbitrary potential units. Read these together with the assumptions: they describe different choices of horizontal coordinate within the same example, with the other inputs held fixed.

These three values are a useful first check, but they do not establish the shape between them. Two endpoints can be equal even when the curve bends or oscillates in between. Likewise, a large change between endpoints does not tell us whether the relationship is linear. We need the equation and intermediate samples to answer those questions.

evaluate = sp.lambdify(q, expression, modules="numpy")
inputs = np.array([-2.0, 0.0, 2.0])
outputs = np.asarray(evaluate(inputs), dtype=float)
outputs = np.broadcast_to(outputs, inputs.shape)
for input_value, output_value in zip(inputs, outputs):
    print(f"{input_value:.6g} m -> {output_value:.6g} arbitrary potential units")
assert np.all(np.isfinite(outputs))

lambdify turns the symbolic expression into a numerical function. We explicitly select NumPy as its numerical backend so it can accept an array. The same expression now has two useful forms: one for algebra and one for calculating many cases. The assertion checks that the chosen inputs produce finite outputs. It would catch an infinity or an undefined numerical result, but a finite value can still be physically inappropriate.

Make a graph that answers the question

The horizontal axis shows horizontal coordinate; the vertical axis shows scalar potential along y=1. Every plotted point is a prediction of the same expression. We mark the reference case separately so that a reader can connect the earlier printed value to its place on the curve. The axis labels include units because a shape without a scale cannot tell us the size of a physical effect.

input_grid = np.linspace(-2.0, 2.0, 301)
output_grid = np.asarray(evaluate(input_grid), dtype=float)
output_grid = np.broadcast_to(output_grid, input_grid.shape)
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(input_grid, output_grid, label="Stated model")
ax.scatter([reference_input], [reference_output], label="Reference case", zorder=3)
ax.set_xlabel("Horizontal coordinate (m)")
ax.set_ylabel("Scalar potential along y=1 (arbitrary potential units)")
ax.legend()
ax.grid(alpha=0.25)
fig.tight_layout()
plt.show()

Look for a sign change, a turning point, or a region where the curve becomes steep. Connect each feature to the expression rather than to the colour of the line. If the curve has a minimum or maximum, changing the input in opposite directions may have similar effects on the output near that point. If it is nearly straight over a short interval, a local linear approximation may be useful even when the complete expression is nonlinear.

Increasing the number of samples makes the line smoother and may reveal features that a coarse grid missed. It does not improve the physical inputs or enlarge the model's validity range. For quantities that can take only discrete values, use the line as a guide to the relationship and interpret only the allowed input values. A plotting function does not enforce such restrictions for you.

Measure the local sensitivity

A derivative asks a more specific question than the whole graph: how quickly does scalar potential along y=1 change near the reference input? Its units are the output unit divided by the input unit. For this calculation, the derivative at 1 m is 2 in those ratio units. Locally, the output increases as the input increases. This statement is local; the sign or size of the slope can be different elsewhere on the curve.

\[f'(q) = 2 q\]

For a small input change, multiply the derivative by that change to estimate the output change. Then compare that estimate with a fresh evaluation of the full expression. The distinction between these two calculations matters: the derivative gives a tangent approximation, while substitution evaluates the chosen expression at the new point.

slope_expression = sp.diff(expression, q)
slope_at_reference = float(slope_expression.subs(q, reference_input))
changed_input = 1.02
linear_prediction = reference_output + slope_at_reference * (
    changed_input - reference_input
)
full_prediction = float(evaluate(changed_input))
print("Symbolic derivative:", slope_expression)
print("Tangent prediction:", linear_prediction, "arbitrary potential units")
print("Full expression:", full_prediction, "arbitrary potential units")
print(
    "Approximation difference:",
    full_prediction - linear_prediction,
    "arbitrary potential units",
)

Here the changed input is 1.02 m. The tangent estimate is 2.04 arbitrary potential units, while the full expression gives 2.0404 arbitrary potential units. If the two values are close, it means the chosen input change is small enough for this local approximation at this point. It does not mean the entire model is linear. If the slope is zero, a quadratic or higher-order term may supply the leading change instead.

This is also the beginning of uncertainty propagation. If the input has a small stated standard uncertainty, the magnitude of the slope times that uncertainty estimates one contribution to output uncertainty. Do not automatically use the same rule for a wide interval, a discontinuity, a turning point with zero first derivative, or several correlated uncertain inputs. Those situations need more of the model than one slope.

Check the derivative with numerical differences

We can estimate the same slope from values on either side of the reference point. Subtract the lower output from the upper output and divide by twice the input step. Parentheses are essential: the entire output difference must be divided by the entire input interval. Without them, Python can execute a different mathematical expression while still producing a plausible number.

The calculation below uses three decreasing step sizes. Each estimate is compared with the symbolic derivative, so the reference is independent of the numerical difference formula. Near an endpoint, it is acceptable here to evaluate a small extension only because the displayed mathematical expression is smooth there; such a check does not assert that extrapolated values describe additional physical cases.

input_span = 4.0
for fraction in [1e-2, 1e-3, 1e-4]:
    step = input_span * fraction
    upper = float(evaluate(reference_input + step))
    lower = float(evaluate(reference_input - step))
    numerical_slope = (upper - lower) / (2 * step)
    difference = numerical_slope - slope_at_reference
    print(f"step={step:.6g}: slope={numerical_slope:.6g}, difference={difference:.6g}")

For a smooth function, reducing the step often reduces the approximation error at first. Very small steps can eventually make subtraction of nearly equal floating-point values less reliable. Therefore “smaller” is not an unlimited guarantee of “better.” Compare the observed behaviour over a useful range of steps instead of choosing the smallest number the computer can represent.

An absolute slope difference is useful when the expected slope is near zero. A relative difference would divide by a very small reference and could look enormous even when the absolute discrepancy is tiny. Away from zero, a relative difference can help compare quantities with very different scales. The tolerance should reflect the question and the numerical method, rather than a universal decimal threshold copied into every test.

Change the example and preserve the reasoning

Make one copy of the reference calculation before editing it. Choose a second value of horizontal coordinate inside the stated interval, predict whether scalar potential along y=1 will rise or fall, and then evaluate the expression. Place the prediction and the result in a text cell. If they disagree, identify whether the mistake was in the sign, the unit conversion, the algebra, or the assumption about how the curve behaves.

Next choose a shorter plotting interval around the reference point. Compare the local curve with its tangent approximation. Then widen the interval again. The difference shows why a useful local estimate need not describe the whole range. Keep the axis labels and numerical scale visible when comparing the plots; automatic axis limits can make two different effects appear equally large.

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 to the setup that would violate that limit. State what new input, equation, or observation would be needed before trusting an answer in the changed situation. This last step connects the Python experiment to the physics instead of treating successful execution as the only criterion for a useful result.

Before saving, restart the runtime and run all cells in order. A result that depends on an earlier, now-deleted input cell is not reproducible from the saved notebook. Keep unrounded values for later calculations, round only the reported output, and label any new data as measured, assumed, or generated. The graph and printed values should remain traceable to the same expression and the same choices of inputs.

Recover the output change by integrating the slope

There is another way to check that the expression and its derivative describe the same relationship. Add up the small output changes predicted by the slope across the chosen input interval. In the continuous limit, this integral equals the output at the upper endpoint minus the output at the lower endpoint. The result has units of arbitrary potential units: the input unit in the integration cancels the input unit in the denominator of the slope.

This statement is about the mathematics of this particular relationship. It does not assign a new physical meaning to an arbitrary area under a graph. For example, an area under force versus distance represents work, while an area under a different pair of quantities may represent something else or have no standard name. Always carry the axis units through the calculation before naming an integral.

slope_function = sp.lambdify(q, slope_expression, modules="numpy")
endpoint_change = float(evaluate(2.0) - evaluate(-2.0))
for points in [101, 201, 401]:
    grid = np.linspace(-2.0, 2.0, points)
    slopes = np.asarray(slope_function(grid), dtype=float)
    slopes = np.broadcast_to(slopes, grid.shape)
    integrated_change = np.trapezoid(slopes, grid)
    print(
        points,
        "integrated change:",
        integrated_change,
        "endpoint change:",
        endpoint_change,
    )

The trapezoidal rule joins neighbouring slope samples with straight segments and adds their signed areas. A negative contribution remains negative; replacing every slope by its magnitude would calculate a different quantity. Increasing the sample count provides a practical refinement check. If the values do not settle toward the endpoint difference, first inspect the interval, singularities, and array ordering.

Do not conclude that two agreeing calculations prove the model is physically complete. Both use the same selected relationship, so an omitted effect would be omitted from both. Their agreement is evidence that the numerical tools implement that relationship consistently. Comparing with an independent experiment or a more appropriate physical model is a separate test.

Keep this comparison in the notebook when you change the expression. It is particularly useful after adding a coefficient, changing a sign convention, or converting an input unit. A code cell that produces a smooth graph can conceal these mistakes; a second calculation of the same output change gives you another place to notice them.

Sources


Share to: