在一个NumPy数组中计算e^x的元素大小
在这篇文章中,我们将讨论如何为NumPy数组的每个元素计算e^x。
示例 :
输入 : [1, 3, 5, 7]
输出 : [2.7182817, 20.085537, 148.41316, 1096.6332]
解释 :
e^1 = 2.7182817
e^3 = 20.085537
e^5 = 148.41316
e^7 = 1096.6332
我们将使用numpy.exp()方法来计算指数值。
例子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)
输出 :
Original array:
[1 3 5 7]
Printing e ^ x, element-wise of the said:
[ 2.71828183 20.08553692 148.4131591 1096.63315843]
例子2 :我们也可以用math.exp()方法来寻找指数。虽然它不会一次取用整个NumPy数组,但我们必须一次传递一个元素。
# 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)
输出 :
Original array:
[1 3 5 7]
Printing e ^ x, element-wise of the said:
[2.718281828459045, 20.085536923187668, 148.4131591025766, 1096.6331584284585]