numerics 0.1.0
Loading...
Searching...
No Matches
lu.cpp
Go to the documentation of this file.
1/// @file linalg/factorization/backends/seq/lu.cpp
2/// @brief Sequential Doolittle LU factorization with partial pivoting.
3#include "impl.hpp"
4#include <cmath>
5#include <algorithm>
6
7namespace num::backends::seq {
8
9LUResult lu(const Matrix& A) {
10 constexpr real singular_tol = 1e-14;
11 const idx n = A.rows();
12 LUResult f;
13 f.LU = A;
14 f.piv.resize(n);
15 f.singular = false;
16
17 Matrix& M = f.LU;
18
19 for (idx k = 0; k < n; ++k) {
20 idx pivot_row = k;
21 real pivot_val = std::abs(M(k, k));
22 for (idx i = k + 1; i < n; ++i) {
23 real v = std::abs(M(i, k));
24 if (v > pivot_val) {
25 pivot_val = v;
26 pivot_row = i;
27 }
28 }
29 f.piv[k] = pivot_row;
30
31 if (pivot_row != k)
32 for (idx j = 0; j < n; ++j)
33 std::swap(M(k, j), M(pivot_row, j));
34
35 if (std::abs(M(k, k)) < singular_tol) {
36 f.singular = true;
37 continue;
38 }
39
40 const real inv_ukk = real(1) / M(k, k);
41 for (idx i = k + 1; i < n; ++i)
42 M(i, k) *= inv_ukk;
43
44 for (idx i = k + 1; i < n; ++i) {
45 const real lik = M(i, k);
46 for (idx j = k + 1; j < n; ++j)
47 M(i, j) -= lik * M(k, j);
48 }
49 }
50
51 return f;
52}
53
54} // namespace num::backends::seq
Dense row-major matrix with optional GPU storage.
Definition matrix.hpp:12
constexpr idx rows() const noexcept
Definition matrix.hpp:24
LUResult lu(const Matrix &A)
Definition lu.cpp:9
double real
Definition types.hpp:10
std::size_t idx
Definition types.hpp:11
constexpr real e
Definition math.hpp:43
std::experimental::simd butterfly for FFT.
Result of an LU factorization with partial pivoting (PA = LU)
Definition lu.hpp:19
Matrix LU
Definition lu.hpp:20
std::vector< idx > piv
Definition lu.hpp:21
bool singular
Definition lu.hpp:22