Advertisement
LinKin

Gaussian Elimination

May 2nd, 2013
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.17 KB | None | 0 0
  1. /*
  2.  * Algorithm: Gaussian Elimination
  3.  * Complexity : O( N^3 )
  4.  */
  5. typedef vector<double> VD;
  6. /* indexin 0 base */
  7. /* return 1 if unique sol ,0 if no sol , INF if multiple sol */
  8. long Gauss( vector<VD> A,vector< double> &Ans )
  9. {
  10.     long Row = (long)A.size();
  11.     long Col = (long)A[0].size() - 1;
  12.     vector<long> Where( Col,-1 );
  13.     long r,c,i,j;
  14.     for( c=0,r=0;c<Col && r<Row;c++ ){
  15.         long sel = r;
  16.         for( i=r;i<Row;i++ ){
  17.             if( fabs( A[i][c] ) > fabs( A[sel][c] ) ) sel = i;
  18.         }
  19.         if( fabs( A[sel][c] ) < EPS ) continue ;
  20.         swap( A[sel] ,A[r] ) ;
  21.         Where[c] = r;
  22.         for( i=0;i<Row;i++ ){
  23.             if( i==r ) continue;
  24.             double CON = A[i][c] / A[r][c] ;
  25.             for( j=c;j<=Col;j++ ) A[i][j] -= A[r][j]*CON;
  26.         }
  27.         r++;
  28.     }
  29.     Ans.assign( Col,0 ) ;
  30.     for( i=0;i<Col;i++ ){
  31.         if( Where[i]==-1 ) continue;
  32.         Ans[i] = A[Where[i]][Col] / A[Where[i]][i];
  33.     }
  34.  
  35.     for( i=0;i<Row;i++ ){
  36.         double Where = 0;
  37.         for( j=0;j<Col;j++ ) Where += Ans[j] * A[i][j];
  38.         /* Found a row which hs all zero co-eff */
  39.         if( fabs( Where - A[i][Col] ) > EPS ){
  40.             return 0;
  41.         }
  42.     }
  43.     for( i=0;i<Col;i++ ){
  44.         if( Where[i] == -1 ){
  45.             return INF ;
  46.         }
  47.     }
  48.     return 1 ;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement