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