Advertisement
double_trouble

invMat

Oct 22nd, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. void SLAE::LUdecomposition()
  2. {
  3.     L.resize(eqcount);
  4.     U.resize(eqcount);
  5.     for (int i(0); i < eqcount; ++i) {
  6.         L[i].resize(varcount);
  7.         U[i].resize(varcount);
  8.     }
  9.  
  10.     for (int i(0); i < eqcount; ++i) {
  11.         for (int j(0); j < varcount; ++j) {
  12.             if (i <= j) {
  13.                 U[i][j] = A[i][j];
  14.                 for (int t(0); t <= i; ++t) {
  15.                     U[i][j] -= L[i][t] * U[t][j];
  16.                 }
  17.             }
  18.             else {
  19.                 L[i][j] = A[i][j];
  20.                 for (int t(0); t < j; ++t) {
  21.                     L[i][j] -= L[i][t] * U[t][j];
  22.                 }
  23.                 L[i][j] /= U[j][j];
  24.             }
  25.         }
  26.         L[i][i] = 1;
  27.     }
  28. }
  29.  
  30. void SLAE::LUsolution()
  31. {
  32.     LUdecomposition();
  33.     std::vector<double> y(varcount);
  34.     for (int j(0); j < varcount; ++j) {
  35.         y[j] = B[j];
  36.         for (int i(0); i < j; ++i) {
  37.             y[j] -= L[j][i] * y[i];
  38.         }
  39.     }
  40.  
  41.     for (int j(eqcount - 1); j >= 0; --j) {
  42.         solution[j] = y[j];
  43.         for (int i(j + 1); i < varcount; ++i) {
  44.             solution[j] -= U[j][i] * solution[i];
  45.         }
  46.         solution[j] /= U[j][j];
  47.     }
  48. }
  49.  
  50. std::vector<std::vector<double> > SLAE::inverseMatrix()
  51. {
  52.     LUdecomposition();
  53.     std::vector<std::vector<double> > inv;
  54.     inv.resize(eqcount);
  55.     for (int i(0); i < eqcount; ++i) {
  56.         inv[i].resize(varcount);
  57.     }
  58.  
  59.     std::vector<double> b;
  60.     for (int i(0); i < eqcount; ++i) {
  61.         b.clear();
  62.         for (int j(0); j < eqcount; ++j) {
  63.             if (j == i) {
  64.                 b.push_back(1);
  65.             }
  66.             else {
  67.                 b.push_back(0);
  68.             }
  69.         }
  70.         SLAE s(A, b);
  71.         s.LUsolution();
  72.         for (int j(0); j < eqcount; ++j) {
  73.             inv[j][i] = s.solution[j];
  74.         }
  75.     }
  76.     return inv;
  77. }
  78.  
  79. void SLAE::invMatMethod()
  80. {
  81.     std::vector < std::vector<double> > invA(inverseMatrix());
  82.     solution = invA * B;
  83. }
  84.  
  85. //кусочек из мэйна
  86. S.invMatMethod();
  87. cout << "Solution:" << endl;
  88. for (int i(0); i < n; ++i) {
  89.     cout << "x" << i + 1 << " = " << S.solution[i] << endl;
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement