利用高斯列主元的方法解n元一次方程组,对方程组的要求是对应的系数矩阵是非奇异的。
课本中的题目是:
| -3 2 6 | |x1| |4|
| 10 -7 0 | |x2| = |7|
| 5 -1 5 | |x3| |6|
其中,采用的语言是 java ,代码如下,
import java.text.NumberFormat;
import java.util.Scanner;
/**
* Created by 一粟 on 2017/11/23.
*/
public class Gaussian {
private int n;//含有x的个数
private double a[][];//增广矩阵
public Gaussian(int n, double[][] a) {
this.n = n;
this.a = a;
}
public void elimination(){ //消元
for(int k = 0;k<n-1;k++){
select(k);
for(int i = k+1; i<n;i++){
double C = a[i][k]*1.0/a[k][k];
for(int j = k;j<=n;j++){
a[i][j] = a[i][j]-C*a[k][j];
}
}
}
}
public void select(int k){ //选取主元并交换
int max = k;
double maxNum = a[k][k];
for(int i = k+1;i<n;i++){
if(a[i][k]>maxNum){
max = i;
maxNum = a[i][k];
}
}
if(max != k){
double temp;
for(int i = k;i<=n;i++){
temp = a[k][i];
a[k][i] = a[max][i];
a[max][i] = temp;
}
}
}
public void solve(){ //回代求解,并将解放在了最后一列中
for(int i = n-1;i>=0;i--){
double sum = 0.0;
for(int j= i+1;j<n;j++){
sum += a[i][j] * a[j][n];
}
a[i][n] = (a[i][n] - sum)/a[i][i];
}
}
public void print(){ //打印方程的解
for(int i = 0;i<n;i++){
NumberFormat ddf1=NumberFormat.getNumberInstance() ;
ddf1.setMaximumFractionDigits(2);
String s= ddf1.format(a[i][n]) ;
System.out.println(s);
}
}
public static void main(String [] args){
Scanner scanner = new Scanner(System.in);
int n;
System.out.println("请输入X的个数");
n = scanner.nextInt();
double [][]shuzu = new double[n][n+1];
System.out.println("请输入系数矩阵");
for(int i=0;i<n;i++){
shuzu[i] = new double[n+1];
for(int j = 0;j<n+1;j++){
shuzu[i][j] = scanner.nextInt();
}
}
Gaussian gaussian = new Gaussian(n,shuzu);
gaussian.elimination();
gaussian.solve();
gaussian.print();
}
}