SPIDAR API Library  0x16033101
Space Interface Device for Artificial Reality
Cholesky.hpp
Go to the documentation of this file.
1 
5 #ifndef SPIDAR_CHOLESKY_HPP
6 #define SPIDAR_CHOLESKY_HPP
7 
8 #include <cmath>
9 
10 namespace Spidar
11 {
12 namespace Math
13 {
18 class Cholesky
19 {
20 public:
21  template <class MatrixType>
22  static void decompose(MatrixType& mat);
23 
24  template <class MatrixType, class VectorType>
25  static void solve(MatrixType& mat, VectorType& vec);
26 
27 }; // end of class Cholesky.
28 
34 template <class MatrixType>
35 void Cholesky::decompose(MatrixType& mat)
36 {
37  static_assert(MatrixType::row==MatrixType::column, "row != column");
38 
39  const size_t size = MatrixType::row;
40 
41  for(size_t j=0; j<size; ++j)
42  {
43  // 対角成分
44  for (size_t k=0; k<j; ++k)
45  {
46  mat[j][j] -= mat[j][k] * mat[j][k];
47  }
48  mat[j][j] = std::sqrt(mat[j][j]);
49 
50  // 対角成分以外のUは0
51  for (size_t i=0; i<j; ++i)
52  {
53  mat[i][j] = 0;
54  }
55 
56  // 残りのL
57  for (size_t i=j+1; i<size; ++i)
58  {
59  for (size_t k=0; k<j; ++k)
60  {
61  mat[i][j] -= mat[i][k] * mat[j][k];
62  }
63  mat[i][j] /= mat[j][j];
64  }
65  }
66 }
67 
74 template <class MatrixType, class VectorType>
75 void Cholesky::solve(MatrixType& mat, VectorType& vec)
76 {
77  static_assert(MatrixType::row==MatrixType::column, "row != column");
78  static_assert(MatrixType::row==VectorType::size, "matrix size != vector size");
79 
80  const size_t size = VectorType::size;
81 
82  // コレスキー分解
83  decompose(mat);
84 
85  // 前進代入(forward substitution)
86  for (size_t i=0; i<size; ++i)
87  {
88  for (size_t k=0; k<i; ++k)
89  {
90  vec[i] -= vec[k] * mat[i][k];
91  }
92  vec[i] /= mat[i][i];
93  }
94 
95  // 後退代入 (backward substitution)
96  for (size_t i=size-1; i<size; --i)
97  {
98  for (size_t k=i+1; k<size; ++k)
99  {
100  vec[i] -= vec[k] * mat[k][i];
101  }
102  vec[i] /= mat[i][i];
103  }
104 }
105 
106 } // end of namespace Math.
107 } // end of namespace Spidar.
108 
109 #endif // SPIDAR_CHOLESKY_HPP
110 
111 // end of file.
コレスキー法のクラスです.
Definition: Cholesky.hpp:18
SPIDARライブラリのルート名前空間です.
static void decompose(MatrixType &mat)
コレスキー分解を行います.
Definition: Cholesky.hpp:35
static void solve(MatrixType &mat, VectorType &vec)
コレスキー分解を用いて連立一次方程式を解きます.
Definition: Cholesky.hpp:75