1 package MyMath; 2 3 import java.util.Scanner; 4 5 public class Gauss { 6 7 /** 8 * @列主元高斯消去法 9 */ 10 static double x[]; 11 static double a[][]; 12 static double b[]; 13 static double m; 14 static int n; 15 //选主元 16 public static void SelectAndChangeLine(int k){ 17 int maxline=k; 18 for(int i=k+1;i<n;i++){ 19 if(Math.abs(a[i][k])>a[maxline][k]){ 20 maxline=i; 21 } 22 } 23 if(maxline!=k){ 24 for(int j=0;j<n+1;j++){ 25 b[j]=a[k][j]; 26 a[k][j]=a[maxline][j]; 27 a[maxline][j]=b[j]; 28 } 29 } 30 } 31 //消元计算 32 public static void Elimination(int k){ 33 for(int i=k+1;i<n;i++){ 34 m=a[i][k]/a[k][k]; 35 a[i][k]=0; 36 for(int j=k+1;j<n+1;j++){ 37 a[i][j]=a[i][j]-m*a[k][j]; 38 //System.out.println("tt="+m*a[k][j]); 39 } 40 } 41 } 42 //回代计算 43 public static void BacksSubstitution(){ 44 for(int i=n-1;i>=0;i--){ 45 for(int j=n-1;j>i;j--){ 46 a[i][n]=a[i][n]-x[j]*a[i][j]; 47 } 48 System.out.println(a[i][n]); 49 x[i]=a[i][n]/a[i][i]; 50 } 51 } 52 //打印行 53 public static void PrintLine(double[] args){ 54 for(int j=0;j<args.length;j++){ 55 System.out.print(args[j]+" "); 56 } 57 } 58 //打印矩阵 59 public static void PrintMatrix(double[][] args){ 60 for(int i=0;i<args.length;i++){ 61 for(int j=0;j<args[i].length;j++){ 62 System.out.print(args[i][j]+" "); 63 } 64 System.out.println(); 65 } 66 } 67 public static void main(String[] args) { 68 Scanner as=new Scanner(System.in); 69 System.out.println("输入方程组的元数:"); 70 n=as.nextInt(); 71 System.out.println("输入方程组的系数矩阵a:"); 72 a=new double[n][n+1]; 73 b=new double[n+1]; 74 x=new double[n]; 75 for(int i=0;i<n;i++){ 76 for(int j=0;j<n+1;j++){ 77 a[i][j]=as.nextDouble(); 78 } 79 } 80 as.close(); 81 for(int i=0;i<n-1;i++){ 82 SelectAndChangeLine(i); 83 System.out.println("第"+(i+1)+"次换主元"); 84 PrintMatrix(a); 85 Elimination(i); 86 System.out.println("第"+(i+1)+"次消元"); 87 PrintMatrix(a); 88 } 89 BacksSubstitution(); 90 PrintLine(x); 91 } 92 }
代入求解:
验证正确: