Vectorised arithmetic and ufuncs

Intermediate

Introduction

The point of NumPy is to write calculations on whole arrays as if they were single numbers. Converting temperatures, applying a tax rate, computing distances: each is one line, with no loop, and runs at compiled speed. This lesson covers the arithmetic operators and the universal functions that make this possible, and the one place where NumPy behaves very differently from plain Python: dividing by zero.

How it works

Every arithmetic operator works element-wise between arrays of the same shape:

a = np.array([1, 2, 3, 4])
b = np.array([10, 20, 30, 40])
print(a + b)     # [11 22 33 44]
print(b / a)     # [10. 10. 10. 10.]
print(b // 3)    # [ 3  6 10 13]
print(a ** 2)    # [ 1  4  9 16]

A scalar, a single number, combines with every element: a * 2 doubles them all, a - a.mean() centres them. / always gives floats; // and % keep integers and follow Python's rules for negative numbers.

Universal functions, or ufuncs, apply a mathematical function to every element: np.sqrt, np.exp, np.log, np.abs, np.sin, np.round and dozens more. They are the array versions of the math module, and they accept arrays of any shape:

print(np.sqrt(np.array([1, 4, 9])))   # [1. 2. 3.]

Plain Python raises ZeroDivisionError for 1 / 0. NumPy follows the floating-point standard instead: dividing a positive number by zero gives inf, a negative one -inf, and 0 / 0 gives nan (not a number). It prints a RuntimeWarning and carries on:

print(np.array([1, -1, 0]) / 0)
# RuntimeWarning: divide by zero encountered in divide
# RuntimeWarning: invalid value encountered in divide
# [ inf -inf  nan]

The same happens with np.log(0) (-inf), np.log(-1) and np.sqrt(-1) (nan). A nan then spreads through later calculations, since any arithmetic with nan gives nan, so check for it with np.isnan before summarising data.

Example

# Element-wise arithmetic and universal functions, modelled one element at a time.
import math

a = [1, 2, 3, 4]
b = [10, 20, 30, 40]
print("a + b:", [x + y for x, y in zip(a, b)])
print("a * 2:", [x * 2 for x in a])
print("b / a:", [y / x for x, y in zip(a, b)])
print("b // 3:", [y // 3 for y in b])
print("b % 7:", [y % 7 for y in b])
print("a ** 2:", [x**2 for x in a])
print("sqrt(a):", [round(math.sqrt(x), 3) for x in a])
print("a > 2:", [x > 2 for x in a])
Open in compiler

Line by line

  1. Each line models one NumPy operator: a list comprehension does to every element what NumPy does in one compiled loop.
  2. b / a gives floats, and b // 3 and b % 7 keep whole numbers.
  3. math.sqrt applied to each element models the ufunc np.sqrt.
  4. A comparison gives one boolean per element.

Expected result

a + b: [11, 22, 33, 44]
a * 2: [2, 4, 6, 8]
b / a: [10.0, 10.0, 10.0, 10.0]
b // 3: [3, 6, 10, 13]
b % 7: [3, 6, 2, 5]
a ** 2: [1, 4, 9, 16]
sqrt(a): [1.0, 1.414, 1.732, 2.0]
a > 2: [False, False, True, True]

In the real world

Unit conversions, price calculations, physics simulations and image filters are all written as array arithmetic. Machine-learning code applies ufuncs such as np.exp and np.log to millions of values per step. Data pipelines check for nan and inf after every division, because a single bad value can spoil a whole average.

Common mistakes

  • Writing a Python loop over array elements to do arithmetic.
  • Using the math module on arrays: math.sqrt(a) fails; use np.sqrt(a).
  • Ignoring RuntimeWarnings, and averaging data that now contains inf or nan.
  • Expecting / to keep integers: it always returns floats; use // for whole numbers.

Best practices

  • Express calculations as whole-array formulas.
  • Use NumPy's functions (np.sqrt, np.log) for arrays and the math module only for single numbers.
  • After divisions and logarithms, check np.isnan(x).any() and np.isinf(x).any().

Summary

Arithmetic operators and ufuncs apply element by element, and a scalar combines with every element, so whole calculations need no loops. Division by zero and invalid operations give inf, -inf or nan with a RuntimeWarning instead of an error, and those values spread, so check for them.

Quick check

1. What does np.array([1, 2, 3]) * 2 give?
2. What does np.array([5, 0]) / 0 give?
3. Which applies a square root to every element of an array a?
4. What is nan + 1?

Key takeaways

  • Operators on arrays work element by element; a single number applies to every element.
  • ufuncs such as np.sqrt and np.exp apply a function to every element in compiled code.
  • Division by zero gives inf or nan with a warning, not an error.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.