Create a custom ufunc for complex numbers in NumPy
NumPy: Universal Functions Exercise-18 with Solution
ufunc with Custom Data Types:
Write a NumPy program that creates a custom ufunc to operate on complex numbers in a NumPy array.
Sample Solution:
Python Code:
import numpy as np
# Define a custom function to operate on complex numbers
def custom_complex_operation(z):
return z.real + z.imag
# Convert the custom function to a NumPy ufunc
custom_ufunc = np.frompyfunc(custom_complex_operation, 1, 1)
# Create a NumPy array of complex numbers
complex_array = np.array([1+2j, 3+4j, 5+6j])
# Apply the custom ufunc to the complex array
result_array = custom_ufunc(complex_array)
# Print the original complex array and the result array
print("Original Complex Array:")
print(complex_array)
print("\nResult Array after applying custom ufunc:")
print(result_array)
Output:
Original Complex Array: [1.+2.j 3.+4.j 5.+6.j] Result Array after applying custom ufunc: [3.0 7.0 11.0]
Explanation:
- Import NumPy Library:
- Import the NumPy library to handle array operations.
- Define Custom Function:
- Create a custom Python function custom_complex_operation to operate on complex numbers. This function returns the sum of the real and imaginary parts of a complex number.
- Convert to NumPy ufunc:
- Use "np.frompyfunc()" to convert the custom function to a NumPy ufunc, specifying that the function takes one input and returns one output.
- Create Complex Array:
- Define a NumPy array complex_array containing complex numbers.
- Apply Custom ufunc:
- Use the custom "ufunc" to operate on the complex array, storing the results in 'result_array'.
- Finally print the original complex array and the resulting array after applying the custom "ufunc" to verify the operation.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics