java实现列主元高斯消去法(附完整源码)
时间: 2023-11-09 10:05:33 浏览: 35
附上Java实现列主元高斯消去法的完整源码:
```java
public class GaussianElimination {
public static void main(String[] args) {
// 矩阵A
double[][] A = {{2, 1, -1}, {-3, -1, 2}, {-2, 1, 2}};
// 向量b
double[] b = {8, -11, -3};
// 解方程Ax=b
double[] x = solve(A, b);
// 输出解向量x
for (int i = 0; i < x.length; i++) {
System.out.printf("x%d = %.2f\n", i + 1, x[i]);
}
}
/**
* 列主元高斯消去法求解线性方程组Ax=b
*
* @param A 系数矩阵
* @param b 常数向量
* @return 解向量
*/
public static double[] solve(double[][] A, double[] b) {
int n = A.length;
double[] x = new double[n];
// 高斯消元
for (int k = 0; k < n - 1; k++) {
// 选主元
int maxIndex = k;
double max = Math.abs(A[k][k]);
for (int i = k + 1; i < n; i++) {
if (Math.abs(A[i][k]) > max) {
max = Math.abs(A[i][k]);
maxIndex = i;
}
}
// 交换行
if (maxIndex != k) {
double[] tmp = A[k];
A[k] = A[maxIndex];
A[maxIndex] = tmp;
double btmp = b[k];
b[k] = b[maxIndex];
b[maxIndex] = btmp;
}
// 消元
for (int i = k + 1; i < n; i++) {
double factor = A[i][k] / A[k][k];
for (int j = k + 1; j < n; j++) {
A[i][j] -= factor * A[k][j];
}
b[i] -= factor * b[k];
}
}
// 回带求解
for (int i = n - 1; i >= 0; i--) {
double sum = 0;
for (int j = i + 1; j < n; j++) {
sum += A[i][j] * x[j];
}
x[i] = (b[i] - sum) / A[i][i];
}
return x;
}
}
```
该程序实现了列主元高斯消去法求解线性方程组Ax=b,其中A为系数矩阵,b为常数向量,x为解向量。程序中的solve方法即为求解方法,通过高斯消元和回带求解来求解线性方程组。