java實現解一元n次多項式(二)
阿新 • • 發佈:2019-01-06
package commonAlgorithm; public class PolynomialSoluter { private double[][] matrix; private double[] result; private int order; // public PolynomialSoluter() { // // } // 檢查輸入項長度 private boolean init(double[][] matrixA, double[] arrayB) { order = arrayB.length; if (matrixA.length != order) return false; for (double[] arrayA : matrixA) if (arrayA.length != order) return false; matrix = matrixA; result = arrayB; return true; } public double[] getResult(double[][] matrixA, double[] arrayB) { if (!init(matrixA, arrayB)) return null; // 高斯消元-正向 for (int i = 0; i < order; i++) { // 如果當前行對角線項為0則與後面的同列項非0的行交換 if (!swithIfZero(i)) return null; // 消元 for (int j = i + 1; j < order; j++) { if (matrix[j][i] == 0) continue; double factor = matrix[j][i] / matrix[i][i]; for (int l = i; l < order; l++) matrix[j][l] -= matrix[i][l] * factor; result[j] -= result[i] * factor; } } // 高斯消元-反向-去掉了冗餘計算 for (int i = order - 1; i >= 0; i--) { result[i] /= matrix[i][i]; for (int j = i - 1; j > -1; j--) result[j] -= result[i] * matrix[j][i]; } return result.clone(); } private boolean swithIfZero(int i) { if (matrix[i][i] == 0) { int j = i + 1; // 找到對應位置非0的列 while (j < order && matrix[j][i] == 0) j++; // 若對應位置全為0則無解 if (j == order) return false; else switchRows(i, j); } return true; } // 調換行 private void switchRows(int i, int j) { double[] tmp1 = matrix[i]; matrix[i] = matrix[j]; matrix[j] = tmp1; double tmp2 = result[i]; result[i] = result[j]; result[j] = tmp2; } public static void main(String[] args) { double[][] matrixA = { { 0, 0, 1 }, { 0, 1, 0 }, { 1, 0, 0 } }; double[] arrayB = { 1, 3, 2 }; PolynomialSoluter ps = new PolynomialSoluter(); for (double result : ps.getResult(matrixA, arrayB)) System.out.println(result); } }
後來發現這個類要被呼叫太多次,但之前沒考慮效率問題。所以重新寫了這個類,之前的程式碼參考我之前的文章http://blog.csdn.net/strangerzz/article/details/45244249
主要就是去掉了數組裡面賦值等操作,也不再生成增廣矩陣了。雖然看起來比以前要難理解一下,但是效率應該會有所提升