Java – 使用Apache Commons Mathematic Library计算派生

我在使用apache commons数学库时遇到问题。
我只想创建像f(x)= 4x ^ 2 + 2x这样的函数,我想计算这个函数的导数
– > f’(x)= 8x + 2

我阅读了有关差异化的文章( http://commons.apache.org/proper/commons-math/userguide/analysis.html ,第4.7节)。
有一个我不明白的例子:

int params = 1; int order = 3; double xRealValue = 2.5; DerivativeStructure x = new DerivativeStructure(params, order, 0, xRealValue); DerivativeStructure y = f(x); //COMPILE ERROR System.out.println("y = " + y.getValue(); System.out.println("y' = " + y.getPartialDerivative(1); System.out.println("y'' = " + y.getPartialDerivative(2); System.out.println("y''' = " + y.getPartialDerivative(3); 

在第5行中,当然会发生编译错误。 函数f(x)被调用但未定义。 我错了什么?
有没有人使用apache commons数学库进行区分/推导的经验,还是有人知道可以帮助我的另一个库/框架吗?

谢谢

在该示例下面的段落中,作者描述了创建DerivativeStructure的方法。 这不是魔术。 在你引用的例子中,有人应该写函数f 。 嗯,那不是很清楚。

用户可以通过多种方式创建UnivariateDifferentiableFunction接口的实现。 第一种方法是直接使用DerivativeStructure中的适当方法直接编写它来计算加法,减法,正弦,余弦……这通常非常简单,并且不需要记住区分规则:用户代码仅代表function本身,差异将在引擎盖下自动计算。 第二种方法是编写经典的UnivariateFunction并将其传递给UnivariateFunctionDifferentiator接口的现有实现,以检索相同函数的差异化版本。 第一种方法更适合用户已经控制所有底层代码的小函数。 第二种方法更适合于使用DerivativeStructure API编写繁琐的大型函数,或者用户无法控制完整底层代码的函数(例如调用外部库的函数)。

使用第一个想法。

 // Function of 1 variable, keep track of 3 derivatives with respect to that variable, // use 2.5 as the current value. Basically, the identity function. DerivativeStructure x = new DerivativeStructure(1, 3, 0, 2.5); // Basically, x --> x^2. DerivativeStructure x2 = x.pow(2); //Linear combination: y = 4x^2 + 2x DerivativeStructure y = new DerivativeStructure(4.0, x2, 2.0, x); System.out.println("y = " + y.getValue()); System.out.println("y' = " + y.getPartialDerivative(1)); System.out.println("y'' = " + y.getPartialDerivative(2)); System.out.println("y''' = " + y.getPartialDerivative(3)); 

来自Apache邮件列表的以下线程似乎说明了如何定义单变量差异函数的导数的两种可能方式。 我正在添加一个新答案,因为我无法评论前一个(声誉不足)。

函数的使用样本规范是f(x)= x ^ 2。

(1)使用DerivativeStructure:

 public DerivativeStructure value(DerivativeStructure t) { return t.multiply(t); } 

(2)通过编写经典的单变量函数:

 public UnivariateRealFunction derivative() { return new UnivariateRealFunction() { public double value(double x) { // example derivative return 2.*x; } } } 

如果我理解得很好,第一种情况的优点是衍生物不需要手动获得,如第二种情况。 如果衍生物是已知的,那么因此没有定义衍生物结构的优势,对吧? 我想到的应用是Newton-Raphson求解器,通常需要知道函数值及其导数。

完整的示例在上述网站上提供(作者是Thomas Neidhart和Franz Simons)。 欢迎任何进一步的评论!