我是一个非常新的 python 用户。 我正在尝试计算求和的指数。该数组具有更多参数。
import math
a = [[1, 2, 3, 4],
[5, 6, 7, 8]]
def y(i):
p = 2
total = 0
for j in range (4):
total += math.exp(a[i][j] * (p**j))
return total
此方法的答案:7.89629603455e+13
答案与下面的手动计算有很大不同:
y = math.exp(1*(2**0) + 2*(2**1) + 3*(2**2) + 4*(2**3))
答案:1.9073465725e+21
最佳答案
您的错误似乎不是 python 错误,而是分解方程式时的数学错误。您可以进行以下两项更改之一:
解决方案 1:先求和,然后从总数中取 e^
import math
a = [[1, 2, 3, 4],
[5, 6, 7, 8]]
def y(i):
p = 2
total = 0
for j in range (4):
total += a[i][j] * (p**j)
return math.exp(total)
方案二:正确分解指数,将total +=改为total *=
import math
a = [[1, 2, 3, 4],
[5, 6, 7, 8]]
def y(i):
p = 2
total = 0
for j in range (4):
total *= math.exp(a[i][j] * (p**j))
return total
解决方案 1 更有效,因为它不会重复调用 math.exp()
关于python - 求和的指数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51107011/