Created
February 16, 2014 13:04
-
-
Save ktcy/9033899 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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