tesseract++ 0.0.1
N-dimensional tensor library for embedded systems
Loading...
Searching...
No Matches
determinant.h
Go to the documentation of this file.
1#ifndef FUSED_ALGORITHMS_DETERMINANT_H
2#define FUSED_ALGORITHMS_DETERMINANT_H
3
4#include "config.h"
6
21namespace matrix_algorithms
22{
23
32 template <typename T, my_size_t N>
34 {
35 if constexpr (N == 1)
36 {
37 return A(0, 0);
38 }
39 else if constexpr (N == 2)
40 {
41 return A(0, 0) * A(1, 1) - A(0, 1) * A(1, 0);
42 }
43 else if constexpr (N == 3)
44 {
45 // clang-format off
46 return A(0, 0) * (A(1, 1) * A(2, 2) - A(1, 2) * A(2, 1))
47 - A(0, 1) * (A(1, 0) * A(2, 2) - A(1, 2) * A(2, 0))
48 + A(0, 2) * (A(1, 0) * A(2, 1) - A(1, 1) * A(2, 0));
49 // clang-format on
50 }
51 else if constexpr (N == 4)
52 {
53 // 2×2 minors from rows 0–1
54 T c0 = A(0, 0) * A(1, 1) - A(0, 1) * A(1, 0);
55 T c1 = A(0, 0) * A(1, 2) - A(0, 2) * A(1, 0);
56 T c2 = A(0, 0) * A(1, 3) - A(0, 3) * A(1, 0);
57 T c3 = A(0, 1) * A(1, 2) - A(0, 2) * A(1, 1);
58 T c4 = A(0, 1) * A(1, 3) - A(0, 3) * A(1, 1);
59 T c5 = A(0, 2) * A(1, 3) - A(0, 3) * A(1, 2);
60
61 // 2×2 minors from rows 2–3
62 T s0 = A(2, 0) * A(3, 1) - A(2, 1) * A(3, 0);
63 T s1 = A(2, 0) * A(3, 2) - A(2, 2) * A(3, 0);
64 T s2 = A(2, 0) * A(3, 3) - A(2, 3) * A(3, 0);
65 T s3 = A(2, 1) * A(3, 2) - A(2, 2) * A(3, 1);
66 T s4 = A(2, 1) * A(3, 3) - A(2, 3) * A(3, 1);
67 T s5 = A(2, 2) * A(3, 3) - A(2, 3) * A(3, 2);
68
69 return c0 * s5 - c1 * s4 + c2 * s3 + c3 * s2 - c4 * s1 + c5 * s0;
70 }
71 else
72 {
73 static_assert(is_floating_point_v<T>,
74 "determinant requires a floating-point scalar type for N > 4");
75
76 auto lu_result = lu(A);
77
78 if (!lu_result.has_value())
79 {
80 return T(0);
81 }
82
83 auto &decomp = lu_result.value();
84
85 T det = T(decomp.sign);
86
87 for (my_size_t i = 0; i < N; ++i)
88 {
89 det *= decomp.LU(i, i);
90 }
91
92 return det;
93 }
94 }
95
96} // namespace matrix_algorithms
97
98#endif // FUSED_ALGORITHMS_DETERMINANT_H
Definition fused_matrix.h:12
Global configuration for the tesseract tensor library.
#define my_size_t
Size/index type used throughout the library.
Definition config.h:126
LU decomposition with partial pivoting for square matrices.
Definition cholesky.h:52
T determinant(const FusedMatrix< T, N, N > &A)
Compute the determinant of a square matrix.
Definition determinant.h:33
Expected< LUResult< T, N >, MatrixStatus > lu(const FusedMatrix< T, N, N > &A, T tol=T(PRECISION_TOLERANCE))
Compute the LU decomposition of a square matrix with partial pivoting.
Definition lu.h:151