@rayyamhk/matrix
Version:
A professional, comprehensive and high-performance library for you to manipulate matrices.
120 lines (88 loc) • 2.56 kB
JavaScript
var _require = require('../../Error'),
INVALID_MATRIX = _require.INVALID_MATRIX,
INVALID_SQUARE_MATRIX = _require.INVALID_SQUARE_MATRIX,
SINGULAR_MATRIX = _require.SINGULAR_MATRIX;
var Matrix = require('../..');
/**
* Find the inverse of non-singular matrix using Elementary Row Operations.
* If the matrix is singular, an error is thrown.
* @memberof Matrix
* @static
* @param {Matrix} A - Any square Matrix
* @returns {Matrix} The inverse of A
*/
function inverse(A) {
if (!(A instanceof this)) {
throw new Error(INVALID_MATRIX);
}
if (!A.isSquare()) {
throw new Error(INVALID_SQUARE_MATRIX);
}
var size = A.size()[0];
if (size === 0) {
// inverse of 0x0 matrix is itself
return new Matrix([]);
}
var EPSILON = 1 / (Math.pow(10, A._digit) * 2);
var inv = this.identity(size)._matrix;
var clone = this.clone(A)._matrix;
var permutation = initPermutation(size); // iterate each column
for (var j = 0; j < size; j++) {
var pivotIdx = j;
var pivot = clone[permutation[j]][j];
while (Math.abs(pivot) < EPSILON && pivotIdx < size - 1) {
pivotIdx++;
pivot = clone[permutation[pivotIdx]][j];
}
if (Math.abs(pivot) < EPSILON) {
throw new Error(SINGULAR_MATRIX);
}
if (j !== pivotIdx) {
var temp = permutation[j];
permutation[j] = permutation[pivotIdx];
permutation[pivotIdx] = temp;
}
var pivotRow = permutation[j]; // the pivot is guaranteed to be non-zero
for (var i = 0; i < size; i++) {
var ith = permutation[i];
if (i === j) {
for (var k = 0; k < size; k++) {
if (k === j) {
clone[ith][k] = 1;
}
if (k > j) {
clone[ith][k] /= pivot;
}
inv[ith][k] /= pivot;
}
pivot = 1;
}
if (i !== j && Math.abs(clone[ith][j]) >= EPSILON) {
var factor = clone[ith][j] / pivot;
for (var _k = 0; _k < size; _k++) {
if (_k === j) {
clone[ith][_k] = 0;
}
if (_k > j) {
clone[ith][_k] -= factor * clone[pivotRow][_k];
}
inv[ith][_k] -= factor * inv[pivotRow][_k];
}
}
}
}
for (var _i = 0; _i < size; _i++) {
clone[_i] = inv[permutation[_i]];
}
return new this(clone);
}
;
function initPermutation(size) {
var permutation = new Array(size);
for (var i = 0; i < size; i++) {
permutation[i] = i;
}
return permutation;
}
module.exports = inverse;
;