NumCpp  2.18.0
A Templatized Header Only C++ Implementation of the Python NumPy Library
Loading...
Searching...
No Matches
lu_decomposition.hpp
Go to the documentation of this file.
1
33#pragma once
34
35#include <utility>
36
39#include "NumCpp/Core/Types.hpp"
41#include "NumCpp/NdArray.hpp"
43
44namespace nc::linalg
45{
46 //============================================================================
47 // Method Description:
54 template<typename dtype>
55 std::pair<NdArray<double>, NdArray<double>> lu_decomposition(const NdArray<dtype>& inMatrix)
56 {
58
59 const auto shape = inMatrix.shape();
60 if (!shape.issquare())
61 {
62 THROW_RUNTIME_ERROR("Input matrix should be square.");
63 }
64
65 NdArray<double> lMatrix = zeros_like<double>(inMatrix);
66 NdArray<double> uMatrix = inMatrix.template astype<double>();
67
68 for (uint32 col = 0; col < shape.cols; ++col)
69 {
70 lMatrix(col, col) = 1;
71
72 for (uint32 row = col + 1; row < shape.rows; ++row)
73 {
74 const double& divisor = uMatrix(col, col);
75 if (utils::essentiallyEqual(divisor, double{ 0. }))
76 {
77 THROW_RUNTIME_ERROR("Division by 0.");
78 }
79
80 lMatrix(row, col) = uMatrix(row, col) / divisor;
81
82 for (uint32 col2 = col; col2 < shape.cols; ++col2)
83 {
84 uMatrix(row, col2) -= lMatrix(row, col) * uMatrix(col, col2);
85 }
86 }
87 }
88
89 return std::make_pair(lMatrix, uMatrix);
90 }
91} // namespace nc::linalg
#define THROW_RUNTIME_ERROR(msg)
Definition Error.hpp:40
#define STATIC_ASSERT_ARITHMETIC(dtype)
Definition StaticAsserts.hpp:39
Holds 1D and 2D arrays, the main work horse of the NumCpp library.
Definition NdArrayCore.hpp:135
const Shape & shape() const noexcept
Definition NdArrayCore.hpp:4587
Definition cholesky.hpp:41
std::pair< NdArray< double >, NdArray< double > > lu_decomposition(const NdArray< dtype > &inMatrix)
Definition lu_decomposition.hpp:55
bool essentiallyEqual(dtype inValue1, dtype inValue2) noexcept
Definition essentiallyEqual.hpp:47
NdArray< dtypeOut > zeros_like(const NdArray< dtype > &inArray)
Definition zeros_like.hpp:45
Shape shape(const NdArray< dtype > &inArray) noexcept
Definition Functions/shape.hpp:42
NdArray< dtypeOut > astype(const NdArray< dtype > inArray)
Definition astype.hpp:43
std::uint32_t uint32
Definition Types.hpp:40