SHARE
TWEET

Gauss elimination

a guest Aug 24th, 2019 86 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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 resRows = Enumerable.Repeat(-1, n).ToArray();
  8.  
  9.     for (int col = 0, row = 0; row < m && col < n; col++)
  10.     {
  11.         double max = Enumerable.Range(row, m - row).Max(r => Math.Abs(matrix[r][col]));
  12.         int xrow = Enumerable.Range(row, m - row).First(r => Math.Abs(matrix[r][col]) == max);
  13.         if (Math.Abs(matrix[xrow][col]) < eps)
  14.             continue;
  15.         Swap(ref matrix[row], ref matrix[xrow]);
  16.         Swap(ref column[row], ref column[xrow]);
  17.         for (int r = 0; r < m; r++)
  18.             if (r != row && Math.Abs(matrix[r][col]) >= eps)
  19.             {
  20.                 double coef = matrix[r][col] / matrix[row][col];
  21.                 for (int c = col; c < n; c++)
  22.                     matrix[r][c] -= matrix[row][c] * coef;
  23.                 column[r] -= column[row] * coef;
  24.             }
  25.         resRows[col] = row++;
  26.     }
  27.     return resRows.Select((row, col) => row < 0 ? 0 : column[row] / matrix[row][col]).ToArray();
  28. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top