public static List<Double> solveByGauss(int n, List<List<Double>> matrix) { }完成高斯定理求线性代数方程solveByGause算法
时间: 2024-06-06 20:06:56 浏览: 74
public static List<Double> solveByGauss(int n, List<List<Double>> matrix) {
List<Double> solution = new ArrayList<Double>();
// Applying Gaussian Elimination
for (int i = 0; i < n; i++) {
// Finding the row with maximum element in the i-th column
int maxRow = i;
for (int j = i + 1; j < n; j++) {
if (Math.abs(matrix.get(j).get(i)) > Math.abs(matrix.get(maxRow).get(i))) {
maxRow = j;
}
}
// Swapping the rows if necessary
List<Double> temp = matrix.get(i);
matrix.set(i, matrix.get(maxRow));
matrix.set(maxRow, temp);
// Performing row operations to make all elements below the i-th element in the i-th column zero
for (int j = i + 1; j < n; j++) {
double factor = matrix.get(j).get(i) / matrix.get(i).get(i);
for (int k = i + 1; k <= n; k++) {
matrix.get(j).set(k, matrix.get(j).get(k) - factor * matrix.get(i).get(k));
}
matrix.get(j).set(i, 0.0);
}
}
// Back substitution to get the values of the variables
for (int i = n - 1; i >= 0; i--) {
double sum = 0.0;
for (int j = i + 1; j < n; j++) {
sum += matrix.get(i).get(j) * solution.get(j);
}
double value = (matrix.get(i).get(n) - sum) / matrix.get(i).get(i);
solution.add(0, value);
}
return solution;
}
阅读全文