Loading, please wait...

MCQ

How to create your own NumPy ufunc in Python?

This article demonstrate how you can create your own ufuncs in python.

         How to create your own NumPy ufunc in Python?

 

1. How to create your own ufunc in python?

step 1: Define a function, as you do with normal functions in python.    

step 2: Add it to your NumPy ufunc library with the frompyfunc() method.

Syntax:

frompyfunc(function , inputs, outputs)

   

Parameters:  

Function: The name of the function.  

Inputs: number of input arrays. 

Outputs: the number of output arrays.

For Example:

import numpy as np

def myMultiplier( x,y,z):

    return x*y*z



myMultiplier =np.frompyfunc(myMultiplier, 3, 1)  

print(myMultiplier([10,20,30] , [20,30,40] ,[30,40,50]))  


output:[6000 24000 60000]





  

Note: check if a function is ufunc or not using type(function) 

a ufunc should return <class‘numpy.ufunc’ > .  

   For Example:

import numpy as np

def myMultiplier( x,y,z):

    return x*y*z


#type of myMultiplier function    

print(type(myMultiplier))


#output:<class 'function'>

myMultiplier =np.frompyfunc(myMultiplier, 3, 1)  

print(type(myMultiplier))


#after adding myMultiplier function to ufunc the type of myMultiplier is changed as

# <class 'numpy.ufunc'>  


MCQ

Related Article