Apply np.exp, np.log, and np.sqrt ufuncs to transform a NumPy array
NumPy: Universal Functions Exercise-8 with Solution
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.
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