Matrix_code

math - Guass

Jul 22nd, 2017 (edited)
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.18 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. #define EPS    1e-9
  3. using namespace std;
  4. struct Gauss{
  5.     /*          1  1 |  3  5
  6.                 1 -1 |  1  6
  7.                 {x+y=3}{x+y=5}
  8.                 {x-y=1}{x-y=6}
  9.     */
  10.     void show(vector<vector<double> > a, vector <vector< double> > b)
  11.     {
  12.         for(int i= 0;i< a.size();i ++) {
  13.             for(int j= 0;j < a[i].size(); j ++) printf("%5.2lf ",a[i][j]);
  14.             printf("| ");
  15.             for(int j = 0; j < b[i].size(); j ++) printf("%5.2lf ",b[i][j]);
  16.             printf("\n");
  17.         }
  18.     }
  19.     int gauss(vector< vector< double > > &a , vector< vector<double > > &b)
  20.     {
  21.         // AX = B;
  22.         // Here n -> # of equations, m = number of column in A, p = # column in B
  23.         // The function returns the rank of the matrix
  24.         int n = a.size(), m= a[0].size() , p = b[0].size();
  25.         int r = 0;
  26.  
  27.         for(int c = 0; c < m  && r < n ; c ++ ) {
  28.             int j = r;
  29.             for(int i = r+1; i < n; i ++ ) {
  30.                 if(fabs(a[i][c]) > fabs(a[j][c])) j= i;
  31.             }
  32.             if(fabs(a[j][c]) < EPS) continue;
  33.             if(j!=r)swap(a[j],a[r]), swap(b[j],b[r]);
  34.             double s = 1./a[r][c];
  35.  
  36.             for(int i = 0; i < m ; i ++ ) a[r][i] *= s;
  37.             for(int i = 0; i < p ; i ++ ) b[r][i] *= s;
  38.             for(int i=0;i < n ;i ++) if(i!=r) {
  39.                 double t = a[i][c];
  40.                 for(int j = 0; j < m ; j ++ ) a[i][j] -= t * a[r][j];
  41.                 for(int j = 0; j < p ; j ++ ) b[i][j] -= t * b[r][j];
  42.             }
  43.             r++;
  44.         }
  45.         return r;
  46.     }
  47. }g;
  48.  
  49. int main()
  50. {
  51.     double a[][2] = {{1,1},{1,-1}};
  52.     double b[][2] = {{3,1},  {5,6}};
  53.  
  54.     vector< vector<double> > A(2, vector<double> (2,0));
  55.     for(int i = 0;i<2; i ++) {
  56.         for(int j = 0; j < 2;j++) {
  57.             A[i][j] = a[i][j];
  58.         }
  59.     }
  60.  
  61.     vector< vector<double> > B(2 , vector<double> (2,0));
  62.     for(int i = 0; i <2;i ++ ) {
  63.         for(int j = 0; j < 2; j ++ ) B[j][i] = b[i][j];
  64.     }
  65.  
  66.  
  67.     g.gauss(A,B);
  68.     for(int i = 0; i < 2;i ++) printf("%lf ",B[i][0]); puts("");
  69.     for(int i = 0; i < 2;i ++) printf("%lf ",B[i][1]);
  70.     return 0;
  71. }
Add Comment
Please, Sign In to add comment