public class Gauss { private double matrix[]; private int cols, rows; public void makeMatrix(int r, int c) { cols = c; rows = r; matrix = new double[c * r]; } public double getValue(int r, int c) { return matrix[r * cols + c]; } public void setValue(int r, int c, double v) { matrix[r * cols + c] = v; } public void dumpMatrix() { int i, j; System.out.println("---"); for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { System.out.print(getValue(i, j) + " "); } System.out.println(""); } } int findrow(int n) { int i; for (i = n; i < rows; i++) { if (getValue(i, n) != 0) break; } if (i >= rows) i = -1; if (i != n) { System.out.println("ha!"); } return i; } void swaprows(int a, int b) { double x; int i; for(i = 0; i < cols; i++) { x = getValue(a, i); setValue(a, i, getValue(b, i)); setValue(b, i, x); } } public void addRow(int row, double[] d) { int i; for (i = 0; i < cols; i++) setValue(row, i, d[i]); } public double[] Eliminate() { int i, j, k; double[] ret = new double[rows]; for (i = 0; i < rows; i++) { double t1; int t4; t4 = findrow(i); if (t4 == -1) { continue; } if (t4 != i) { swaprows(t4, i); } t1 = getValue(i, i); for (j = i; j < cols; j++) { setValue(i, j, getValue(i, j)/t1); } for (j = i + 1; j < rows; j++) { double t2; t2 = getValue(j, i); for (k=i; k < cols; k++) { setValue(j, k, getValue(j, k)-t2*getValue(i, k)); } } } for (i = rows - 1; i >= 0; i--) { if (getValue(i, i) == 0) { for (j = i + 1; j < cols; j++) { if (getValue(i, j) == 0) { break; } } if (j != cols) break; } for (j = i - 1; j >= 0; j--) { double t3; t3 = getValue(j, i); for (k = i; k < cols; k++) { setValue(j, k, getValue(j, k) - t3*getValue(i, k)); } } } for (i = 0; i < rows; i++) ret[i] = getValue(i, cols-1); return ret; } }