代码之家  ›  专栏  ›  技术社区  ›  user3347007

我想用java实现matlab的根函数(多项式的根)

  •  0
  • user3347007  · 技术社区  · 10 年前

    我正在尝试理解根函数。。我正在寻找一个实现类似功能matlab的java代码 r = roots(p) .

    例如,如果 p = [1 -6 -72 -27] ,matlab返回 r = 12.1229 -5.7345 -0.3884

    我承认我不知道它在实际函数根中的含义,但我需要在我的java应用程序中的算法中使用它。

    我尝试在Efficent 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;
    }
    }
    

    但此代码返回 [ -2.5747724050560374, -0.17438281737671643, 0.08248855576608725 ] 我提议的例子。

    我问你: 这个 roots 函数matlab和java中的roots函数是相同的函数吗? 您有没有想法实现类似于 在matlab中?

    1 回复  |  直到 10 年前
        1
  •  1
  •   jjlema    10 年前

    函数应该是相同的,不同的是传递给方法的系数的顺序发生了变化。尝试:

    final double[] coeff = new double[] { -27, -72, -6, 1 };
    

    或使用apache math:

    final LaguerreSolver solver = new LaguerreSolver();
    final Complex[] result = solver.solveAllComplex(coeff, 0);