Created
October 4, 2017 10:52
-
-
Save sue71/ac014dbfd8dec294fea27b1cf4e88fe6 to your computer and use it in GitHub Desktop.
LU decomposition logic written in Javascript
This file contains 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
let matA = [ | |
[1, 1, 0, 3], | |
[2, 1, -1, 1], | |
[3, -1, -1, 2], | |
[-1, 2, 3, -1] | |
]; | |
let N = matA.length; | |
console.log("matA", matA); | |
let matL = [ | |
[1, 0, 0, 0], | |
[0, 1, 0, 0], | |
[0, 0, 1, 0], | |
[0, 0, 0, 1], | |
]; | |
let matU = [ | |
[0, 0, 0, 0], | |
[0, 0, 0, 0], | |
[0, 0, 0, 0], | |
[0, 0, 0, 0], | |
]; | |
for (let i = 0; i < N; i++) { | |
// 次数 | |
let n = N - i - 1; | |
// u00 == a00 | |
let u00 = matU[i][i] = matA[0][0]; | |
// u1T == a1T | |
let u1T = [] | |
for (let j = 0; j < n; j++ ) { | |
u1T[j] = matU[i][j + i + 1] = matA[0][j + 1]; | |
} | |
// l1 = a1 / u00 | |
let l1 = [] | |
for (let j = 0; j < n; j++ ) { | |
l1[j] = matL[j + i + 1][i] = matA[j + 1][0] / u00; | |
} | |
// A1 = A1 - l1 * u1T | |
let lu = new Array(n); | |
for (let j = 0; j < n; j++) { | |
lu[j] = new Array(n) | |
for (let k = 0; k < n; k++) { | |
lu[j][k] = matA[j + 1][k + 1] - l1[j] * u1T[k]; | |
} | |
} | |
matA = lu; | |
} | |
// Check A = LU | |
let original = [ | |
[0, 0, 0, 0], | |
[0, 0, 0, 0], | |
[0, 0, 0, 0], | |
[0, 0, 0, 0], | |
]; | |
for (let i = 0; i < N; i++) { | |
for (let j = 0; j < N; j++) { | |
for (let k = 0; k < N; k++) { | |
original[i][j] += matL[i][k] * matU[k][j]; | |
} | |
} | |
} | |
console.log("matL", matL); | |
console.log("matU", matU); | |
console.log("matLU", original); | |
let matB = [ | |
4, 1, -3, 4 | |
]; | |
// Ly = B | |
let y = new Array(N); | |
for (let i = 0; i < N; i++) { | |
let sum = 0; | |
for (let j = 0; j < i; j++) { | |
sum += matL[i][j] * y[j]; | |
} | |
y[i] = (matB[i] - sum) / matL[i][i]; | |
} | |
// Ux = y | |
let x = new Array(N); | |
for (let i = N - 1; 0 <= i; i--) { | |
let sum = 0; | |
if (matU[i][i] === 0) { | |
continue; | |
} | |
for (let j = N - 1; j > i; j--) { | |
sum += matU[i][j] * x[j]; | |
} | |
x[i] = (y[i] - sum) / matU[i][i]; | |
} | |
console.log(x); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment