Apply np.exp, np.log, and np.sqrt ufuncs to transform a NumPy array
8. Ufunc Chain: exp, log, and sqrt Transformations
Chaining ufuncs:
Write a NumPy program that creates a NumPy array and applies a sequence of ufuncs (np.exp, np.log, and np.sqrt) to transform the array.
Sample Solution:
Python Code:
import numpy as np
# Create a 1D NumPy array of integers
array_1d = np.array([1, 2, 3, 4, 5])
# Apply the np.exp ufunc to the array
exp_array = np.exp(array_1d)
# Apply the np.log ufunc to the resulting array from np.exp
log_array = np.log(exp_array)
# Apply the np.sqrt ufunc to the resulting array from np.log
sqrt_array = np.sqrt(log_array)
# Print the original array and the resulting arrays after each transformation
print('Original 1D array:', array_1d)
print('Array after applying np.exp:', exp_array)
print('Array after applying np.log:', log_array)
print('Array after applying np.sqrt:', sqrt_array)
Output:
Original 1D array: [1 2 3 4 5] Array after applying np.exp: [ 2.71828183 7.3890561 20.08553692 54.59815003 148.4131591 ] Array after applying np.log: [1. 2. 3. 4. 5.] Array after applying np.sqrt: [1. 1.41421356 1.73205081 2. 2.23606798]
Explanation:
- Import Libraries:
- Imported numpy as "np" for array creation and manipulation.
- Create 1D NumPy Array:
- Create a 1D NumPy array named 'array_1d' with integers [1, 2, 3, 4, 5].
- Apply np.exp ufunc:
- Applied the np.exp "ufunc" to the 'array_1d' to compute the exponential of each element, resulting in 'exp_array'.
- Apply np.log ufunc:
- Applied the np.log "ufunc" to the 'exp_array' to compute the natural logarithm of each element, resulting in log_array.
- Apply np.sqrt ufunc:
- Applied the np.sqrt "ufunc" to the 'log_array' to compute the square root of each element, resulting in 'sqrt_array'.
- Print Results:
- Print the original array and the resulting arrays after each transformation to verify the operations.
For more Practice: Solve these Related Problems:
- Write a Numpy program to apply np.exp, np.log, and np.sqrt sequentially on an array and then compare the final output with the original array.
- Write a Numpy program to transform an array using np.exp, then np.log, and finally np.sqrt, ensuring proper handling of edge cases.
- Write a Numpy program to chain np.exp, np.log, and np.sqrt on an array and use np.allclose to verify reversibility.
- Write a Numpy program to combine np.exp, np.log, and np.sqrt in a single pipeline using function composition on an input array.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.Previous: Create a custom ufunc in NumPy to compute x^2+2x+1.
Next: Compute sum of all elements in 1D array using np.add.reduce.
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