Advertisement
dmkozyrev

true_gauss.cpp

Feb 14th, 2017
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.17 KB | None | 0 0
  1. #include <vector>
  2. #include <iostream>
  3. #include <iomanip>
  4. #include <cmath>
  5. #include <fstream>
  6.  
  7. using namespace std;
  8.  
  9. ifstream fin ("in.txt");
  10. ofstream fout ("out.txt");
  11.  
  12. const double eps = 10e-9;
  13.  
  14. void print(const vector<vector<double>> & v) {
  15.     for (auto & row : v) {
  16.         for (auto & it : row)
  17.             fout << setw(12) << (fabs(it) > eps ? it : 0);
  18.         fout << endl;
  19.     }
  20. }
  21.  
  22. vector<double> solve(vector<vector<double>> & D) {
  23.     fout << "Input:" << endl;
  24.     print(D);
  25.     fout << endl;
  26.    
  27.     int m = D.size(), n = D.front().size(), now = 0;
  28.     for (int j = 0, i; j < n-1; ++j) {
  29.         int max = now;
  30.         for (i = now+1; i < m; ++i)
  31.             if (fabs(D[i][j]) > fabs(D[max][j]))
  32.                 max = i;
  33.        
  34.         if ( fabs(D[max][j]) < 10e-9 ) continue;
  35.        
  36.         swap(D[max], D[now]);
  37.        
  38.         for (i = now+1; i < m; ++i) {
  39.             if ( !D[i][j] ) continue;
  40.             double c = D[i][j] / D[now][j];
  41.             for (int k = j; k < n; ++k)
  42.                 D[i][k] -= c * D[now][k];
  43.         }
  44.         ++now;
  45.     }
  46.    
  47.     fout << "First:" << endl;
  48.     print(D);
  49.     fout << endl;
  50.    
  51.     now = m-1;
  52.    
  53.     for (int j = n-2; j >= 0; --j, --now) {
  54.         if ( !D[now][j] ) continue;
  55.        
  56.         for (int i = now-1; i >= 0; --i) {
  57.             if ( !D[i][j] ) continue;
  58.             double c = D[i][j] / D[now][j];
  59.             for (int k = n-1; k >= 0; --k)
  60.                 D[i][k] -= c * D[now][k];
  61.         }
  62.     }
  63.    
  64.     fout << "Second:" << endl;
  65.     print(D);
  66.     fout << endl;
  67.    
  68.     vector<double> answer(m, 0);
  69.     for (int i = 0; i < m; ++i)
  70.         if ( D[i][i] ) {
  71.             D[i].back() /= D[i][i];
  72.             D[i][i] = 1;
  73.             answer[i] = D[i].back();
  74.         }
  75.        
  76.     return answer;
  77. }
  78.  
  79. int main() {
  80.     int n;
  81.     fin >> n;
  82.     vector<vector<double>> s(n, vector<double>(n+1, 0));
  83.    
  84.     for (auto & row : s)
  85.         for (auto & it : row)
  86.             fin >> it;
  87.    
  88.    
  89.     auto a = solve(s);
  90.    
  91.     fout << "Answer:" << endl;  
  92.     for (auto & it : a)
  93.         fout << setw(12) << (fabs(it) > eps ? it : 0);
  94.     fout << endl;
  95.    
  96.     return 0;
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement