How to define and apply a Custom ufunc with Broadcasting in NumPy
NumPy: Universal Functions Exercise-14 with Solution
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.
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/numpy/define-and-apply-a-custom-ufunc-with-broadcasting-in-numpy.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics