← Back to NumPy Course | Chapter 6: Math Operations | Lesson 3 of 7

Universal functions (ufuncs)

ufuncs are NumPy's fast built-in functions that work on every element of an array at once.
Syntax
python
np.sqrt(arr)
np.exp(arr)
np.add(arr1, arr2)
np.sin(arr)

Universal functions (ufuncs)

A universal function is a vectorized function applied element by element, such as np.sqrt, np.exp, np.sin, np.add and np.maximum. They support broadcasting and optional arguments like out and where.

Binary ufuncs also offer methods such as reduce and accumulate.

Note: np.add.reduce(a) equals a.sum(), and np.add.accumulate(a) gives running totals.

Example: Universal functions (ufuncs)

python
import numpy as np

a = np.array([1, 4, 9, 16])
print(np.sqrt(a))
print(np.exp(np.array([0, 1])))
print(np.maximum(a, 5))
print(np.add.accumulate(a))

# Output:
# [1. 2. 3. 4.]
# [1.         2.71828183]
# [ 5  5  9 16]
# [ 1  5 14 30]
Related Topics
Common Mistakes
  1. Using math.sqrt on arrays, which only accepts scalars
  2. Writing a loop where a ufunc exists
  3. Forgetting ufuncs return new arrays
Chapter Summary
  • ufuncs operate element-wise
  • They support broadcasting
  • Prefer np.sqrt over math.sqrt for arrays
  • reduce and accumulate aggregate
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.