A Byte of PhysicsLogo

Vectors as arrays

A vector is a physical quantity with both magnitude and direction. Displacement, velocity, acceleration, force, and momentum are common examples. A scalar, such as mass or temperature, has a magnitude but no spatial direction. This distinction is physical: changing the direction of a force can change the motion even when the force's magnitude stays the same.

An arrow is a useful geometric picture of a vector. Its length represents magnitude, and its arrowhead represents direction. A computer cannot store that picture as an abstract physical object, so it stores components such as \([v_x,v_y]\). Those numbers describe the arrow relative to a declared coordinate basis.

From an arrow to components

Choose perpendicular unit vectors \(\hat{\mathbf i}\) and \(\hat{\mathbf j}\) along the positive horizontal and vertical axes. A two-dimensional vector can be written as

\[\mathbf v=v_x\hat{\mathbf i}+v_y\hat{\mathbf j}\]

The scalar component \(v_x\) tells how much of the vector points along the first basis direction. The component \(v_y\) does the same for the second. A negative component points opposite to its positive basis direction. The components carry the same physical units as the vector. A velocity component is measured in units of velocity, not in a unitless array index.

The component list can therefore be stored in order:

import numpy as np

horizontal_velocity = 3.0
vertical_velocity = 4.0
east = np.array([1.0, 0.0])
north = np.array([0.0, 1.0])
velocity = horizontal_velocity * east + vertical_velocity * north
print("Velocity components (m/s):", velocity)

Changing the order to vertical-then-horizontal changes the meaning unless every consumer uses the same convention. Three-dimensional Cartesian vectors add a third component and unit vector. Higher-dimensional arrays are mathematically useful too, but not every list of numbers represents an ordinary arrow in physical space.

Magnitude and direction

Because the Cartesian basis directions are perpendicular and have unit length, the Pythagorean theorem gives the vector magnitude:

\[|\mathbf v|=\sqrt{v_x^2+v_y^2}\]

Magnitude is a scalar and cannot be negative. It is zero exactly when both components are zero. For the velocity \(\mathbf v=(3\hat{\mathbf i}+4\hat{\mathbf j})\,\mathrm{m/s}\), the speed is \(|\mathbf v|=5\,\mathrm{m/s}\). This familiar three-four-five result is a good test fixture because the exact answer is known before code is run.

The direction angle measured counterclockwise from the positive horizontal axis is best computed with the two-argument arctangent:

\[\theta=\operatorname{atan2}(v_y,v_x)\]

Using only \(\tan^{-1}(v_y/v_x)\) loses quadrant information and fails when \(v_x=0\). The two-argument function uses the signs of both components. Angle units must still be stated: many programming languages return radians while human-facing examples often use degrees. The zero vector has no unique direction, so software should return an explicit absent value or diagnostic rather than inventing an angle.

def magnitude(vector):
    return float(np.linalg.norm(vector))


def direction_2d(vector, tolerance=1e-12):
    if magnitude(vector) <= tolerance:
        return None
    return float(np.arctan2(vector[1], vector[0]))


print(f"Speed: {magnitude(velocity):.1f} m/s")
print(f"Direction: {np.degrees(direction_2d(velocity)):.2f} degrees")

For extremely large or small components, a library hypot operation is often safer than squaring directly because it reduces avoidable overflow and underflow. That is a numerical improvement, not a change to the physics.

Addition, subtraction, and scaling

Vectors may be added only when they describe compatible physical quantities in the same basis and frame. Component addition is

\[\mathbf a+\mathbf b=(a_x+b_x)\hat{\mathbf i}+(a_y+b_y)\hat{\mathbf j}\]

Geometrically, placing the tail of the second arrow at the head of the first gives the same resultant. The component rule works because addition distributes over the basis vectors. Vector subtraction adds the opposite vector. Multiplication by a scalar changes every component by the same factor:

\[c\mathbf a=(ca_x)\hat{\mathbf i}+(ca_y)\hat{\mathbf j}\]

If \(c>0\), direction is preserved. If \(c<0\), direction reverses. If \(c=0\), the result is the zero vector.

Suppose a boat's velocity relative to the water is

\((4,1)\,\mathrm{m/s}\)

and the water's velocity relative to the shore is \((-1,2)\,\mathrm{m/s}\). When all components use the same east-north basis, the boat's velocity relative to the shore is

\[\mathbf v_{BS}=\mathbf v_{BW}+\mathbf v_{WS}=(3,3)\,\mathrm{m/s}\]

The subscripts matter. They prevent an attractive but meaningless addition of vectors defined in inconsistent frames.

# Both velocities are in m/s in the same east/north frame.
first = np.array([4.0, 1.0])
second = np.array([-1.0, 2.0])
assert first.shape == second.shape
result = first + second
print("Sum (m/s):", result)
print("Difference (m/s):", first - second)

Unit vectors and normalization

A nonzero vector can be divided by its magnitude to produce a unit vector pointing in the same direction:

\[\hat{\mathbf v}=\frac{\mathbf v}{|\mathbf v|},\qquad |\hat{\mathbf v}|=1\]

Normalization separates direction from size. It is useful when a force has a known magnitude but must point toward a target. The operation is undefined for the zero vector because division by zero cannot choose one direction from infinitely many. Testing only for exact floating-point zero is often too brittle. A tolerance should be chosen with the scale and units of the problem, and the program should make the near-zero policy visible.

def normalize(vector, tolerance=1e-12):
    norm = np.linalg.norm(vector)
    if norm <= tolerance:
        raise ValueError("A near-zero vector has no reliable direction.")
    return vector / norm


unit_direction = normalize(velocity)
print("Unit direction:", unit_direction)
assert np.isclose(np.linalg.norm(unit_direction), 1.0)

Displacement is not position

Position is a vector from a chosen origin to an object. Displacement is the difference between final and initial positions:

\[\Delta\mathbf r=\mathbf r_f-\mathbf r_i\]

If the origin moves, both position vectors can change even while their difference stays the same. This is one reason an array of position components must name its origin and frame. Distance travelled is different again: it is a nonnegative scalar accumulated along a path and generally is not the magnitude of displacement except for suitable straight, unreversed motion.

Array operations that are not vector physics

Programming libraries may offer elementwise multiplication, concatenation, sorting, or broadcasting for arrays. These operations do not automatically have vector meaning. For example, multiplying corresponding components of two vectors produces another array, but it is neither the dot product nor the cross product. Sorting components changes which value belongs to which basis direction. Concatenating two three-component vectors produces six numbers, not one physical vector in ordinary space.

The type system should distinguish positions, displacements, velocities, and generic numeric arrays when practical. At minimum, names and runtime checks should preserve dimension, units, basis, and frame. A compact representation is useful only while its meaning remains inspectable.

Checks that reveal mistakes

Vector code should be tested against geometry and algebra rather than only copied examples. Useful checks include:

These checks cannot establish that the input measurements or physical model are correct. They do establish that the representation obeys the vector rules it claims to implement. A physical vector is independent of the coordinate labels used to record it; the next lesson makes that distinction precise by changing coordinate bases.

A worked Python notebook

Hold the vertical velocity at 4 metres per second while changing the horizontal component. The question for this calculation is precise: how does speed change when we change horizontal velocity, 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.

Both components must use the same reference frame and perpendicular Cartesian axes. 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 -6 to 6 m/s. 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 velocity, expressed in m/s. The output is speed, expressed in m/s. 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) = \sqrt{q^{2} + 16}\]

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 3 m/s, the expression gives 5 m/s. 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("sqrt(q**2+16)", locals={"q": q})
reference_input = 3.0
reference_output = float(expression.subs(q, reference_input))
print("Input:", reference_input, "m/s")
print("Predicted speed:", reference_output, "m/s")

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 7.2111 m/s. The midpoint, at 0 m/s, gives 4 m/s. The upper endpoint gives 7.2111 m/s. Read these together with the assumptions: they describe different choices of horizontal velocity 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([-6.0, 0.0, 6.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/s -> {output_value:.6g} m/s")
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 velocity; the vertical axis shows speed. 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(-6.0, 6.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 velocity (m/s)")
ax.set_ylabel("Speed (m/s)")
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 speed change near the reference input? Its units are the output unit divided by the input unit. For this calculation, the derivative at 3 m/s is 0.6 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) = \frac{q}{\sqrt{q^{2} + 16}}\]

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 = 3.06
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, "m/s")
print("Full expression:", full_prediction, "m/s")
print("Approximation difference:", full_prediction - linear_prediction, "m/s")

Here the changed input is 3.06 m/s. The tangent estimate is 5.036 m/s, while the full expression gives 5.03623 m/s. 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 = 12.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 velocity inside the stated interval, predict whether speed 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: Both components must use the same reference frame and perpendicular Cartesian axes. 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 m/s: 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(6.0) - evaluate(-6.0))
for points in [101, 201, 401]:
    grid = np.linspace(-6.0, 6.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: