4

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

4

3 回答 3

8

您可以使用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;
    }
}
于 2012-12-10T17:11:06.717 回答
1

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

LaguerreSolver#solveAllComplex

于 2014-06-27T20:48:10.803 回答
0

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);
于 2016-03-29T12:59:56.230 回答