NumCpp  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  else if (inShape.rows == 2)
72  {
73  return inArray(0, 0) * inArray(1, 1) - inArray(0, 1) * inArray(1, 0);
74  }
75  else if (inShape.rows == 3)
76  {
77  dtype aei = inArray(0, 0) * inArray(1, 1) * inArray(2, 2);
78  dtype bfg = inArray(0, 1) * inArray(1, 2) * inArray(2, 0);
79  dtype cdh = inArray(0, 2) * inArray(1, 0) * inArray(2, 1);
80  dtype ceg = inArray(0, 2) * inArray(1, 1) * inArray(2, 0);
81  dtype bdi = inArray(0, 1) * inArray(1, 0) * inArray(2, 2);
82  dtype afh = inArray(0, 0) * inArray(1, 2) * inArray(2, 1);
83 
84  return aei + bfg + cdh - ceg - bdi - afh;
85  }
86  else
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  }
114  }
115 }
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::NdArray< dtype >
nc::NdArray::front
value_type front() const noexcept
Definition: NdArrayCore.hpp:2782
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