Реализовать алгоритм нахождения обратной матрицы методом Гаусса - C#
Формулировка задачи:
Прошу помощи, так как сам уже даже и не знаю.
Нужно реализовать алгоритм нахождения обратной матрицы методом Гаусса
Вот мой класс:
Он работает, то есть левая матрица успешно приводится к единичной, но левая неправильная. Видимо, косяки в алгоритме, но тогда они какие-то странные
Листинг программы
- namespace mtest
- {
- public class Row
- {
- double[] m_dItems;
- public int Length { get { return m_dItems.GetLength(0); } }
- public Row(int nSize)
- {
- m_dItems = new double[nSize];
- }
- public double this[int nIndex]
- {
- get
- {
- return m_dItems[nIndex];
- }
- set
- {
- m_dItems[nIndex] = value;
- }
- }
- public static Row operator+ (Row rFirst, Row rSecond)
- {
- Row rResult = new Row(rFirst.Length);
- for (int i = 0; i < rFirst.Length; i++)
- rResult[i] = rFirst[i] + rSecond[i];
- return rResult;
- }
- public static Row operator -(Row rFirst, Row rSecond)
- {
- Row rResult = new Row(rFirst.Length);
- for (int i = 0; i < rResult.Length; i++)
- rResult[i] = rFirst[i] - rSecond[i];
- return rResult;
- }
- public static Row operator *(Row rItem, double dValue)
- {
- Row rResult = new Row(rItem.Length);
- for (int i = 0; i < rResult.Length; i++)
- rResult[i] = rItem[i] * dValue;
- return rResult;
- }
- public static Row operator /(Row rItem, double dValue)
- {
- Row rResult = new Row(rItem.Length);
- for (int i = 0; i < rResult.Length; i++)
- rResult[i] = rItem[i] / dValue;
- return rResult;
- }
- public override string ToString()
- {
- string sResult = "";
- for (int i = 0; i < Length; i++)
- sResult += m_dItems[i].ToString("F")+" ";
- return sResult.Trim();
- }
- }
- public class Matrix
- {
- Row[] m_rRows;
- public int Length { get { return m_rRows.GetLength(0); } }
- public Matrix(int nSize)
- {
- m_rRows = new Row[nSize];
- for (int i = 0; i < Length; i++)
- m_rRows[i] = new Row(nSize);
- }
- public Matrix(Matrix mEt)
- {
- m_rRows = new Row[mEt.Length];
- for (int i = 0; i < Length; i++)
- m_rRows[i] = new Row(mEt.Length);
- for (int i = 0; i < mEt.Length; i++)
- for (int j = 0; j < mEt.Length; j++)
- this[i][j] = mEt[i][j];
- }
- public static Matrix GenerateE(int nSize)
- {
- Matrix mResult = new Matrix(nSize);
- for (int i = 0; i < nSize; i++)
- mResult[i][i] = 1;
- return mResult;
- }
- public Row this[int nIndex]
- {
- get
- {
- return m_rRows[nIndex];
- }
- set
- {
- m_rRows[nIndex] = value;
- }
- }
- public override string ToString()
- {
- string sResult = "";
- for (int i = 0; i < Length; i++)
- sResult += m_rRows[i].ToString() + "\n";
- return sResult;
- }
- public static string PrintSplitted(Matrix mL, Matrix mR)
- {
- string sResult = "";
- for (int i = 0; i < mL.Length; i++)
- sResult += mL[i].ToString() + " | " + mR[i]+"\n";
- return sResult;
- }
- public Matrix Invert()
- {
- Matrix mResult = Matrix.GenerateE(Length);
- /*
- * Получать "1" на элементе главной диагонали, а потом
- * Занулять оставшиеся элементы
- * */
- Matrix mCur = new Matrix(this);
- for (int i = 0; i < Length; i++) //Цикл по строкам сверху-вниз
- {
- //Заединичить вервую строку
- double dItem = mCur[i][i];
- mCur[i] = mCur[i] / dItem;
- mResult[i] = mResult[i] / dItem;
- //Забить нулями вертикаль
- for (int j = 0; j < Length; j++)
- {
- if (i == j) continue; //Там единица должна быть
- double drTmp = mCur[j][i];
- Row rTmp = mCur[i];
- Row dTmp = mCur[i]* mCur[j][i];
- mCur[j] = mCur[j] - dTmp;
- mResult[j] = mResult[j] - dTmp;
- System.Console.WriteLine(PrintSplitted(mCur, mResult));
- System.Console.WriteLine("=========================================");
- }
- }
- return mResult;
- }
- }
- }
Решение задачи: «Реализовать алгоритм нахождения обратной матрицы методом Гаусса»
textual
Листинг программы
- using System;
- class Gauss
- {
- public static int Main(string[] args)
- {
- try
- {
- Matrix a = (args.Length == 0) ? SLAU.In() : SLAU.In(args[0]);
- for (int k = 1; k <= a.AmountOfRows - 1; k++)
- {
- if (a[k, k] == 0)
- for (int i = k + 1; i <= a.AmountOfRows; i++)
- if (a[i, k] != 0)
- {
- a.SwapRows(k, i);
- break;
- }
- double delElem = a[k, k];
- if (delElem == 0)
- {
- Console.WriteLine("Система не совместна");
- return 0;
- }
- a.MulRow(k, 1 / delElem);
- for (int i = k + 1; i <= a.AmountOfRows; i++)
- a.SumRows(k, i, -a[i, k]);
- }
- if (a[a.AmountOfRows, a.AmountOfColumns - 1] == 0)
- {
- Console.WriteLine("Система не совместна");
- return 0;
- }
- a.MulRow(a.AmountOfRows, 1 / a[a.AmountOfRows, a.AmountOfColumns - 1]);
- Matrix res = new Matrix(a.AmountOfRows, 1);
- for (int i = a.AmountOfRows; i >= 1; i--)
- {
- double sum = 0;
- for (int j = a.AmountOfRows; j >= i + 1; j--)
- sum += res[j, 1] * a[i, j];
- res[i, 1] = a[i, a.AmountOfColumns] - sum;
- }
- res.Out();
- }
- catch (Exception exc)
- {
- Console.WriteLine("Произошла критическая ошибка.
- Дальнейшее выполение программы нецелесобразно!!!");
- Console.WriteLine(exc.StackTrace);
- Console.WriteLine(exc.TargetSite);
- return 1;
- }
- finally
- {
- Console.WriteLine();
- Console.Write("Для продолжения нажмите Enter ... ");
- Console.ReadLine();
- }
- return 0;
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д