Advertisement
Guest User

Gauss elimination

a guest
Aug 24th, 2019
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.09 KB | None | 0 0
  1. public static double[] SolveSystem(double[][] typeMatrix, double[] grades)
  2. {
  3.     const double eps = 1e-9;
  4.     double[][] matrix = typeMatrix.Select(x => x.ToArray()).ToArray();
  5.     double[] column = grades.ToArray();
  6.     int m = matrix.Length, n = matrix[0].Length;
  7.     var result = Enumerable.Repeat(-1, n).ToArray();
  8.  
  9.     for (int col = 0, curRow = 0; col < n; col++)
  10.     {
  11.         double max = Enumerable.Range(curRow, m - curRow).Max(r => Math.Abs(matrix[r][col]));
  12.         int row = Enumerable.Range(curRow, m - curRow).First(r => Math.Abs(matrix[r][col]) == max);
  13.         if (Math.Abs(matrix[row][col]) < eps)
  14.             continue;
  15.         Swap(ref matrix[curRow], ref matrix[row]);
  16.         Swap(ref column[curRow], ref column[row]);
  17.         for (int r = 0; r < m; r++)
  18.             if (r != curRow && Math.Abs(matrix[r][col]) >= eps)
  19.             {
  20.                 double coef = matrix[r][col] / matrix[curRow][col];
  21.                 for (int c = col; c < n; c++)
  22.                     matrix[r][c] -= matrix[curRow][c] * coef;
  23.                 column[r] -= column[curRow] * coef;
  24.             }
  25.         result[col] = curRow;
  26.         curRow++;
  27.     }
  28.     return result.Select((row, col) => row < 0 ? 0 : column[row] / matrix[row][col]).ToArray();
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement