Реализовать алгоритм нахождения обратной матрицы методом Гаусса - C#

Узнай цену своей работы

Формулировка задачи:

Прошу помощи, так как сам уже даже и не знаю. Нужно реализовать алгоритм нахождения обратной матрицы методом Гаусса Вот мой класс:
Листинг программы
  1. namespace mtest
  2. {
  3. public class Row
  4. {
  5. double[] m_dItems;
  6. public int Length { get { return m_dItems.GetLength(0); } }
  7. public Row(int nSize)
  8. {
  9. m_dItems = new double[nSize];
  10. }
  11.  
  12. public double this[int nIndex]
  13. {
  14. get
  15. {
  16. return m_dItems[nIndex];
  17. }
  18. set
  19. {
  20. m_dItems[nIndex] = value;
  21. }
  22. }
  23.  
  24. public static Row operator+ (Row rFirst, Row rSecond)
  25. {
  26. Row rResult = new Row(rFirst.Length);
  27. for (int i = 0; i < rFirst.Length; i++)
  28. rResult[i] = rFirst[i] + rSecond[i];
  29. return rResult;
  30. }
  31.  
  32. public static Row operator -(Row rFirst, Row rSecond)
  33. {
  34. Row rResult = new Row(rFirst.Length);
  35. for (int i = 0; i < rResult.Length; i++)
  36. rResult[i] = rFirst[i] - rSecond[i];
  37. return rResult;
  38. }
  39. public static Row operator *(Row rItem, double dValue)
  40. {
  41. Row rResult = new Row(rItem.Length);
  42. for (int i = 0; i < rResult.Length; i++)
  43. rResult[i] = rItem[i] * dValue;
  44. return rResult;
  45. }
  46. public static Row operator /(Row rItem, double dValue)
  47. {
  48. Row rResult = new Row(rItem.Length);
  49. for (int i = 0; i < rResult.Length; i++)
  50. rResult[i] = rItem[i] / dValue;
  51. return rResult;
  52. }
  53.  
  54. public override string ToString()
  55. {
  56. string sResult = "";
  57. for (int i = 0; i < Length; i++)
  58. sResult += m_dItems[i].ToString("F")+" ";
  59. return sResult.Trim();
  60. }
  61. }
  62.  
  63. public class Matrix
  64. {
  65. Row[] m_rRows;
  66. public int Length { get { return m_rRows.GetLength(0); } }
  67.  
  68. public Matrix(int nSize)
  69. {
  70. m_rRows = new Row[nSize];
  71. for (int i = 0; i < Length; i++)
  72. m_rRows[i] = new Row(nSize);
  73. }
  74. public Matrix(Matrix mEt)
  75. {
  76. m_rRows = new Row[mEt.Length];
  77. for (int i = 0; i < Length; i++)
  78. m_rRows[i] = new Row(mEt.Length);
  79. for (int i = 0; i < mEt.Length; i++)
  80. for (int j = 0; j < mEt.Length; j++)
  81. this[i][j] = mEt[i][j];
  82. }
  83. public static Matrix GenerateE(int nSize)
  84. {
  85. Matrix mResult = new Matrix(nSize);
  86. for (int i = 0; i < nSize; i++)
  87. mResult[i][i] = 1;
  88.  
  89. return mResult;
  90. }
  91.  
  92. public Row this[int nIndex]
  93. {
  94. get
  95. {
  96. return m_rRows[nIndex];
  97. }
  98. set
  99. {
  100. m_rRows[nIndex] = value;
  101. }
  102. }
  103.  
  104. public override string ToString()
  105. {
  106. string sResult = "";
  107. for (int i = 0; i < Length; i++)
  108. sResult += m_rRows[i].ToString() + "\n";
  109. return sResult;
  110. }
  111. public static string PrintSplitted(Matrix mL, Matrix mR)
  112. {
  113. string sResult = "";
  114. for (int i = 0; i < mL.Length; i++)
  115. sResult += mL[i].ToString() + " | " + mR[i]+"\n";
  116. return sResult;
  117. }
  118. public Matrix Invert()
  119. {
  120. Matrix mResult = Matrix.GenerateE(Length);
  121. /*
  122. * Получать "1" на элементе главной диагонали, а потом
  123. * Занулять оставшиеся элементы
  124. * */
  125. Matrix mCur = new Matrix(this);
  126. for (int i = 0; i < Length; i++) //Цикл по строкам сверху-вниз
  127. {
  128. //Заединичить вервую строку
  129. double dItem = mCur[i][i];
  130. mCur[i] = mCur[i] / dItem;
  131. mResult[i] = mResult[i] / dItem;
  132.  
  133. //Забить нулями вертикаль
  134. for (int j = 0; j < Length; j++)
  135. {
  136. if (i == j) continue; //Там единица должна быть
  137. double drTmp = mCur[j][i];
  138. Row rTmp = mCur[i];
  139. Row dTmp = mCur[i]* mCur[j][i];
  140. mCur[j] = mCur[j] - dTmp;
  141. mResult[j] = mResult[j] - dTmp;
  142. System.Console.WriteLine(PrintSplitted(mCur, mResult));
  143. System.Console.WriteLine("=========================================");
  144. }
  145.  
  146. }
  147. return mResult;
  148. }
  149. }
  150. }
Он работает, то есть левая матрица успешно приводится к единичной, но левая неправильная. Видимо, косяки в алгоритме, но тогда они какие-то странные

Решение задачи: «Реализовать алгоритм нахождения обратной матрицы методом Гаусса»

textual
Листинг программы
  1.  using System;
  2.  
  3. class Gauss
  4. {
  5.     public static int Main(string[] args)
  6.     {
  7.         try
  8.         {
  9.             Matrix a = (args.Length == 0) ? SLAU.In() : SLAU.In(args[0]);
  10.  
  11.             for (int k = 1; k <= a.AmountOfRows - 1; k++)
  12.             {
  13.                 if (a[k, k] == 0)
  14.                     for (int i = k + 1; i <= a.AmountOfRows; i++)
  15.                         if (a[i, k] != 0)
  16.                         {
  17.                             a.SwapRows(k, i);
  18.                             break;
  19.                         }
  20.  
  21.                 double delElem = a[k, k];
  22.                 if (delElem == 0)
  23.                 {
  24.                     Console.WriteLine("Система не совместна");
  25.                     return 0;
  26.                 }
  27.                 a.MulRow(k, 1 / delElem);
  28.                 for (int i = k + 1; i <= a.AmountOfRows; i++)
  29.                     a.SumRows(k, i, -a[i, k]);
  30.             }
  31.  
  32.             if (a[a.AmountOfRows, a.AmountOfColumns - 1] == 0)
  33.             {
  34.                 Console.WriteLine("Система не совместна");
  35.                 return 0;
  36.             }
  37.             a.MulRow(a.AmountOfRows, 1 / a[a.AmountOfRows, a.AmountOfColumns - 1]);
  38.  
  39.             Matrix res = new Matrix(a.AmountOfRows, 1);
  40.  
  41.             for (int i = a.AmountOfRows; i >= 1; i--)
  42.             {
  43.                 double sum = 0;
  44.                 for (int j = a.AmountOfRows; j >= i + 1; j--)
  45.                     sum += res[j, 1] * a[i, j];
  46.                 res[i, 1] = a[i, a.AmountOfColumns] - sum;
  47.             }
  48.             res.Out();
  49.         }
  50.         catch (Exception exc)
  51.         {
  52.             Console.WriteLine("Произошла критическая ошибка.
  53. Дальнейшее выполение программы нецелесобразно!!!");
  54.             Console.WriteLine(exc.StackTrace);
  55.             Console.WriteLine(exc.TargetSite);
  56.             return 1;
  57.         }
  58.         finally
  59.         {
  60.             Console.WriteLine();
  61.             Console.Write("Для продолжения нажмите Enter ... ");
  62.             Console.ReadLine();
  63.         }
  64.         return 0;
  65.     }
  66. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

5   голосов , оценка 4.6 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы