In this article, we will discuss how to compute e^x for each element of a NumPy array.
Example :
Input : [1, 3, 5, 7] Output : [2.7182817, 20.085537, 148.41316, 1096.6332] Explanation : e^1 = 2.7182817 e^3 = 20.085537 e^5 = 148.41316 e^7 = 1096.6332
We will be using the numpy.exp() method to calculate the exponential value.
Example 1 :
# importing the module import numpy as np # creating an array arr = np.array([ 1 , 3 , 5 , 7 ]) print ( "Original array: " ) print (arr) # converting array elements into e ^ x res = np.exp(arr) print ( "\nPrinting e ^ x, element-wise of the said:" ) print (res) |
Output :
Original array: [1 3 5 7] Printing e ^ x, element-wise of the said: [ 2.71828183 20.08553692 148.4131591 1096.63315843]
Example 2 : We can also find the exponential using the math.exp() method. Although it won’t take the whole NumPy array at once, we have to pass one element at a time.
# importing the module import numpy as np import math # creating an array arr = np.array([ 1 , 3 , 5 , 7 ]) print ( "Original array: " ) print (arr) # converting array elements into e ^ x res = [] for element in arr: res.append(math.exp(element)) print ( "\nPrinting e ^ x, element-wise of the said:" ) print (res) |
Output :
Original array: [1 3 5 7] Printing e ^ x, element-wise of the said: [2.718281828459045, 20.085536923187668, 148.4131591025766, 1096.6331584284585]
<!–
–>
Please Login to comment…