2#include "../vector_matrix/FlatMatrix.hpp"
24 static_assert(std::is_floating_point_v<T>,
25 "T must be a floating-point type (float or double)");
30 void elimination(
int col);
33 std::iota(P.begin(), P.end(), 0);
35 std::vector<int> initInvP()
const {
37 std::vector<int>
invP(
n,-1);
38 for (
int i = 0;
i <
n;
i++) {
40 if (
pi < 0 || pi >=
n)
throw std::invalid_argument(
"invalid permutation");
45 int pivoting(
int col);
46 void forwardSubstitution(std::vector<T>&
y,
const std::vector<T>&
b,
int n)
const;
47 void backwardSubstitution(std::vector<T>&
x,
const std::vector<T>&
y,
int n)
const;
49 static constexpr T eps = std::numeric_limits<T>::epsilon() *
static_cast<T>(100);
62 const std::vector<int>&
getP()
const{
return P; }
68 int LU<T>::pivoting(
int col) {
71 int n = matrix.getRows();
72 for (
int i =
col+1;
i <
n;
i++) {
83 void LU<T>::elimination(
int col) {
85 int n = matrix.getRows();
99 void LU<T>::decomposition() {
100 if (matrix.getRows() != matrix.getCols())
101 throw std::runtime_error(
"Matrix must be square for LU decomposition");
102 int n = matrix.getRows();
105 for (
int k = 0;
k <
n; ++
k) {
108 for (
int j = 0;
j <
n;
j++) {
109 std::swap(matrix(
k,
j), matrix(
pivot,
j));
112 std::swap(P[
k], P[
pivot]);
115 if (std::abs(matrix(
k,
k)) <= eps) {
116 throw std::runtime_error(
"Matrix is singular or nearly singular at pivot " + std::to_string(
k));
125 int n = matrix.getRows();
127 for(
int i = 0;
i <
n;
i++) {
137 for (
int i = 1;
i <
n; ++
i) {
139 for (
int j = 0;
j <
i; ++
j) {
147 void LU<T>::backwardSubstitution(std::vector<T>& x,
const std::vector<T>& y,
int n)
const {
148 for (
int i =
n-1;
i >= 0; --
i){
150 for (
int j =
i+1;
j <
n; ++
j) {
159 int n = matrix.getRows();
161 std::vector<int>
invP = initInvP();
162 std::vector<T>
b(
n),
y(
n),
x(
n);
166 for(
int i = 0;
i <
n; ++
i) {
174 forwardSubstitution(
y,
b,
n);
175 backwardSubstitution(
x,
y,
n);
177 for (
int k = 0;
k <
n; ++
k) {
LU decomposition with partial pivoting.
Definition LU.hpp:23
const FlatMatrix< T > & getMatrix() const
Definition LU.hpp:63
T det() const
Definition LU.hpp:124
LU(const FlatMatrix< T > &m)
Definition LU.hpp:53
FlatMatrix< T > inv() const
Definition LU.hpp:158
LU(FlatMatrix< T > &&m)
Definition LU.hpp:57
const std::vector< int > & getP() const
Definition LU.hpp:62
Examples:
Definition VectorMatrix.hpp:32
VectorMatrix()
Definition VectorMatrix.hpp:61
int getRows() const
return count rows
Definition VectorMatrix.hpp:107
Definition DecomposeLU.hpp:9