Universal Functions

Overview

  • Time: 10 min

  1. Learn how to implement ufunc in Python.

  2. Understand how to use the vectorize decorator in Numba.

A universal function (ufunc) performs element-by-element operations on NumPy arrays. While creating traditional ufuncs in NumPy requires writing C code, Numba simplifies this process. With the vectorize() decorator, Numba can compile a pure Python function into a ufunc that operates on NumPy arrays with performance comparable to ufuncs written in C.

1@vectorize([float64(float64, float64)])
2def sinacosb_vect(a, b):
3    return math.sin(a) * math.cos(b)

Key Points

  1. Numba can simplify ufunc in Python.

  2. The vectorize decorator compiles a Python function into a ufunc.