JAVA解N元一次方程組(矩陣)
今天寫了一個解N元一次方程組的JAVA程式(矩陣),畢竟不是專業搞演算法的,用的是最基本的消元法, 模擬人的計算過程,記錄一下.
public class Matrix {
/**
* @param args
* 必須為N行N+1列
*/
public static void main(String[] args) {
int n = 4;
float[][] matrix = { { 6, 0, 7, 9, 20 }, { 0, 3, 0, 10, 50 },
{ 0, 4, 0, 11, 31 }, { 0, 8, 9, 0, 10 } };
// float[][] matrix = { { 6, 0, 7, 9, 20 ,99}, { 0, 3, 0, 10, 50 ,56},
// { 0, 4, 0, 11, 31 ,4}, { 0, 8, 9, 0, 10 ,78} ,{3,6,23,76,34,0}};
// 消元前
System.out.println("消元前");
printMatrix(n, matrix);
simple(n, matrix);
// 消元后
System.out.println("消元后");
printMatrix(n, matrix);
getResult(n, matrix);
}
private static void simple(int n, float[][] matrix) {
for (int k = 0; k < n; k++) {
if (matrix[k][k] == 0) {
changeRow(n, k, matrix);
}
for (int i = 0; i < n; i++) {
// 記錄對角線元素,作為除數
float temp = matrix[i][k];
for (int j = 0; j < n + 1; j++) {
// i<k時,i行已經計算完成
if (i < k)
break;
if (temp == 0)
continue;
if (temp != 1) {
matrix[i][j] /= temp;
}
if (i > k)
matrix[i][j] -= matrix[k][j];
}
}
}
}
private static float[] getResult(int n, float[][] matrix) {
float[] result = new float[n];
for (int i = n - 1; i >= 0; i--) {
float temp = matrix[i][n];
for (int j = n - 1; j >= 0; j--) {
if (i < j && matrix[i][j] != 0) {
temp = temp - result[j] * matrix[i][j];
}
}
temp /= matrix[i][i];
result[i] = temp;
}
for (int k = 0; k < result.length; k++) {
System.out.println("X" + (k + 1) + " = " + result[k]);
}
return result;
}
// 對角線上元素為0時候和下行交換
private static void changeRow(int n, int k, float[][] matrix) {
float[] temp = new float[n + 1];
// if()
for (int i = k; i < n; i++) {
// 已到最後一列,不能繼續交換
if (i + 1 == n && matrix[k][k] == 0) {
System.out.println("無解或有不唯一解!");
System.exit(1);
}
for (int j = 0; j < n + 1; j++) {
temp[j] = matrix[k][j];
matrix[k][j] = matrix[i + 1][j];
matrix[i + 1][j] = temp[j];
}
if (matrix[k][k] != 0)
return;
}
}
private static void printMatrix(int n, float[][] matrix) {
// 列印矩陣
System.out.println("============================================================================");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n + 1; j++) {
if (j == n)
System.out.print(" = " + matrix[i][j]);
else
System.out.print("(" + matrix[i][j] + ") * X" + (j + 1)+ " + ");
}
System.out.println();
}
System.out.println("============================================================================");
}
}