Gaussian elimination

For the Gaussian elimination method to solve a system of linear equations,

My understanding is similar to the method of addition, subtraction and subtraction when we do math problems,

Just write it as a general program operation process

For a linear system of equations, we eliminate the elements below the corresponding row of a column from left to right by adding and subtracting elements,

The coefficients of each element finally form an upper triangular matrix, and then reverse the order to find the answer

In order to ensure the operability of the program, we need to reduce the number used to eliminate the following elements to 1 each time,

Then subtract the coefficient of each element of the following row from the coefficient of the main row * the multiple of expansion,

At this time, the multiple is the coefficient of the element to be eliminated in the row.

 

It is recommended to look at the content of "Mathematics in One Book", the introduction is relatively simple

 

Find pivot:

The division operation of double has some errors. When we operate, we must find the pivot element with the largest beginning each time to eliminate it, which can reduce the precision error

The replacement process:

ans[i]=m[i][n+1]-m[i+1][i]*ans[i+1]-m[i+2][i]*ans[i+2]-m[i+3][i]*ans[i+3]……-m[n][i]*ans[n];(ans[i]/系数1=ans[i])

 

This is actually very similar to our addition, subtraction and subtraction elements.

 

Template Question https://www.luogu.org/problemnew/show/P3389

Code:

 

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cmath>
 4 using namespace std;
 5 const int MAXN = 1010;
 6 int n;
 7 double a[MAXN][MAXN],ans[MAXN];
 8 int main()
 9 {
10     scanf("%d",&n);
11     for(int i=1;i<=n;i++)
12      for(int j=1;j<=n+1;j++)
13       scanf("%lf",&a[i][j]);
14     for(int i=1;i<=n;i++)
15     {
16         int now=i;
17         for(int j=i+1;j<=n;j++)
18          if(fabs(a[now][i])<fabs(a[j][i])) now=j;  //找主元
19         if(now!=i) swap(a[i],a[now]);         //换到当前行
20         double d=a[i][i];
21         if(d== 0 ){ //If there is 0 on the diagonal, there will be elements that cannot be eliminated and a unique solution cannot be obtained
 22              puts( " No Solution " );
 23              return  0 ;
 24          }
 25          for ( int j= i;j<=n+ 1 ;j++) a[i][j]/= d; //Pivoting to 1
 26          for ( int j=i+ 1 ;j<=n;j++ )
 27           for ( int k= i+ 1 ;k<=n+ 1 ;k++ )
 28            a[j][k]-=a[j][i]* a[i][k]; //Each line below eliminates the element in the same column, this line also transform at the same time
29         for(int j=i+1;j<=n;j++)
30          a[j][i]=0;
31     }
32     for(int i=n;i>=1;i--)
33     {
34         ans[i]=a[i][n+1];
35         for(int j=i+1;j<=n;j++)
36          ans[i]-=a[i][j]*ans[j];
37     }
38     for(int i=1;i<=n;i++)
39      printf("%.2lf\n",ans[i]+1e-9);
40     return 0;
41 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324954614&siteId=291194637