python - 求和的指数

标签 python math

我是一个非常新的 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

Equation

最佳答案

您的错误似乎不是 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/

相关文章:

python - 需要外部库时使用Maturin

python - 为什么我的 on_message 在我的命令后被调用?

algorithm - 生成求和矩阵游戏的算法

c++ - C/C++ 矩阵乘法顺序

javascript - 克隆维度列表并在克隆上进行数学运算

javascript - 在 JavaScript 中是否可以定义负数的平方根?

python - Inorder树走不工作

python - 无法使用 urlib2 通过代理发送 HTTPS 请求

python - 找不到 GEOS 库

.net - 在 .NET 中模拟 VBA 算术