NumCpp  2.7.0
A Templatized Header Only C++ Implementation of the Python NumPy Library
det.hpp
Go to the documentation of this file.
1 #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:
53  template<typename dtype>
54  dtype det(const NdArray<dtype>& inArray)
55  {
57 
58  const Shape inShape = inArray.shape();
59  if (inShape.rows != inShape.cols)
60  {
61  THROW_INVALID_ARGUMENT_ERROR("input array must be square with size no larger than 3x3.");
62  }
63 
64  if (inShape.rows == 1)
65  {
66  return inArray.front();
67  }
68 
69  if (inShape.rows == 2)
70  {
71  return inArray(0, 0) * inArray(1, 1) - inArray(0, 1) * inArray(1, 0);
72  }
73 
74  if (inShape.rows == 3)
75  {
76  dtype aei = inArray(0, 0) * inArray(1, 1) * inArray(2, 2);
77  dtype bfg = inArray(0, 1) * inArray(1, 2) * inArray(2, 0);
78  dtype cdh = inArray(0, 2) * inArray(1, 0) * inArray(2, 1);
79  dtype ceg = inArray(0, 2) * inArray(1, 1) * inArray(2, 0);
80  dtype bdi = inArray(0, 1) * inArray(1, 0) * inArray(2, 2);
81  dtype afh = inArray(0, 0) * inArray(1, 2) * inArray(2, 1);
82 
83  return aei + bfg + cdh - ceg - bdi - afh;
84  }
85 
86  dtype determinant = 0;
87  NdArray<dtype> submat(inShape.rows - 1);
88 
89  for (uint32 c = 0; c < inShape.rows; ++c)
90  {
91  uint32 subi = 0;
92  for (uint32 i = 1; i < inShape.rows; ++i)
93  {
94  uint32 subj = 0;
95  for (uint32 j = 0; j < inShape.rows; ++j)
96  {
97  if (j == c)
98  {
99  continue;
100  }
101 
102  submat(subi, subj++) = inArray(i, j);
103  }
104  ++subi;
105  }
106  determinant += (static_cast<dtype>(std::pow(-1, c)) * inArray(0, c) * det(submat));
107  }
108 
109  return determinant;
110  }
111  } // namespace linalg
112 } // 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:4283
const_reference front() const noexcept
Definition: NdArrayCore.hpp:2772
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:54
Definition: Coordinate.hpp:45
std::uint32_t uint32
Definition: Types.hpp:40