NumCpp  2.6.2
A Templatized Header Only C++ Implementation of the Python NumPy Library
det.hpp
Go to the documentation of this file.
1 
28 #pragma once
29 
32 #include "NumCpp/Core/Shape.hpp"
33 #include "NumCpp/Core/Types.hpp"
34 #include "NumCpp/NdArray.hpp"
35 
36 #include <cmath>
37 #include <string>
38 
39 namespace nc
40 {
41  namespace linalg
42  {
43  //============================================================================
44  // Method Description:
55  template<typename dtype>
56  dtype det(const NdArray<dtype>& inArray)
57  {
59 
60  const Shape inShape = inArray.shape();
61  if (inShape.rows != inShape.cols)
62  {
63  THROW_INVALID_ARGUMENT_ERROR("input array must be square with size no larger than 3x3.");
64  }
65 
66  if (inShape.rows == 1)
67  {
68  return inArray.front();
69  }
70 
71  if (inShape.rows == 2)
72  {
73  return inArray(0, 0) * inArray(1, 1) - inArray(0, 1) * inArray(1, 0);
74  }
75 
76  if (inShape.rows == 3)
77  {
78  dtype aei = inArray(0, 0) * inArray(1, 1) * inArray(2, 2);
79  dtype bfg = inArray(0, 1) * inArray(1, 2) * inArray(2, 0);
80  dtype cdh = inArray(0, 2) * inArray(1, 0) * inArray(2, 1);
81  dtype ceg = inArray(0, 2) * inArray(1, 1) * inArray(2, 0);
82  dtype bdi = inArray(0, 1) * inArray(1, 0) * inArray(2, 2);
83  dtype afh = inArray(0, 0) * inArray(1, 2) * inArray(2, 1);
84 
85  return aei + bfg + cdh - ceg - bdi - afh;
86  }
87 
88  dtype determinant = 0;
89  NdArray<dtype> submat(inShape.rows - 1);
90 
91  for (uint32 c = 0; c < inShape.rows; ++c)
92  {
93  uint32 subi = 0;
94  for (uint32 i = 1; i < inShape.rows; ++i)
95  {
96  uint32 subj = 0;
97  for (uint32 j = 0; j < inShape.rows; ++j)
98  {
99  if (j == c)
100  {
101  continue;
102  }
103 
104  submat(subi, subj++) = inArray(i, j);
105  }
106  ++subi;
107  }
108  determinant += (static_cast<dtype>(std::pow(-1, c)) * inArray(0, c) * det(submat));
109  }
110 
111  return determinant;
112  }
113  } // namespace linalg
114 } // namespace nc
#define THROW_INVALID_ARGUMENT_ERROR(msg)
Definition: Error.hpp:36
#define STATIC_ASSERT_ARITHMETIC(dtype)
Definition: StaticAsserts.hpp:37
Holds 1D and 2D arrays, the main work horse of the NumCpp library.
Definition: NdArrayCore.hpp:72
Shape shape() const noexcept
Definition: NdArrayCore.hpp:4483
const_reference front() const noexcept
Definition: NdArrayCore.hpp:2933
A Shape Class for NdArrays.
Definition: Core/Shape.hpp:41
uint32 rows
Definition: Core/Shape.hpp:44
uint32 cols
Definition: Core/Shape.hpp:45
constexpr auto j
Definition: Constants.hpp:45
constexpr double c
speed of light
Definition: Constants.hpp:40
dtype det(const NdArray< dtype > &inArray)
Definition: det.hpp:56
Definition: Coordinate.hpp:45
std::uint32_t uint32
Definition: Types.hpp:40