NAbdulla

GaussianElimination

Aug 14th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.02 KB | None | 0 0
  1. /*
  2.     origin: http://www.comp.nus.edu.sg/~stevenha/myteaching/competitive_programming/ch9.zip
  3. */
  4.  
  5. #include <cmath>
  6. #include <cstdio>
  7. using namespace std;
  8.  
  9. #define MAX_N 3                              // adjust this value as needed
  10. struct AugmentedMatrix { double mat[MAX_N][MAX_N + 1]; };
  11. struct ColumnVector { double vec[MAX_N]; };
  12.  
  13. ColumnVector GaussianElimination(int N, AugmentedMatrix Aug) {
  14.   // input: N, Augmented Matrix Aug, output: Column vector X, the answer
  15.   int i, j, k, l; double t;
  16.  
  17.   for (i = 0; i < N - 1; i++) {            // the forward elimination phase
  18.     l = i;
  19.     for (j = i + 1; j < N; j++)       // which row has largest column value, pivoting strategy
  20.       if (fabs(Aug.mat[j][i]) > fabs(Aug.mat[l][i]))
  21.         l = j;                                       // remember this row l
  22.     // swap this pivot row, reason: minimize floating point error
  23.     for (k = i; k <= N; k++)            // t is a temporary double variable
  24.       t = Aug.mat[i][k], Aug.mat[i][k] = Aug.mat[l][k], Aug.mat[l][k] = t;
  25.     for (j = i + 1; j < N; j++)     // the actual forward elimination phase
  26.       for (k = N; k >= i; k--)//why not "for(k = i; k <= N; k++)"?
  27.         Aug.mat[j][k] -= Aug.mat[i][k] * Aug.mat[j][i] / Aug.mat[i][i];//care should be taken when Aug.mat[i][i] == 0
  28.   }
  29.  
  30.   ColumnVector Ans;                          // the back substitution phase
  31.   for (j = N - 1; j >= 0; j--) {                         // start from back
  32.     for (t = 0.0, k = j + 1; k < N; k++) t += Aug.mat[j][k] * Ans.vec[k];
  33.     Ans.vec[j] = (Aug.mat[j][N] - t) / Aug.mat[j][j]; // the answer is here
  34.   }
  35.   return Ans;
  36. }
  37.  
  38. int main() {
  39.   AugmentedMatrix Aug;
  40.   Aug.mat[0][0] = 1; Aug.mat[0][1] = 1; Aug.mat[0][2] = 2; Aug.mat[0][3] = 9;
  41.   Aug.mat[1][0] = 2; Aug.mat[1][1] = 4; Aug.mat[1][2] = -3; Aug.mat[1][3] = 1;
  42.   Aug.mat[2][0] = 3; Aug.mat[2][1] = 6; Aug.mat[2][2] = -5; Aug.mat[2][3] = 0;
  43.  
  44.   ColumnVector X = GaussianElimination(3, Aug);
  45.   printf("X = %.1lf, Y = %.1lf, Z = %.1lf\n", X.vec[0], X.vec[1], X.vec[2]);
  46.  
  47.   return 0;
  48. }
Add Comment
Please, Sign In to add comment