NumPy Lesson 13 – Universal Functions | Dataplexa

Universal Functions (ufuncs) in NumPy

Universal functions, commonly called ufuncs, are fast, vectorized functions that operate element-by-element on NumPy arrays.

They are one of the main reasons NumPy is extremely fast compared to regular Python loops.


What Are Universal Functions?

A universal function is a function that:

  • Operates on NumPy arrays element-wise
  • Supports broadcasting
  • Is implemented in optimized C code
  • Returns a new array as output

Instead of looping through each value manually, ufuncs apply the operation to all elements at once.


Simple Example: Square Root

Let’s start with a simple ufunc: np.sqrt().

import numpy as np

numbers = np.array([1, 4, 9, 16])
result = np.sqrt(numbers)

print(result)

Output:

[1. 2. 3. 4.]

Each element is processed individually, but without writing a loop.


Common Mathematical ufuncs

NumPy provides many built-in mathematical ufuncs.

  • np.add()
  • np.subtract()
  • np.multiply()
  • np.divide()
  • np.power()

These functions work element-wise on arrays.


Example: Addition Using ufunc

a = np.array([10, 20, 30])
b = np.array([1, 2, 3])

result = np.add(a, b)
print(result)

Output:

[11 22 33]

This produces the same result as a + b, but explicitly uses a ufunc.


Trigonometric ufuncs

NumPy also provides trigonometric functions. All angle values are in radians.

angles = np.array([0, np.pi/2, np.pi])
result = np.sin(angles)

print(result)

Output:

[0.0000000e+00 1.0000000e+00 1.2246468e-16]

The tiny number near zero is due to floating-point precision.


Exponential and Logarithmic ufuncs

Exponential and logarithmic operations are also handled by ufuncs.

values = np.array([1, 10, 100])

print(np.log10(values))
print(np.exp(values))

Output:

[0. 1. 2.]
[2.71828183e+00 2.20264658e+04 2.68811714e+43]

Comparison ufuncs

Comparison operations also use ufuncs and return boolean arrays.

data = np.array([5, 10, 15, 20])
result = data > 10

print(result)

Output:

[False False  True  True]

These boolean results are often used for filtering data.


Why ufuncs Are Faster

Universal functions are fast because:

  • They avoid Python loops
  • They execute compiled C code internally
  • They use optimized memory access

This makes them ideal for large datasets and numerical computations.


Practice Exercise

Exercise

Create a NumPy array and apply the following ufuncs:

  • Square root
  • Logarithm
  • Comparison (> value)

Expected Outcome

You should see element-wise transformations without using loops.


What’s Next?

In the next lesson, you will learn about the NumPy Random Module and how to generate random data for simulations and testing.