Open In App

Create your own universal function in NumPy

Last Updated : 28 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Create Our Own Universal Function in NumPy

Below are the ways by which we can create our universal function in NumPy:

  1. Using frompyfunc() Function
  2. Using numpy.vectorize() Function

Creating Our Own Universal Function Using frompyfunc() method

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.

Python3




# using numpy
import numpy as np
 
# creating own function
def fxn(val):
  return (val % 2)
 
# adding into numpy
mod_2 = np.frompyfunc(fxn, 1, 1)
 
# creating numpy array
arr = np.arange(1, 11)
print("arr     :", *arr)
 
# using function over numpy array
mod_arr = mod_2(arr)
print("mod_arr :", *mod_arr)


Output :

arr     : 1 2 3 4 5 6 7 8 9 10
mod_arr : 1 0 1 0 1 0 1 0 1 0

Create Own Universal Function Using np.vectorize() Function

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.

Python3




import numpy as np
 
def circle_area(radius):
    return np.pi * radius**2
 
# Create a vectorized version of the function
circle_ufunc = np.vectorize(circle_area)
 
# Test the ufunc with a single value
radius_values = np.array([1, 2, 3, 4])
areas = circle_ufunc(radius_values)
print(areas)


Output:

[ 3.14159265 12.56637061 28.27433388 50.26548246]


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads