2015-02-06 23 views
0

我想了解根函數..我正在尋找一個實現類似函數matlab r = roots(p)的Java代碼。我想在Java中實現matlab(多項式的根)的根函數

例如,如果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中的roots的Java函數嗎?

+0

'我不知道這意味着什麼實際功能roots'試圖代碼的東西,你不明白的是一個壞主意 – jhamon 2015-02-06 13:35:49

+0

如果你不不知道多項式的根源是什麼......這將很難理解特徵值分解......也許數學課程+維基百科會幫助你。 – 2015-02-06 13:37:34

+0

是的,我現在正在研究它 – user3347007 2015-02-06 13:38:59

回答

1

函數應該是一樣的,不同之處在於你所傳遞的係數的順序改變方法。嘗試:

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

或使用Apache數學:

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

謝謝,現在的解決方案是正確的 – user3347007 2015-02-06 13:58:13