JavaScript:掃き出し法による逆行列の計算

今回は、掃き出し法(Gaussian elimination method, row reduction algorithm)を使って、正方行列の逆行列を計算するプログラムを紹介します。 但し、線形方程式を解くだけなら、こちらの記事 C++ vs Python vs JavaScript vs Julia のGaussの消去法を使ったほうが、逆行列を使って x=A-1b を計算するよりも高速に計算できます。 尚、下記のプログラムは、こちらの paiza.IO で試せます。

inverse.js


class Matrix {
  constructor(matrix) {
    this.n = matrix.length;
    this.matrix = matrix;
    this.invers = Array(this.n).fill().map(() => Array(this.n).fill(0));
  }
  inverse() {
    for (let i = 0; i < this.n; i++) {
      for (let j = 0; j < this.n; j++) {
        this.invers[i][j] = (i != j) ? 0 : 1;
      }
    }
    for (let i = 0; i < this.n; i++) {
      const scalar = 1 / this.matrix[i][i];
      for (let j = 0; j < this.n; j++) {
        this.matrix[i][j] *= scalar;
        this.invers[i][j] *= scalar;
      }
      for (let j = 0; j < this.n; j++) {
        if (i != j) {
          const scalar = this.matrix[j][i];
          for (let k = 0; k < this.n; k++) {
            this.matrix[j][k] -= scalar * this.matrix[i][k];
            this.invers[j][k] -= scalar * this.invers[i][k];
          }
        }
      }
    }
    return this.invers;
  }
}
const matrix = new Matrix([[1, -2, 8, -5, 3], [-8, 0, 6, 4, -1], [2, 9, 0, 5, -7], [3, -2, -7, 1, 5], [-8, 6, 4, -9, 0]]);
console.log(matrix.inverse());
 

 

〈結果〉


[[0.07274085710454226, -0.06044177091515161, 0.04536485373283013,  0.007777926780206557, -0.04120768597099561],
 [0.06390927029253435,  0.02933006379432559, 0.11649648460698483,  0.130615529033123350,  0.05676353953140865],
 [0.10151535470028161,  0.03969424701622636, 0.03486656832506370, -0.004157167761834557, -0.01984712350811318],
 [0.02306557596888830,  0.09092128201689689, 0.05283626123105807,  0.078315676545527680, -0.04546064100844844],
 [0.11942757524090500,  0.08538477748615875, 0.05762562501197342,  0.226096285369451560,  0.02873618268549206]]