Advertisement
vatman

Untitled

May 22nd, 2024
471
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.77 KB | None | 0 0
  1. #include <cmath>
  2. #include <fstream>
  3. #include <vector>
  4.  
  5. void method_vr(const std::string &input_file_path, const std::string &output_file_path) {
  6.   double w = 1.2;
  7.   int N_max = 10000;
  8.   int S = 0;
  9.   double eps;
  10.   double eps_max = 0;
  11.   double eps_cur = 0;
  12.   int n;
  13.  
  14.   std::ifstream input_file(input_file_path);
  15.   input_file>> eps;
  16.   input_file >> n;
  17.  
  18.   std::vector<std::vector<double>> a(n, std::vector<double>(n));
  19.   std::vector<double> b(n);
  20.   std::vector<double> x(n);
  21.  
  22.   for (int i = 0; i < n; ++i) {
  23.     for (int j = 0; j < n; ++j) {
  24.       input_file >> a[i][j];
  25.     }
  26.   }
  27.  
  28.   for (int j = 0; j < n; ++j) {
  29.     input_file >> b[j];
  30.   }
  31.  
  32.   for (int j = 0; j < n; ++j) {
  33.     input_file >> x[j];
  34.   }
  35.  
  36.   input_file.close();
  37.  
  38.   double x_old;
  39.   double x_new;
  40.   bool f = false;
  41.   while (!f) {
  42.     for (int i = 0; i < n; ++i) {
  43.       x_old = x[i];
  44.       x_new = (1 - w) * x[i]*a[i][i] + w * b[i];
  45.       for (int j = 0; j < n; ++j) {
  46.         if (j != i) {
  47.           x_new -= w * a[i][j] * x[j];
  48.         }
  49.       }
  50.       x_new /= a[i][i];
  51.       eps_cur = fabs(x_old - x_new);
  52.       if (i == 1) {
  53.         eps_max = eps_cur;
  54.       } else if (eps_cur > eps_max) {
  55.         eps_max = eps_cur;
  56.       }
  57.       x[i] = x_new;
  58.     }
  59.     S += 1;
  60.     if ((eps_max <= eps) || (S >= N_max)) {
  61.       f = true;
  62.     }
  63.   }
  64.  
  65.   std::ofstream output_file(output_file_path);
  66.   output_file << "eps_max: " << eps_max << '\n';
  67.   for (int i = 0; i < n; ++i) {
  68.     output_file << x[i] << ' ';
  69.   }
  70.   output_file << '\n';
  71.   output_file << "count of steps: " << S << '\n';
  72.   output_file.close();
  73. }
  74.  
  75. int main() {
  76.   std::string input_file_path = "input.txt";
  77.   std::string output_file_path = "output.txt";
  78.   method_vr(input_file_path, output_file_path);
  79.   return 0;
  80. }
  81.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement