JAVA用List实现高斯消元法,并指出什么时候方程组有无限解和无解
时间: 2024-05-05 22:15:09 浏览: 16
高斯消元法可以用Java中的List实现。以下是实现代码:
```
import java.util.ArrayList;
import java.util.List;
public class GaussElimination {
// 高斯消元法
public static List<Double> gaussElimination(List<List<Double>> matrix) {
int n = matrix.size();
for (int i = 0; i < n; i++) {
// 找到主元素
int pivotRow = findPivotRow(matrix, i);
if (matrix.get(pivotRow).get(i) == 0) {
// 主元素为0,方程无解
return null;
}
// 交换当前行和主元素所在行
if (pivotRow != i) {
swapRows(matrix, i, pivotRow);
}
// 将主元素归一
double pivot = matrix.get(i).get(i);
for (int j = i; j < n + 1; j++) {
matrix.get(i).set(j, matrix.get(i).get(j) / pivot);
}
// 消元
for (int j = i + 1; j < n; j++) {
double factor = matrix.get(j).get(i);
for (int k = i; k < n + 1; k++) {
matrix.get(j).set(k, matrix.get(j).get(k) - factor * matrix.get(i).get(k));
}
}
}
// 回代求解
List<Double> solution = new ArrayList<Double>();
for (int i = n - 1; i >= 0; i--) {
double sum = 0;
for (int j = i + 1; j < n; j++) {
sum += matrix.get(i).get(j) * solution.get(n - j - 1);
}
solution.add(matrix.get(i).get(n) - sum);
}
// 返回解向量
return solution;
}
// 找到主元素所在行
private static int findPivotRow(List<List<Double>> matrix, int col) {
int n = matrix.size();
int pivotRow = col;
double max = Math.abs(matrix.get(col).get(col));
for (int i = col + 1; i < n; i++) {
double value = Math.abs(matrix.get(i).get(col));
if (value > max) {
max = value;
pivotRow = i;
}
}
return pivotRow;
}
// 交换两行
private static void swapRows(List<List<Double>> matrix, int i, int j) {
List<Double> temp = matrix.get(i);
matrix.set(i, matrix.get(j));
matrix.set(j, temp);
}
// 测试
public static void main(String[] args) {
List<List<Double>> matrix = new ArrayList<List<Double>>();
matrix.add(new ArrayList<Double>() {{add(2.0); add(1.0); add(-1.0); add(8.0);}});
matrix.add(new ArrayList<Double>() {{add(-3.0); add(-1.0); add(2.0); add(-11.0);}});
matrix.add(new ArrayList<Double>() {{add(-2.0); add(1.0); add(2.0); add(-3.0);}});
List<Double> solution = gaussElimination(matrix);
if (solution == null) {
System.out.println("The system of equations has no solution.");
} else {
System.out.print("The solution is (");
for (int i = solution.size() - 1; i >= 0; i--) {
System.out.print(solution.get(i));
if (i != 0) {
System.out.print(", ");
}
}
System.out.println(").");
}
}
}
```
当方程组有无限解时,矩阵的秩小于变量的个数,即方程组中的自由变量的个数大于0。在高斯消元法中,当某一行全为0时,会出现主元素为0的情况,这时方程组无解。