Vectorised Arithmetic

Describing the operation instead of writing the loop - and the two habits that undo the benefit.

Overview

Operators apply to every element

a + b adds the arrays elementwise. So do -, *, /, //, % and **. A scalar applies to every element: a * 10 scales the whole array.

The one to be careful with is *. On arrays it is elementwise multiplication, not matrix multiplication. Matrix multiplication is @, and confusing the two produces an array of the wrong shape or, worse, the right shape and the wrong numbers. That has its own module later.

Comparisons work the same way and give a boolean array: a > 2 is [False, False, True, True], not a single answer. Using that in an if raises, because NumPy refuses to guess whether you meant "any" or "all".

Worth knowing

Every arithmetic operator works elementwise, including with a scalar. * is elementwise multiplication, not a dot product.
ufuncs like np.sqrt apply to a whole array; math.sqrt takes one number and raises on an array.
Float division by zero gives inf or nan with a warning rather than an exception. Python would have raised.
a += 1 writes in place; a = a + 1 allocates a new array and rebinds the name. Aliases see one and not the other.
Indexing an array element-by-element from Python is slower than the same loop over a list, because each value is boxed into an object.
The usual conversion is: compute the branches over the whole array, then combine them with np.where.

Check yourself

0 of …

Answer without scrolling back up.

  1. What does `*` do between two arrays?

  2. What does float division by zero produce in NumPy?

  3. How does `a += 1` differ from `a = a + 1`?

  4. Why is looping over an array in Python slower than looping over a list?

Cheat sheet

Vectorised Arithmetic

The one to be careful with is *. On arrays it is elementwise multiplication, not matrix multiplication. Matrix multiplication is @, and confusing the two produces an array of the wrong shape or, worse, the right shape and the wrong numbers. That has its own module later.

NUMPY · AI.Cruz.in/numpy/vectorised_arithmetic.html

About the author

AI.Cruz builds and maintains AI.Cruz. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.