|
| 1 | +/** |
| 2 | + * @description |
| 3 | + * Computes the determinant of the given matrix using elimination. |
| 4 | + * - Rounding errors may occur for some matrices. |
| 5 | + * - Only handles 6 decimal places. Rounds thereafter. |
| 6 | + * @Complexity_Analysis |
| 7 | + * Time complexity: O(n^3) |
| 8 | + * Space Complexity: O(n^2) |
| 9 | + * @param {number[][]} m - A square matrix (2D array) |
| 10 | + * @return {number} - The determinant |
| 11 | + * @example det([[1,1],[1,1]]) = 0 |
| 12 | + */ |
| 13 | + |
| 14 | +function interchange(m: number[][], from: number, to: number): number[][] { |
| 15 | + ;[m[to], m[from]] = [m[from], m[to]] |
| 16 | + return m |
| 17 | +} |
| 18 | + |
| 19 | +function addition( |
| 20 | + m: number[][], |
| 21 | + from: number, |
| 22 | + to: number, |
| 23 | + c: number |
| 24 | +): number[][] { |
| 25 | + m[to] = m[to].map((e, i) => e + c * m[from][i]) |
| 26 | + return m |
| 27 | +} |
| 28 | + |
| 29 | +function diagProduct(m: number[][]): number { |
| 30 | + let product = 1 |
| 31 | + for (let i = 0; i < m.length; i++) { |
| 32 | + product *= m[i][i] |
| 33 | + } |
| 34 | + return product |
| 35 | +} |
| 36 | + |
| 37 | +export function det(m: number[][]): number { |
| 38 | + if (m.some((r) => r.length != m.length)) { |
| 39 | + throw new Error('only square matrices can have determinants') |
| 40 | + } |
| 41 | + |
| 42 | + const decPlaces = 6 |
| 43 | + const epsilon = 1e-6 |
| 44 | + |
| 45 | + // track the number of applied interchange operations |
| 46 | + let appliedICs = 0 |
| 47 | + for (let i = 0; i < m[0].length; i++) { |
| 48 | + // partial pivotting |
| 49 | + let idealPivot = null |
| 50 | + let maxValue = 0 |
| 51 | + for (let j = i; j < m.length; j++) { |
| 52 | + if (Math.abs(m[j][i]) > maxValue) { |
| 53 | + maxValue = Math.abs(m[j][i]) |
| 54 | + idealPivot = j |
| 55 | + } |
| 56 | + } |
| 57 | + if (idealPivot === null) { |
| 58 | + return 0 |
| 59 | + } |
| 60 | + if (idealPivot != i) { |
| 61 | + m = interchange(m, i, idealPivot) |
| 62 | + appliedICs++ |
| 63 | + } |
| 64 | + // eliminate entries under the pivot |
| 65 | + for (let j = i + 1; j < m.length; j++) { |
| 66 | + if (Math.abs(m[j][i]) > epsilon) { |
| 67 | + m = addition(m, i, j, -m[j][i] / m[i][i]) |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + const result = diagProduct(m) * (-1) ** appliedICs |
| 72 | + return parseFloat(result.toFixed(decPlaces)) |
| 73 | +} |
0 commit comments