Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 31 additions & 4 deletions utils/matrixMath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,38 @@ export const getDeterminant = (m: MatrixData): number | null => {
if (n === 1) return m[0][0];
if (n === 2) return m[0][0] * m[1][1] - m[0][1] * m[1][0];

// Simple recursion for example (Laplace expansion on row 0)
let det = 0;
for (let j = 0; j < n; j++) {
det += Math.pow(-1, j) * m[0][j] * getDeterminant(getMinor(m, 0, j))!;
// Gaussian elimination (O(N^3))
const tempM = m.map(row => [...row]); // Copy matrix to avoid side effects
let det = 1;

for (let i = 0; i < n; i++) {
// Pivot
let pivotIdx = i;
for (let j = i + 1; j < n; j++) {
if (Math.abs(tempM[j][i]) > Math.abs(tempM[pivotIdx][i])) {
pivotIdx = j;
}
}

// Swap rows if needed
if (pivotIdx !== i) {
[tempM[i], tempM[pivotIdx]] = [tempM[pivotIdx], tempM[i]];
det *= -1;
}

if (Math.abs(tempM[i][i]) < 1e-10) return 0; // Singular matrix

Comment on lines +73 to +74

Copilot AI Feb 4, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The singular-matrix check uses a fixed absolute threshold (1e-10). This is scale-dependent and can incorrectly return 0 for non-singular matrices with small pivots (or fail to detect singularity for very large-valued matrices). Consider using a relative tolerance based on the matrix scale (e.g., compare pivot to maxAbs in the column/row or to a norm times Number.EPSILON) and/or make the epsilon a named constant configurable by callers.

Copilot uses AI. Check for mistakes.
det *= tempM[i][i];

// Elimination
for (let j = i + 1; j < n; j++) {
const factor = tempM[j][i] / tempM[i][i];
for (let k = i; k < n; k++) {
tempM[j][k] -= factor * tempM[i][k];
}
}
}

return det;
};

Expand Down
Loading