Create Your Own ufunc

M.Ramya

  How to Create Your Own Universal Function (ufunc) in NumPy

In NumPy, ufuncs (universal functions) are used to perform element-wise operations on arrays efficiently.
But did you know you can create your own ufunc using Python functions?

Here’s how you can do it:

Steps:

Define a regular Python function (just like any other function).
Use np.frompyfunc() to convert it into a ufunc.
np.frompyfunc() Syntax:
numpy.frompyfunc(function, inputs, outputs)
  • function: Your custom function name.
  • inputs: Number of input arguments (usually the number of arrays you want to process).
  • outputs: Number of outputs your function returns.

 Program: 

Create a Custom ufunc for Addition
import numpy as np
# Step 1: Define a simple function
def myadd(x, y):
    return x + y
# Step 2: Convert it into a ufunc
myadd = np.frompyfunc(myadd, 2, 1)
# Step 3: Use it with NumPy arrays
result = myadd([1, 2, 3, 4], [5, 6, 7, 8])
print(result)

Output:

[6 8 10 12]

How to Check if a Function is a NumPy ufunc

In NumPy, ufuncs (universal functions) are functions that operate element-wise on arrays, such as np.add or np.subtract.
To check whether a function is a ufunc, you can inspect its type.

Program: 

Check if a function is a ufunc:
import numpy as np
print(type(np.add))

Output:

<class 'numpy.ufunc'>
This confirms that np.add is a ufunc.

Program: 

Check a function that is not a ufunc:
import numpy as np
print(type(np.concatenate))

Output:

<class 'function'>
np.concatenate is a regular function, not a ufunc.

Program: 

Check an invalid function (this will raise an error):
import numpy as np
print(type(np.blahblah))

Output:

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

 Program:

You can use an if statement to check whether a function is a ufunc:
import numpy as np
if type(np.add) == np.ufunc:
    print("add is a ufunc")
else:
    print("add is not a ufunc")

Output:

add is a ufunc

Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send