Advertisement
kajacx

GaussJordan

Feb 5th, 2014
302
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.59 KB | None | 0 0
  1.     static void gaussJordan(BigRational[][] matrix) {
  2.         final int rows = matrix.length, cols = matrix[0].length;
  3.         int row = 0, col = 0, i, j;
  4.         BigRational[] swapBuffer;
  5.         BigRational multKoef;
  6.         while (row < rows && col < cols) {
  7.             i = row; //pos of non-null row
  8.             while (i < rows && matrix[i][col].equals(BigRational.ZERO)) {
  9.                 i++;
  10.             }
  11.             if (i == rows) {
  12.                 //no pivots at all
  13.                 col++;
  14.                 continue;
  15.             }
  16.             if (i != row) {
  17.                 //need to swap
  18.                 swapBuffer = matrix[i];
  19.                 matrix[i] = matrix[row];
  20.                 matrix[row] = swapBuffer;
  21.             }
  22.  
  23.             //set pivot to 1
  24.             multKoef = matrix[row][col].reciprocal();
  25.             matrix[row][col] = BigRational.ONE;
  26.             for (j = col + 1; j < cols; j++) {
  27.                 matrix[row][j] = matrix[row][j].times(multKoef);
  28.             }
  29.  
  30.             //set 0 over and under pivot
  31.             for (i = 0; i < rows; i++) {
  32.                 if (i == row) {
  33.                     continue;
  34.                 }
  35.                 if (matrix[i][col].equals(BigRational.ZERO)) {
  36.                     continue;
  37.                 }
  38.                 multKoef = matrix[i][col].negate();
  39.                 matrix[i][col] = BigRational.ZERO;
  40.                 for (j = col + 1; j < cols; j++) {
  41.                     matrix[i][j] = matrix[i][j].plus(matrix[row][j].times(multKoef));
  42.                 }
  43.             }
  44.  
  45.             //now move to next pivot
  46.             col++;
  47.             row++;
  48.         }
  49.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement