-
Notifications
You must be signed in to change notification settings - Fork 3
/
MatrixEquation.java
executable file
·53 lines (49 loc) · 1.68 KB
/
MatrixEquation.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package cn.qiyubing;
/**
* 求解矩阵方程
*
* @author qiyubing
* @since 2019-03-26
*/
public class MatrixEquation {
/**
* 初始增广矩阵
*/
private static double[][] matrix1 = {
{1, 2, 3, 14},
{0, 1, 2, 8},
{2, 4, 1, 13}
};
public static void main(String[] args) {
// 高斯消元
for (int mainRow = 0; mainRow < matrix1.length - 1; mainRow++) {
for (int nowRow = mainRow + 1; nowRow < matrix1.length; nowRow++) {
double ratio = (matrix1[nowRow][mainRow] / matrix1[mainRow][mainRow]);
for (int nowCol = mainRow; nowCol < matrix1[nowRow].length; nowCol++) {
matrix1[nowRow][nowCol] -= ratio * matrix1[mainRow][nowCol];
}
}
}
System.out.println("高斯消元结果为:");
for (double[] nowRow : matrix1) {
for (double nowElem : nowRow) {
System.out.print(nowElem + " ");
}
System.out.println();
}
// 回代解x1 x2 x3...
double[] xArray = new double[matrix1.length];
for (int nowRow = matrix1.length - 1; nowRow >= 0; nowRow--) {
// ax = right
double right = matrix1[nowRow][matrix1[nowRow].length - 1];
for (int j = nowRow + 1; j < matrix1[nowRow].length - 1; j++) {
right -= matrix1[nowRow][j] * xArray[j];
}
xArray[nowRow] = right / matrix1[nowRow][nowRow];
}
System.out.println("回代得:");
for (int i = 0; i < xArray.length; i++) {
System.out.println("x" + (i + 1) + " = " + xArray[i]);
}
}
}