NumPy: Compute e^x, element-wise of a given array
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:
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