Creating Ufunc
Submitted by moazkhan on Thursday, July 9, 2020 - 23:22.
In this tutorial you will learn:
- How to create own ufunc?
- Checking types of funcs?
- Python Syntax
Creating a ufunc
NumPy provides programmers a flexibility to create a ufunc by letting the programmers define a ufunc and adding that function in NumPy ufunc library using the inbuilt method “frompyfunc”. “frompyfunc” function takes in 3 mandatory parameters- The name of function, but before passing the function as argument the function has to be defined.
- Number of inputs of the defined function
- Number of output from the defined function
- #importing the NumPy library
- import numpy as np
- #defining the function
- def subs(x, y):
- return x-y
- #Here we are adding the subtraction func "subs" to the ufunc lib,we are giving in the parameters with two input values and resultantly one output value
- subs = np.frompyfunc(subs, 2, 1)
- #Here we are declaring two arrays
- array_a=[10,20,30,40]
- array_b=[1,2,3,4]
- #Using the arrays as parameters for input into the subs() function
- array_c=subs(array_a,array_b)
- #here we are printing the result
- print ("Result after subtraction of 2 arrays")
- print(array_c)
Type of functions
We can know the type of each function whether it’s a built-in function or a universal function using the type() function. This function takes in a function name and returns its type. In this example we will be finding the type of a function which is a ufunc and is used to carry out subtraction operation- import numpy as np
- #printing type of the function “subtract”
- print ("Type of the function 'Subtract()'")
- print(type(np.subtract))
- import numpy as np
- #printing type of the function “hsplit”
- print ("Type of the function 'hsplit()'")
- print(type(np.hsplit))
- import numpy as np
- #name of function is given here
- funcName = np.subtract
- #here we get the type of function
- tfunc = type(funcName)
- #here we are converting the type object to a string
- tfunc = str(tfunc)
- #applying if and else statements
- if tfunc == "<class 'numpy.ufunc'>":
- print('The function is a universal function')
- elif tfunc == "<class 'function'>":
- print('The function is a built-in function')
- else:
- print('It is not a built-in nor a universal function')
Add new comment
- 80 views