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



我正在努力理解roots函数。。我正在寻找一个实现类似函数matlab r = roots(p)的java代码。

例如,如果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;
}
}

但是对于我提出的示例,此代码返回CCD_ 4。

我问你:matlab中的CCD_ 5函数和java中的roots函数是同一个函数吗?你有没有想法在matlab中实现一个类似roots的java函数?

函数应该相同,不同之处在于您在方法中传递的系数的顺序发生了变化。尝试:

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

或者使用apachemath:

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

最新更新