Advertisement
HaS5HeM

C++ JACOBI'S ALGO

May 28th, 2021 (edited)
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3. using namespace std;
  4. int main() {
  5.     float A[3][3], C[3], X[3];
  6.     float X1 = 0, X2 = 0, X3 = 0, TOL;
  7.     int i, c = 0, ITR;
  8.  
  9.     cout << "Enter the matrix of coefficients:\n";
  10.     for (i = 0; i < 3; i++)
  11.         for (int j = 0; j < 3; j++)
  12.             cin >> A[i][j];
  13.  
  14.     cout << "Enter the vector of constants:\n";
  15.     for (i = 0; i < 3; i++)
  16.         cin >> C[i];
  17.  
  18.     cout << "Enter the number of iterations and stopping tolerance respectively:\t";
  19.     cin >> ITR >> TOL;
  20.  
  21.     for (i = 0; i < ITR; i++) {
  22.         X[0] = (1 / A[0][0]) * (C[0] - A[0][1] * X2 - A[0][2] * X3);
  23.         X[1] = (1 / A[1][1]) * (C[1] - A[1][0] * X1 - A[1][2] * X3);
  24.         X[2] = (1 / A[2][2]) * (C[2] - A[2][0] * X1 - A[2][1] * X2);
  25.  
  26.         if ((abs(X[0] - X1) < TOL) && (abs(X[1] - X2) < TOL) && (abs(X[2] - X3) < TOL)) {
  27.             printf("\n%.3f\tDiff: %.3f\n%.3f\tDiff: %.3f\n%.3f\tDiff: %.3f\n\n", X[0], abs(X[0] - X1), X[1], abs(X[1] - X2), X[2], abs(X[2] - X3));
  28.             cout << endl << endl << "Number of iterations:" << i << endl;
  29.             c = 1;
  30.             break;
  31.         }
  32.  
  33.         X1 = X[0]; X2 = X[1]; X3 = X[2];
  34.     }
  35.     if (c == 0)
  36.         printf("\n%.3f\tDiff: %.3f\n%.3f\tDiff: %.3f\n%.3f\tDiff: %.3f\n\n", X[0], abs(X[0] - X1), X[1], abs(X[1] - X2), X[2], abs(X[2] - X3));
  37.     return 0;
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement