【问题标题】:Finding roots of polynomial in Java在Java中找到多项式的根
【发布时间】:2012-12-10 17:06:39
【问题描述】:

我需要找到Legendre polynomial 的(近似的、数值的)解。我尝试了几个 Java 库,但都没有我想要的(最接近的是 commons-math,它甚至有在 Laguerre solver 中查找解决方案的代码,但它没有公开该方法)。有现成的解决方案还是我需要自己实施?

【问题讨论】:

  • @PradeepSimha:JScience、common-math、JAP 以及可能在 stackoverflow/google 上找到的其他一些(我在发布前花了大约 4 个小时搜索)。
  • 所以,他们都缺少你需要的东西。
  • @mtk:是的。 JScience 和 JAP 根本没有求根,common-math 有求根的方法,而 commons-math 只找到一个根(可能可以选择适当的初始条件来找到所有根,但应该不需要用多项式这样的简单函数来做到这一点)。至少我找不到。

标签: java math polynomial-math


【解决方案1】:

您可以使用EJML高效的 Java 矩阵库)。

请在下面找到相同的示例。

public class PolynomialRootFinder {

    /**
     * <p>
     * Given a set of polynomial coefficients, compute the roots of the polynomial.  Depending on
     * the polynomial being considered the roots may contain complex number.  When complex numbers are
     * present they will come in pairs of complex conjugates.
     * </p>
     *
     * @param coefficients Coefficients of the polynomial.
     * @return The roots of the polynomial
     */
    public static Complex64F[] findRoots(double... coefficients) {
        int N = coefficients.length-1;

        // Construct the companion matrix
        DenseMatrix64F c = new DenseMatrix64F(N,N);

        double a = coefficients[N];
        for( int i = 0; i < N; i++ ) {
            c.set(i,N-1,-coefficients[i]/a);
        }
        for( int i = 1; i < N; i++ ) {
            c.set(i,i-1,1);
        }

        // Use generalized eigenvalue decomposition to find the roots
        EigenDecomposition<DenseMatrix64F> evd =  DecompositionFactory.eigGeneral(N, false);

        evd.decompose(c);

        Complex64F[] roots = new Complex64F[N];

        for( int i = 0; i < N; i++ ) {
            roots[i] = evd.getEigenvalue(i);
        }

        return roots;
    }
}

【讨论】:

  • 如果您不知道上述内容的出处,请查看this paper,特别是第 2 页“伴随矩阵:作为特征值/特征向量问题的单变量多项式求根”。
  • eigGeneral 方法现在更改为 eig
  • @zygimantus 感谢您的信息和知识分享:)
  • 链接仍然有效,但也许更新它?
【解决方案2】:

自 3.1 版起,Commons-Math 支持查找多项式函数的所有复数根。

LaguerreSolver#solveAllComplex

【讨论】:

  • 链接已损坏:“未找到。在此服务器上未找到请求的 URL。”
【解决方案3】:

Commons-Math 有一个合理的多项式 API:

//  -4 + 3 x + x^2
PolynomialFunction polynomial = new PolynomialFunction(new double[]{ -4, 3, 1});
LaguerreSolver laguerreSolver = new LaguerreSolver();
double root = laguerreSolver.solve(100, polynomial, -100, 100);
System.out.println("root = " + root);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 2022-10-06
    • 2013-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多