Skip to content

Instantly share code, notes, and snippets.

@ktcy
Created February 16, 2014 13:04
Show Gist options
  • Save ktcy/9033899 to your computer and use it in GitHub Desktop.
Save ktcy/9033899 to your computer and use it in GitHub Desktop.
function gaussianElimination(matrix) {
var pivot, base, col, div, mul, v, n, i, j;
n = matrix.length;
// Forward Elimination
for (pivot = 0; pivot < n - 1; pivot++) {
swap(matrix, pivot);
base = matrix[pivot];
div = base[pivot];
if (div === 0) {
continue;
}
for (i = pivot + 1; i < n; i++) {
col = matrix[i];
mul = col[pivot] / div;
for (j = pivot; j <= n; j++) {
col[j] -= mul * base[j];
}
}
}
// Back Substitution
for (i = n - 1; i >= 0; i--) {
col = matrix[i];
v = col[n];
for (j = i + 1; j < n; j++) {
v -= col[j] * matrix[j][n];
}
div = col[i];
col[n] = div ? v / div : 0;
}
return matrix.map(function(col) { return col[n]; });
}
function swap(matrix, pivot) {
var target, max, v, n, i, tmp;
n = matrix.length;
target = pivot;
max = matrix[pivot][pivot];
for (i = pivot + 1; i < n; i++) {
v = matrix[i][pivot];
if (max === 0 || v / max > 1) {
max = v;
target = i;
}
}
if (target !== pivot) {
tmp = matrix[pivot];
matrix[pivot] = matrix[target];
matrix[target] = tmp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment