Skip to main content
Albero Academy

Universal Functions

Fast element-wise math functions — sqrt, log, exp, sin and friends.

Operations8 min

A universal function (ufunc) applies a mathematical operation element-wise across an entire array, in compiled C. NumPy ships fast versions of all the common maths functions.

Common ufuncs

element-wise math
a = np.array([1, 4, 9, 16])
np.sqrt(a) # [1. 2. 3. 4.]
np.log(a) # natural log of each
np.exp(a) # e**each
np.round(a * 1.5, 2)
np.abs(a - 10)
np.maximum(a, 5) # element-wise max against 5

Why not math.sqrt?

Binary ufuncs

Some ufuncs take two arrays and combine them element-wise — np.add, np.maximum, np.power — and they broadcast (next chapter):

two-array ufuncs
np.add(a, b) # same as a + b
np.power(a, 2) # same as a ** 2
np.minimum(a, b) # element-wise minimum

Key takeaways

  1. 01ufuncs apply element-wise math across a whole array in compiled C.
  2. 02Common ones: sqrt, log, exp, round, abs, sin/cos.
  3. 03Use np.sqrt (not math.sqrt) on arrays — math functions only take scalars.
  4. 04Binary ufuncs (add, maximum, power) combine two arrays element-wise and broadcast.

Finished this chapter?

Mark it complete to track your progress through NumPy.