commons-math 微分结果为 0

commons-math differentiation result is 0

我正在尝试使用 commons-math 库来完成一些数值微分任务。我使用我认为可行的 DerivativeStructures 构建了一个非常简单的函数;显然我错了。

public static void main(String[] args) {
    DerivativeStructure x0 = new DerivativeStructure(2, 2, 2.0);
    DerivativeStructure y0 = new DerivativeStructure(2, 2, 4.0);
    DerivativeStructure xi = x0.pow(2);
    DerivativeStructure yi = y0.pow(2);
    DerivativeStructure f = xi.add(yi);

    System.out.println(f.getValue());
    System.out.println(f.getPartialDerivative(1, 0)); // (?)
    System.out.println(f.getPartialDerivative(0, 1)); // (?)
}

我正在尝试获取多元函数 f(x)=x^2+y^2 在点 (2.0, 4.0) 的一阶和二阶偏导数。因此,我希望 df/dx 的 4.0 和 df/dy 的 8.0 作为一阶偏音。 2.0 用于二阶偏音。然而,我得到了正确的 f(x,y) 值,我什至没有从这个 javadoc 中得到丝毫的想法。我在这里看到了几个关于 Whosebug 的问题,其中有一些关于 commons-math 的不透明文档的评论,但不是关于多元函数的工作示例。单变量我可以解决,但不是这个...

如有任何提示,我们将不胜感激!

在您的代码中,您并未真正指定 2 个自变量 x0、y0,而仅指定了 1 个。对于 DerivativeStructure x0,y0 实际上被视为函数本身,具体取决于变量的隐式向量 p.对于每个自变量,您必须为 p 自变量向量提供不同的索引。您需要做的是:

DerivativeStructure x0 = new DerivativeStructure(2, 2, 0, 2.0);
DerivativeStructure y0 = new DerivativeStructure(2, 2, 1, 4.0);

其中第三个参数 0 和 1 表示 p 向量中的 2 个不同索引,因此是两个不同的自变量。如果在创建 DerivativeStructure 时省略此参数,则假定为 0,因此在您的代码中 x0、y0 不是独立的。

Further Reading