w3resource

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

NumPy: Universal Functions Exercise-7 with Solution

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:

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

Previous: Create array using np.where based on condition in NumPy.
Next: Apply np.exp, np.log, and np.sqrt ufuncs to transform a NumPy array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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/create-a-custom-ufunc-in-numpy-to-compute-x-exponent-2-plus-2-x-plus-1.php