w3resource

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:

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.



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://w3resource.com/python-exercises/numpy/apply-np-dot-exp-np-dot-log-and-np-dot-sqrt-ufuncs-to-transform-a-numpy-array.php