Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Program
- {
- static void Gauss(float[,] M)
- {
- Console.WriteLine("Start:");
- for (int i = 0; i < M.GetLength(0); i++)
- {
- for (int j = 0; j < M.GetLength(1); j++)
- {
- Console.Write("| " + Math.Round(M[i, j], 1) + " |");
- if(j==M.GetLength(1)-2)
- {
- Console.Write("=");
- }
- }
- Console.WriteLine();
- }
- // size
- int rowCount = M.GetLength(0);
- for (int col = 0; col + 1 < rowCount; col++)
- if (M[col, col] == 0)
- {
- // find non-zero coefficient
- int swapRow = col + 1;
- for (; swapRow < rowCount; swapRow++)
- if (M[swapRow, col] != 0) break;
- if (M[swapRow, col] != 0)
- {
- // swap it with the above
- float[] tmp = new float[rowCount + 1];
- for (int i = 0; i < rowCount + 1; i++)
- {
- tmp[i] = M[swapRow, i];
- M[swapRow, i] = M[col, i];
- M[col, i] = tmp[i];
- }
- }
- }
- // elimination
- for (int sourceRow = 0; sourceRow + 1 < rowCount; sourceRow++)
- {
- for (int destRow = sourceRow + 1; destRow < rowCount; destRow++)
- {
- float df = M[sourceRow, sourceRow];
- float sf = M[destRow, sourceRow];
- for (int i = 0; i < rowCount + 1; i++)
- M[destRow, i] = M[destRow, i] * df - M[sourceRow, i] * sf;//умножаем n-ые элементы n строки на 1 эл-т 1 строки и наоборот,а затем вычитаем
- }
- }
- for (int row = rowCount - 1; row >= 0; row--)
- {
- float f = M[row, row];
- //divide in all rows on first number this row(сокращаем по возможности всю строку)
- for (int i = 0; i < rowCount + 1; i++)
- M[row, i] /= f;
- // substiling the value(подставляем значения x1,x2,x3....)
- for (int destRow = 0; destRow < row; destRow++)
- {
- M[destRow, rowCount] -= M[destRow, row] * M[row, rowCount];
- M[destRow, row] = 0;
- }
- }
- Console.WriteLine("Result:");
- for(int i = 0; i < M.GetLength(0); i++)
- {
- for(int j = 0; j < M.GetLength(1); j++)
- {
- Console.Write("| "+Math.Round(M[i, j],1) + " |");
- if (j == M.GetLength(1) - 2)
- {
- Console.Write("=");
- }
- }
- Console.WriteLine();
- }
- Console.WriteLine();
- for(int i = 0; i < M.GetLength(0); i++)
- {
- Console.WriteLine("X[{0}]" + Math.Round(M[i,rowCount],1),i+1);
- }
- }
- public static void Main()
- {
- float[,] ar = new float[,] { { 2, 4, 5, 5 }, { 4, 1, 3, 2 }, { 2, 1,3, 1 } };
- Gauss(ar);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment