JAVA用List实现高斯消元法
时间: 2024-05-30 12:13:57 浏览: 10
高斯消元法是一种线性方程组求解的算法,可以用Java中的List实现。具体实现过程如下:
1. 定义一个二维List,表示线性方程组的系数矩阵和常数矩阵,例如:
List<List<Double>> matrix = new ArrayList<>();
matrix.add(Arrays.asList(2.0, 1.0, -1.0, 8.0));
matrix.add(Arrays.asList(-3.0, -1.0, 2.0, -11.0));
matrix.add(Arrays.asList(-2.0, 1.0, 2.0, -3.0));
2. 实现高斯消元的主要步骤:
- 将系数矩阵化为上三角矩阵:遍历每一行,将该行的第一个元素除以该行的第一个非零元素,然后将该行加到下面的行中,使得下面的行的第一个非零元素为0。
- 回代求解:从最后一行开始,依次代入已知的变量值,求解未知变量。
具体实现代码如下:
public static List<Double> gauss(List<List<Double>> matrix) {
int n = matrix.size();
for (int i = 0; i < n; i++) {
// 将该行的第一个元素除以该行的第一个非零元素
double a = matrix.get(i).get(i);
for (int j = i + 1; j <= n; j++) {
double b = matrix.get(j).get(i);
for (int k = i; k <= n; k++) {
matrix.get(j).set(k, matrix.get(j).get(k) - matrix.get(i).get(k) * b / a);
}
}
}
// 回代求解
List<Double> result = new ArrayList<>();
for (int i = n - 1; i >= 0; i--) {
double x = matrix.get(i).get(n);
for (int j = i + 1; j < n; j++) {
x -= matrix.get(i).get(j) * result.get(n - j - 1);
}
result.add(x / matrix.get(i).get(i));
}
// 反转结果
Collections.reverse(result);
return result;
}
3. 调用高斯消元方法,并输出结果:
List<List<Double>> matrix = new ArrayList<>();
matrix.add(Arrays.asList(2.0, 1.0, -1.0, 8.0));
matrix.add(Arrays.asList(-3.0, -1.0, 2.0, -11.0));
matrix.add(Arrays.asList(-2.0, 1.0, 2.0, -3.0));
List<Double> result = gauss(matrix);
System.out.println(result); // [2.0, 3.0, -1.0]
以上就是用Java中的List实现高斯消元法的方法。