Created
December 10, 2024 10:40
-
-
Save cosmicproc/1242ee0937a90737e6bef8725ff1771c to your computer and use it in GitHub Desktop.
TypeScript concise and fast determinant
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
type vector = number[]; | |
type matrix = vector[]; | |
function interchange(m: matrix, from: number, to: number) { | |
[m[to], m[from]] = [m[from], m[to]]; | |
return m; | |
} | |
function addition(m: matrix, from: number, to: number, c: number) { | |
m[to] = m[to].map((e, i) => e + c * m[from][i]); | |
return m; | |
} | |
function diagProduct(m: matrix) { | |
let product = 1; | |
for (let i = 0; i < m.length; i++) { | |
product *= m[i][i]; | |
} | |
return product; | |
} | |
function det(m: matrix) { | |
let appliedICs = 0; | |
for (let j = 0; j < m[0].length; j++) { | |
if (m[j][j] === 0) { | |
let nonzero = m.slice(j + 1).findIndex((e) => e[j] !== 0); | |
if (nonzero === -1) { | |
return 0; | |
} | |
appliedICs++; | |
m = interchange(m, nonzero + j + 1, j); | |
} | |
for (let i = j + 1; i < m[0].length; i++) { | |
if (m[i][j] !== 0) { | |
m = addition(m, j, i, -m[i][j] / m[j][j]); | |
} | |
} | |
} | |
return diagProduct(m) * (-1) ** appliedICs; | |
} | |
// For matrices larger than 100x100, | |
// the result may exceed the max number in JS so you may get Infinity. | |
const sampleSize = 100; | |
const sample = new Array(sampleSize) | |
.fill(0) | |
.map(() => | |
new Array(sampleSize) | |
.fill(0) | |
.map(() => Math.round(Math.random() * sampleSize)) | |
); | |
console.log(det(sample)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment