Advertisement
dtorkin

Untitled

Dec 26th, 2023
788
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.12 KB | None | 0 0
  1.  
  2. #include <iostream>
  3. #include <cmath>
  4. #include <vector>
  5. #include <algorithm>
  6. #include <chrono>
  7.  
  8. using namespace std::chrono;
  9. using namespace std::literals;
  10. using matrix = std::vector<std::vector<double>>;
  11.  
  12. std::vector<double> iterationMethod(const matrix& A, const std::vector<double>& b)
  13. {
  14.     for (int j = 0; j < A.size(); ++j)
  15.     {
  16.         double sum = 0;
  17.  
  18.         for (int i = 0; i < A.size(); ++i)
  19.         {
  20.             if (j != i)
  21.             {
  22.                 sum += A[j][i];
  23.             }
  24.         }
  25.  
  26.         if (sum >= std::abs(A[j][j]))
  27.         {
  28.             throw std::runtime_error("wrong matrix");
  29.         }
  30.     }
  31.  
  32.     matrix C = A;
  33.     std::vector<double> F = b;
  34.  
  35.     for (int j = 0; j < C.size(); ++j)
  36.     {
  37.         for (int i = 0; i < C.size(); ++i)
  38.         {
  39.             if (j == i)
  40.             {
  41.                 C[j][i] = 0;
  42.             }
  43.             else
  44.             {
  45.                 C[j][i] /= A[j][j];
  46.                 C[j][i] *= -1;
  47.             }
  48.         }
  49.     }
  50.  
  51.     for (int i = 0; i < F.size(); ++i)
  52.     {
  53.         F[i] /= A[i][i];
  54.     }
  55.  
  56.     std::vector<double> prev(b.size(), 0);
  57.     std::vector<double> cur(b.size(), 0);
  58.     double maxDif = 0;
  59.     double accuracy = 0.001f;
  60.  
  61.     do
  62.     {
  63.         prev = cur;
  64.         maxDif = 0;
  65.        
  66.         for (int j = 0; j < C.size(); ++j)
  67.         {
  68.             double sum = 0;
  69.  
  70.             for (int i = 0; i < C.size(); ++i)
  71.             {
  72.                 sum += C[j][i] * prev[i];
  73.             }
  74.  
  75.             cur[j] = sum + F[j];
  76.         }
  77.  
  78.         for (int i = 0; i < cur.size(); ++i)
  79.         {
  80.             double dif = std::abs(cur[i] - prev[i]);
  81.  
  82.             if (dif > maxDif)
  83.             {
  84.                 maxDif = dif;
  85.             }
  86.         }
  87.     }
  88.     while (maxDif > accuracy);
  89.  
  90.     return cur;
  91. }
  92.  
  93. int main()
  94. {
  95.     std::vector<double> res = iterationMethod(m, b);
  96.    
  97.     time_point<high_resolution_clock> endTime = clock.now();
  98.  
  99.     std::cout << "Result = { ";
  100.  
  101.     for (auto& i : res)
  102.     {
  103.         std::cout << i << " ";
  104.     }
  105.  
  106.     std::cout << "}" << std::endl;
  107.  
  108.     return 0;
  109. }
  110.  
  111.  
  112.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement