Vectorized Math Functions
Introduction
Welcome to Vectorized Operations. We’re at Lesson 5 of 5, the final lesson in this course. So far, we’ve combined numbers and arrays with arithmetic operators. Now we’ll add NumPy math functions to our toolkit: square roots, absolute values, rounding, and exponentials. We’ll use them to calculate distances, prediction errors, taxed prices, and a deposit’s growth, applying each function across a whole array in one expression.
Square Roots: np.sqrt for Distances
Arithmetic can square values, but finding a square root calls for a function. NumPy math functions work element by element on arrays. We can pass a whole expression to np.sqrt, so the square root is taken for each result of dx ** 2 + dy ** 2. This is the distance formula applied to matching horizontal and vertical distances. For these paired observations, we use same-length arrays whose entries correspond position by position. As always, we import NumPy as np first; the later snippets in this lesson use the same import.
The powers are calculated first, then added position by position; np.sqrt acts on the resulting array. The result is a new array of distances. Square roots produce floating-point results, even when the answers are whole numbers.
Each value is the straight-line distance for one pair; for example, the first pair, 3 and 4, gives 5.

Absolute Values: np.abs for Error Sizes
A difference tells us which value is larger, but a prediction error is often about how far off the prediction was, regardless of direction. np.abs makes negative values positive and leaves positive values unchanged. Here, actual - predicted can have either sign; wrapping that difference in np.abs gives the size of each error. This applies the function to the whole array, just as np.sqrt did for distances.
The arrays are paired by position, so each actual delivery time is compared with its matching prediction. Subtracting first preserves the signed difference; np.abs then returns nonnegative error sizes in a new array.
The errors are positive whether the prediction was too low or too high. We keep the order of subtraction clear because it shows which values are being compared, even though the absolute errors do not show direction.
