The implementation of Gaussian elimination is to use an augmented matrix to convert it into an upper triangle matrix, and then iterate from the bottom up to evaluate the value.
Specifically,
For example, there is a binary system
Then, the coefficient of the unknown is proposed to form a 2*2 matrix, and then the constant term on the right of the medium number of the equations is added to form a 2*3 matrix.
This is an augmented matrix,
Next we will turn into an upper triangle matrix,
From the first line of the Matrix to the last line,
For example, row I is currently facing,
In the last row from I to I, find the row with the largest absolute value of the column I and change the position of the row I. In this way, the exchange is advantageous, that is, when the case is 0, haha think about it
Then, use row I to delete all rows from I + 1 to the last row, the purpose of element elimination is to change column I of all rows after row I to 0.
Finally, it becomes an upper triangle matrix.
Perform iterative evaluation from bottom up.
If you don't know how to calculate the value by iteration, just make a draft.
My code:
#include<iostream>#include<map>#include<string>#include<cstring>#include<cstdio>#include<cstdlib>#include<cmath>#include<queue>#include<vector>#include<algorithm>using namespace std;double gauss(double a[10][10],int n){int i,j,k,t;for(i=0;i<n;i++){t=i;for(j=i+1;j<n;j++)if(fabs(a[j][i])>fabs(a[t][i]))t=j;if(t!=i)for(j=0;j<=n;j++)swap(a[i][j],a[t][j]);if(a[i][i]!=0)for(j=i+1;j<n;j++)for(k=n;k>=i;k--)a[j][k]-=a[j][i]/a[i][i]*a[i][k];}for(i=n-1;i>-1;i--){for(j=i+1;j<n;j++)a[i][n]-=a[j][n]*a[i][j];a[i][n]/=a[i][i];}}int main(){double a[10][10];int i,j,n;while(cin>>n){for(i=0;i<n;i++)for(j=0;j<=n;j++)cin>>a[i][j];gauss(a,n);for(i=0;i<n;i++)cout<<a[i][n]<<" ";cout<<endl;}}
Gaussian elimination implementation