w3resource

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


7. Custom Ufunc: Quadratic Expression

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".

For more Practice: Solve these Related Problems:

  • Write a Numpy program to define a custom ufunc that computes x² + 2x + 1 and then test it on an array with both positive and negative values.
  • Write a Numpy program to create a custom ufunc for x² + 2x + 1 and chain it with np.sqrt to compute the square root of the result.
  • Write a Numpy program to implement a custom ufunc for a quadratic function and compare its output with a vectorized expression of the same formula.
  • Write a Numpy program to define and apply a custom ufunc for x² + 2x + 1 on a large random array, then profile its performance.

Go to:


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.

Python-Numpy Code Editor:

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

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.