简体   繁体   English

我想在Java中实现Matlab的根函数(多项式的根)

[英]I want to implement the roots function of matlab (root of polynomial) in java

I'm trying to understand the roots function.. I was looking for a java code that implemented the similar function matlab r = roots(p) . 我正在尝试了解roots函数。.我正在寻找实现类似功能matlab r = roots(p)的Java代码。

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

I admit that I have no idea what it means in practical function roots, but I need to use it within an algorithm in my java application. 我承认我不知道在实际函数根中这意味着什么,但是我需要在Java应用程序的算法中使用它。

I tried using this code with Efficent-java-matrix-library: 我尝试在Efficent-java-matrix-library中使用此代码:

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;
}
}

but this code returns [ -2.5747724050560374, -0.17438281737671643, 0.08248855576608725 ] for the example that I propose. 但是对于我建议的示例,此代码返回[ -2.5747724050560374, -0.17438281737671643, 0.08248855576608725 ]

I ask you: the roots function matlab and the roots function in java is the same function? 请问:在roots功能的MATLAB和根系功能在java中是相同的功能? Do you have any idea to implement a java function similar the roots in matlab? 你有什么想法来实现类似的Java函数roots在MATLAB?

The funcion should be the same, the diference is that the order of the coefs you pass de method change. 函数应该相同,不同之处在于您通过方法更改的系数的顺序。 Try: 尝试:

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

or using apache math: 或使用apache数学:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM