![]() |
VOOZH | about |
Universal functions in NumPy are simple mathematical functions. It is just a term that we gave to mathematical functions in the Numpy library. Numpy provides various universal functions that cover a wide variety of operations. However, we can create our universal function in Python. In this article, we will see how to create our own universal function using NumPy.
Below are the ways by which we can create our universal function in NumPy:
Numpy.frompyfunc() function allows to creation of an arbitrary Python function as Numpy ufunc (universal function). In this example, a custom Python function fxn that calculates the modulo 2 operation is converted into a NumPy universal function using np.frompyfunc.
Output :
arr : 1 2 3 4 5 6 7 8 9 10
mod_arr : 1 0 1 0 1 0 1 0 1 0
In this example, the Python function circle_area computes the area of a circle given its radius. Using np.vectorize(), a vectorized universal function circle_ufunc is created from this Python function. When applied to an array radius_values containing radii, the ufunc computes the areas for each radius, producing an array areas which is then printed.
Output:
[ 3.14159265 12.56637061 28.27433388 50.26548246]