Advertisement
MeShootIn

Gauss-Seidel method

Jun 20th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <math.h>
  4.  
  5. using namespace std;
  6.  
  7. bool converges(vector < vector <double> > A){
  8.     int N = A.size();
  9.    
  10.     for(int i = 0; i < N; ++i){
  11.         double sum = 0;
  12.        
  13.         for(int j = 0; j < N; ++j){
  14.             if(j != i){
  15.                 sum += fabs(A[i][j]);
  16.             }
  17.         }
  18.        
  19.         if(fabs(A[i][i]) <= sum){
  20.             return false;
  21.         }
  22.     }
  23.    
  24.     return true;
  25. }
  26.  
  27. bool stop(vector <double> x, vector <double> x_prev, double Eps){
  28.     int N = x.size();
  29.    
  30.     for(int i = 0; i < N; ++i){
  31.         if(fabs(x[i] - x_prev[i]) >= Eps){
  32.             return false;
  33.         }
  34.     }
  35.    
  36.     return true;
  37. }
  38.  
  39. vector <double> Gauss_Seidel(vector < vector <double> > A, vector <double> b, double Eps){
  40.     int N = A.size();
  41.     vector <double> x(N), x_prev(N);
  42.    
  43.     do{
  44.         x_prev = x;
  45.        
  46.         for(int i = 0; i < N; ++i){
  47.             double sum = 0;
  48.            
  49.             for(int j = 0; j < i; ++j){
  50.                 sum += A[i][j] * x[j];
  51.             }
  52.             for(int j = i + 1; j < N; ++j){
  53.                 sum += A[i][j] * x_prev[j];
  54.             }
  55.             x[i] = (b[i] - sum) / A[i][i];
  56.         }
  57.     }
  58.     while(!stop(x, x_prev, Eps));
  59.    
  60.     return x;
  61. }
  62.  
  63. int main(){
  64.     int N;
  65.     cin >> N;
  66.    
  67.     vector < vector <double> > A(N, vector <double> (N));
  68.     vector <double> b(N);
  69.    
  70.     for(int i = 0; i < N; ++i){
  71.         for(int j = 0; j < N; ++j){
  72.             cin >> A[i][j];
  73.         }
  74.         cin >> b[i];
  75.     }
  76.    
  77.     if(!converges(A)){
  78.         cout << "The matrix does not have diagonal predominance!";
  79.         system("PAUSE");
  80.         return 0;
  81.     }
  82.    
  83.     double Eps = 1e-5;
  84.     cin >> Eps;
  85.    
  86.     for(auto & x : Gauss_Seidel(A, b, Eps)){
  87.         cout << x << endl;
  88.     }
  89.    
  90.     system("PAUSE");
  91.     return 0;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement