w3resource

Advanced NumPy Exercises - Calculate the exponential of each element in a 5x5 array

NumPy: Advanced Exercise-15 with Solution

Write a NumPy program to create a 5x5 array with random values and calculate the exponential of each element.

To perform element-wise exponential calculations on a 5x5 array in NumPy, you can generate the array using numpy.random.rand. Then, use the numpy.exp function to compute the exponential of each element in the array. This operation applies the exponential function to each value, transforming the original array into one where each element is the exponentiated value of the corresponding element in the original array.

Sample Solution:

Python Code:

import numpy as np
nums = np.random.rand(5, 5)
print("Original array elements:")
print(nums)
exp_arr = np.exp(nums)
print("\nExponential of each element of the said array:")
print(exp_arr)

Output:

Original array elements:
[[0.36959613 0.61718307 0.51482027 0.54201977 0.47885604]
 [0.96237425 0.86653443 0.99702202 0.20504792 0.10261349]
 [0.47008673 0.46721343 0.94903901 0.74238819 0.23236025]
 [0.06117178 0.13717994 0.18294167 0.25826883 0.87410313]
 [0.41298433 0.57386986 0.34611886 0.47406998 0.32508609]]

Exponential of each element of the said array:
[[1.44715003 1.85369893 1.67333772 1.7194763  1.61422673]
 [2.61790465 2.37865316 2.71019888 1.22758388 1.10806305]
 [1.60013297 1.5955419  2.58322601 2.10094699 1.26157413]
 [1.06308151 1.14703452 1.20074437 1.29468682 2.39672477]
 [1.51132134 1.77512325 1.41357063 1.6065194  1.3841498 ]]

Explanation:

In the above exercise -

nums = np.random.rand(5, 5): This line creates a NumPy array of shape (5, 5) with random values generated from a uniform distribution between 0 and 1.

exp_arr = np.exp(nums): This line calculates the exponential function for each element in nums. The exponential function exp(x) is defined as e^x, where e is Euler's number (approximately 2.71828). In this case, the function is applied element-wise to the entire array, resulting in a new array with the same shape as nums, where each element is the exponential function of the corresponding element in nums.

Python-Numpy Code Editor:

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

Previous: Replace the minimum value with 0 in a 5x5 array with random values.
Next: Compute Eigenvalues and Eigenvectors of a 4x4 Random array using NumPy.

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://198.211.115.131/python-exercises/numpy/advanced-numpy-exercise-15.php