Universal Functions in NumPy

NoteQuestion

What is a universal function?

TipAnswer

A universal function, or ufunc, is a function that performs element-wise operations on ndarrays. You can think of them as fast vectorized wrappers for simple functions that take one or more scalar values and produce one or more scalar results.

Here is an interesting passage from the official NumPy documentation: NumPy hands off array processing to C, where looping and computation are much faster than in Python. To exploit this, programmers using NumPy eliminate Python loops in favor of array-to-array operations. vectorization can refer both to the C offloading and to structuring NumPy code to leverage it.

NoteQuestion

What is the rationale for using ufuncs?

TipAnswer

Per the previous point, using a ufunc offer substantial performance advantages vis a’ vis non-vectorized code — i.e., code using built-in Python iterators.

NoteQuestion

What are the ufunc options available in NumPy?

TipAnswer

There are circa sixty universal functions implemented in NumPy. For the sake of convenience, the full list of ufunc options is available in the NumPy documentation. The following sections of the current chapter will illustrate how to use some of the popular central ufuncs in NumPy.