w3resource

Create a custom ufunc in NumPy to compute x^2+2x+1


Custom ufunc with Multiple Operations:

Write a NumPy program that creates a custom ufunc that computes x^2 + 2x + 1 for each element in a NumPy array.

Sample Solution:

Python Code:

import numpy as np

# Define a custom function to compute x^2 + 2x + 1
def compute_expression(x):
    return x**2 + 2*x + 1

# Create a ufunc from the custom function using np.frompyfunc
compute_ufunc = np.frompyfunc(compute_expression, 1, 1)

# Create a 1D NumPy array of integers
array_1d = np.array([1, 2, 3, 4, 5])

# Apply the custom ufunc to the 1D array
result_array = compute_ufunc(array_1d)

# Print the original array and the resulting array
print('Original 1D array:', array_1d)
print('Resulting array after applying compute_ufunc:', result_array)

Output:

Original 1D array: [1 2 3 4 5]
Resulting array after applying compute_ufunc: [4 9 16 25 36]

Explanation:

  • Import Libraries:
    • Imported numpy as "np" for array creation and manipulation.
  • Define Custom Function:
    • Defined a custom function compute_expression that takes an input x and returns x^2+2x+1.
  • Create ufunc:
    • Create a ufunc from the custom function using np.frompyfunc. The function takes the custom function, the number of input arguments (1), and the number of output arguments (1).
  • Create 1D NumPy Array:
    • Create a 1D NumPy array named array_1d with integers [1, 2, 3, 4, 5].
  • Apply Custom ufunc:
    • Apply the custom ufunc compute_ufunc to the 1D array to obtain the result.
  • Print Results:
    • Print the original 1D array and the resulting array after applying the custom "ufunc".

Python-Numpy Code Editor: