NumPy: Compute e^x, element-wise of a given array
NumPy Mathematics: Exercise-31 with Solution
Write a NumPy program to compute ex, element-wise of a given array.
Sample Solution:
Python Code:
# Importing the NumPy library
import numpy as np
# Creating an array of float32 type
x = np.array([1., 2., 3., 4.], np.float32)
# Displaying the original array
print("Original array: ")
print(x)
# Calculating exponential (e^x) for each element of the array x
print("\ne^x, element-wise of the said:")
r = np.exp(x)
print(r)
Sample Output:
Original array: [1. 2. 3. 4.] e^x, element-wise of the said: [ 2.7182817 7.389056 20.085537 54.59815 ]
Explanation:
In the above code –
x = np.array([1., 2., 3., 4.], np.float32): This code creates a one-dimensional NumPy array x of data type float32 is created with the values [1., 2., 3., 4.].
r = np.exp(x) – Here np.exp() function is applied to x, which returns a new array r containing the exponential value of each element in x. The exponential function raises the constant e to the power of each element in x, so the resulting array r will have the values [2.718282 , 7.389056 , 20.085537, 54.598152].
Python-Numpy Code Editor:
Next: Write a NumPy program to calculate exp(x) - 1 for all elements in a given array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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/python-numpy-math-exercise-31.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics