This is not the matrix solution to linear equations in discrete mathematics
前置知识:初等行(列)变换
Multiply a row by a non-zero number (multiplying both sides of the equation by a non-zero number at the same time does not change the solution of the equation)
Swap certain two lines (exchange the positions of the two equations)
Add several times of a line to another line (add several times of one equation to another equation)
Finally, substituting the ladder matrix from bottom to top to the first layer to get the solution of the equation
算法步骤
Enumerate each column c,
Find the row with the largest absolute value of the current column
Use elementary line transformation (2) to change this line to the top (the ladder-shaped line is not determined, not the first line)
Use elementary row transformation (1) to change the first number of the row to 1
(All the other numbers change in turn) Use elementary row transformation (3) to change the value of the current column of all the following rows to 0
③. Learning points
④. Code implementation
import java.util.Scanner;publicclassMain{
staticint N=110;staticdouble[][] a=newdouble[N][N+1];staticint n=0;staticdouble eps=0.000001;publicstaticvoidmain(String[] args){
Scanner sc =newScanner(System.in);
n=sc.nextInt();for(int i =0; i <n; i++){
//行 nfor(int j =0; j <=n; j++){
//列n+1
a[i][j]=sc.nextDouble();}}int t=guass(a);if(t==0){
//唯一解for(int i =0; i <n; i++){
System.out.println(String.format("%.2f", a[i][n]));}}elseif(t==1){
//五穷解
System.out.println("Infinite group solutions");}else{
//无解
System.out.println("No solution");}}staticintguass(double[][] a){
int row,col;//遍历每一列for(row=0,col=0;col<n;col++){
int t=row;//找到该列中的绝对值的最大值的行号//每一个固定一行 不能进行修改for(int i =row; i <n; i++){
//Math.abs()可以用于浮点数取绝对值if(Math.abs(a[i][col])>Math.abs(a[t][col])){
t=i;}}//如果最大值为0,继续下一列寻找非0的最大值if(Math.abs(a[t][col])<eps)continue;//交换最大值的当前和和从上往下未固定的行for(int i=col;i<=n;i++){
//t是当前最大值的行 row是开始固定的那一行double temp=a[t][i];
a[t][i]=a[row][i];
a[row][i]=temp;}//将当前的非0第一位数置为1,构造阶梯矩阵的斜边//这里要注意从后往前去更新数据,因为这里变化是根据第一个数变化的,要保持它的数据最后变化或者找个数存一for(int i = n;i>=col; i--){
a[row][i]/=a[row][col];}//用上面那一行来更新下面的所有行,将该列中最大值改为1后下面的数全变成0//同样要注意从后往前更新数据for(int i=row+1;i<n;i++){
if(Math.abs(a[i][col])>eps){
for(int j = n; j >=col; j--){
a[i][j]-=a[row][j]*a[i][col];}}}//下一行处理
row++;}//0解或者无穷解if(row<n){
//阶梯状,更新不了下面的说明往下的都是0;//判断下面每一行的最后结果,如果不是0,说明无解for(int i =row; i <n; i++){
if(Math.abs(a[i][n])>eps){
return2;}}return1;}//处理唯一解,从下往上得出解for(int i =n-1; i>=0; i--){
for(int j =i+1; j <n; j++){
a[i][n]-=a[j][n]*a[i][j];}}return0;}}