Java代码实现:
import java.util.Arrays;
// 列主元消去法
public class ColumnPivot {
//调用启动
public static void main(String[] args) {
//输入增广矩阵
int[][] matrix = {{1, 1, 0, 3, 4},
{2, 1, -1, 1, 1},
{3, -1, -1, 3, -3},
{-1, 2, 3, -1, 4}};
//创建对象
ColumnPivot columnPivot = new ColumnPivot(matrix);
double[] root= columnPivot.getRoot();
// 输出结果
if (root.length == 0) {
System.err.println("方程组无解!");
} else {
for (int i = 0; i < root.length; ++i) {
System.out.print("X" + (i + 1) + " =");
System.out.printf("%6.2f\n", root[i]);
}
}
}
private double[][] matrix;// 增广矩阵
private int n;// 系数矩阵的阶数
// 参数为增广矩阵
public ColumnPivot(int[][] matrix) {
n = matrix.length;// 系数矩阵的阶
this.matrix = new double[n][n + 1];
for (int i = 0; i < n; ++i) {
for (int j = 0; j <= n; ++j) {
this.matrix[i][j] = matrix[i][j];// 数据类型转换
}
}
}
// 参数为增广矩阵
public ColumnPivot(double[][] matrix) {
n = matrix.length;// 系数矩阵的阶
this.matrix = new double[n][n + 1];
for (int i = 0; i < n; ++i) {// 备份
this.matrix[i] = Arrays.copyOf(matrix[i], n + 1);
}
}
// 获取方程组的根
public double[] getRoot() {
for (int k = 0; k < n - 1; ++k) {
int i = columnPivoting(k);// 列选主元
if (matrix[i][k] == 0) {
return new double[0];// 无解
}
if (i != k) {
lineSwitch(k, i);// 行交换
}
elimination(k);// 消元
}
return backSubstitution();// 回代求根并返回根
}
// 选第k列的主元
private int columnPivoting(int k) {
double maxVal = Math.abs(matrix[k][k]);
int maxRow = k;
for (int i = k + 1; i < n; ++i) {// 查找值最大的行下标
double val = Math.abs(matrix[i][k]);
if (val > maxVal) {
maxVal = val;
maxRow = i;
}
}
return maxRow;// 返回行下标
}
// a[l1][j]和a[l2][j]交换,j=l1,l1+1,...,n
private void lineSwitch(int l1, int l2) {// l1 < l2
for (int j = l1; j <= n; ++j) {
double temp = matrix[l1][j];
matrix[l1][j] = matrix[l2][j];
matrix[l2][j] = temp;
}
}
// 消元
private void elimination(int k) {
for (int i = k + 1; i < n; ++i) {
matrix[i][k] /= matrix[k][k];// 倍数
for (int j = k + 1; j <= n; ++j) {
matrix[i][j] -= matrix[i][k] * matrix[k][j];
}
}
}
// 回代求根
private double[] backSubstitution() {
double[] root = new double[n];
for (int i = n - 1; i >= 0; --i) {
for (int j = i + 1; j < n; ++j) {
matrix[i][n] -= matrix[i][j] * root[j];
}
root[i] = matrix[i][n] / matrix[i][i];
}
return root;
}
}
输出结果: