NumCpp  1.0
A C++ implementation of the Python Numpy library
cholesky.hpp
Go to the documentation of this file.
1 #pragma once
34 
35 #include "NumCpp/NdArray.hpp"
38 #include "NumCpp/Core/Types.hpp"
39 
40 namespace nc
41 {
42  namespace linalg
43  {
44  //============================================================================
45  // Method Description:
54  template<typename dtype>
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  auto lMatrix = inMatrix.template astype<double>();
66 
67  for(uint32 row = 0; row < shape.rows; ++row)
68  {
69  for(uint32 col = row + 1; col < shape.cols; ++col)
70  {
71  lMatrix(row, col) = 0.0;
72  }
73  }
74 
75  for(uint32 k = 0; k < shape.cols; ++k)
76  {
77  const double& a_kk = lMatrix(k, k);
78 
79  if(a_kk > 0.0)
80  {
81  lMatrix(k, k) = std::sqrt(a_kk);
82 
83  for(uint32 i = k + 1; i < shape.rows; ++i)
84  {
85  lMatrix(i, k) /= lMatrix(k, k);
86 
87  for(uint32 j = k + 1; j <= i; ++j)
88  {
89  lMatrix(i, j) -= lMatrix(i, k) * lMatrix(j, k);
90  }
91  }
92  }
93  else
94  {
95  THROW_RUNTIME_ERROR("Matrix is not positive definite.");
96  }
97  }
98 
99  return lMatrix;
100  }
101  }
102 }
StaticAsserts.hpp
nc::NdArray::shape
Shape shape() const noexcept
Definition: NdArrayCore.hpp:4296
Error.hpp
STATIC_ASSERT_ARITHMETIC
#define STATIC_ASSERT_ARITHMETIC(dtype)
Definition: StaticAsserts.hpp:38
nc::sqrt
auto sqrt(dtype inValue) noexcept
Definition: sqrt.hpp:51
nc::shape
Shape shape(const NdArray< dtype > &inArray) noexcept
Definition: Functions/Shape.hpp:45
nc::NdArray< double >
nc::Shape::issquare
constexpr bool issquare() const noexcept
Definition: Core/Shape.hpp:124
nc::constants::j
constexpr auto j
Definition: Constants.hpp:46
nc::uint32
std::uint32_t uint32
Definition: Types.hpp:41
NdArray.hpp
nc::Shape::cols
uint32 cols
Definition: Core/Shape.hpp:46
THROW_RUNTIME_ERROR
#define THROW_RUNTIME_ERROR(msg)
Definition: Error.hpp:38
nc
Definition: Coordinate.hpp:45
nc::linalg::cholesky
NdArray< double > cholesky(const NdArray< dtype > &inMatrix)
Definition: cholesky.hpp:55
nc::Shape::rows
uint32 rows
Definition: Core/Shape.hpp:45
Types.hpp