codingstreets
Search
Close this search box.
numpy-universal-function

Creation of Own Numpy Universal Function in Python

In This Article, You Will Learn About Creation of Numpy Universal Function.

Numpy Universal Function – Before moving ahead, let’s know a bit of Python Numpy Universal

Create Your Own ufunc

First of all, usually define a function in Python, then add it to with the frompyfunc() method of NumPy ufunc library.

The method frompyfunc() includes arguments –

function – Function name.

inputs -  Represents the number of input arguments (arrays).

outputs – Shows the number of output arrays.

Example – Creating our ufunc by adding elements of an array. 

import numpy as np

def my_func(a, b):
   return a+b
myadd = np.frompyfunc(my_func, 2, 1)

print(my_func([11, 12, 13, 14], [15, 16, 17, 18]))
Output -

[25 28 30 32] 

As shown above, it returned an array of shape 1×4 after adding both list’s numbers.

Check if a Function is a ufunc

Check function type to know whether a function is unfunc or not, a ufunc returns <class ‘numpy.ufunc’>.  

Example – Checking whether a function is a ufunc or not.

A ufunc should return <class ‘numpy.ufunc’> to be universal function.

import numpy as np

print(type(np.add))
Output - 

<class 'numpy.ufunc'>

As shown above, it returned code <class ‘numpy.ufunc’> that shows it is ab ubfunc.

Example – Checking the type of another function i.e., concatenate().

import numpy as np

print(type(np.concatenate))
Output - 

<class 'builtin_function_or_method'>

Example – Checking the type of something that does not have existence. 

import numpy as np

print(type(np.hurreye))
Output - 

AttributeError: module 'numpy' has no attribute 'hurreye'

As a result, it returned an error because module ‘numpy’ has no attribute ‘hurreye’.

Example – Using an if statement to check whether the function is a ufunc or not.

import numpy as np

if type(np.subtract) == np.ufunc:
  print('subtract is ufunc')
else:
  print('subtract is not ufunc')

If you find anything incorrect in the above-discussed topic and have any further questions, please comment below.

Like us on

Recent Post

Popular Post

Top Articles

Archives
Categories

Share on