w3resource

How to define and apply a Custom ufunc with Broadcasting in NumPy


14. Custom Ufunc: 3x + 4y Operation

Custom ufunc with Broadcasting:

Write a Numpy program that defines a custom ufunc that computes 3x + 4y for elements x and y from two arrays, and apply it to 2D arrays.

Sample Solution:

Python Code:

import numpy as np

# Define the custom ufunc
def custom_func(x, y):
    return 3 * x + 4 * y

# Convert the Python function to a NumPy ufunc
custom_ufunc = np.frompyfunc(custom_func, 2, 1)

# Create two 2D NumPy arrays
array_x = np.array([[1, 2], [3, 4]])
array_y = np.array([[5, 6], [7, 8]])

# Apply the custom ufunc to the 2D arrays with broadcasting
result_array = custom_ufunc(array_x, array_y)

# Convert the result to a numeric type array if needed
result_array = result_array.astype(np.float64)

# Print the input arrays and the result array
print("Array X:")
print(array_x)

print("\nArray Y:")
print(array_y)

print("\nResult Array (3x + 4y):")
print(result_array)

Output:

Array X:
[[1 2]
 [3 4]]

Array Y:
[[5 6]
 [7 8]]

Result Array (3x + 4y):
[[23. 30.]
 [37. 44.]]

Explanation:

  • Import NumPy Library:
    • Import the NumPy library to handle arrays and "ufunc" creation.
  • Define the Custom Function:
    • Create a custom Python function custom_func that computes 3x + 4y.
  • Convert to NumPy ufunc:
    • Use np.frompyfunc() to convert the Python function to a NumPy ufunc, specifying that the function takes two input arguments and returns one output.
  • Create 2D Arrays:
    • Define two 2D NumPy arrays ‘array_x’ and ‘array_y’ with some example data.
  • Apply the Custom ufunc:
    • Use the custom "ufunc" with broadcasting to compute the result array from 'array_x' and 'array_y'.
  • Convert Result to Numeric Type:
    • If needed, convert the result array to a specific numeric type (e.g., np.float64) for further numerical operations.
  • Finally print the original input arrays and the resulting array to verify the computation.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to define a custom ufunc that computes 3x + 4y for paired elements from two 2D arrays and then apply it element-wise.
  • Write a Numpy program to create a custom ufunc for 3x + 4y and then test it on edge cases such as zeros and negative numbers in two matrices.
  • Write a Numpy program to implement a custom ufunc for 3x + 4y, then chain it with another ufunc that scales the result by a factor of 0.5.
  • Write a Numpy program to define and benchmark a custom ufunc for 3x + 4y against a vectorized expression performing the same operation.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Divide each 2D slice of 3D array by 1D array using np.divide.
Next: Comparing performance of custom ufunc and Python loop in NumPy.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.