MUDA
Loading...
Searching...
No Matches
gauss_elimination.h
1#pragma once
2#include <muda/muda_def.h>
3#include <muda/ext/eigen/eigen_core_cxx20.h>
4
5namespace muda::eigen
6{
8{
9 template <typename T, int N>
10 MUDA_INLINE MUDA_GENERIC Eigen::Matrix<T, N, N> operator()(const Eigen::Matrix<T, N, N>& input)
11 {
12 Eigen::Matrix<T, N, N> result;
13
14 constexpr auto eps = std::numeric_limits<T>::epsilon();
15 constexpr int dim = N;
16 T mat[dim][dim * 2];
17 for(int i = 0; i < dim; i++)
18 {
19 for(int j = 0; j < 2 * dim; j++)
20 {
21 if(j < dim)
22 {
23 mat[i][j] = input(i, j); //[i, j];
24 }
25 else
26 {
27 mat[i][j] = j - dim == i ? 1 : 0;
28 }
29 }
30 }
31
32 for(int i = 0; i < dim; i++)
33 {
34 if(abs(mat[i][i]) < eps)
35 {
36 int j;
37 for(j = i + 1; j < dim; j++)
38 {
39 if(abs(mat[j][i]) > eps)
40 break;
41 }
42 if(j == dim)
43 return result;
44 for(int r = i; r < 2 * dim; r++)
45 {
46 mat[i][r] += mat[j][r];
47 }
48 }
49 T ep = mat[i][i];
50 for(int r = i; r < 2 * dim; r++)
51 {
52 mat[i][r] /= ep;
53 }
54
55 for(int j = i + 1; j < dim; j++)
56 {
57 T e = -1 * (mat[j][i] / mat[i][i]);
58 for(int r = i; r < 2 * dim; r++)
59 {
60 mat[j][r] += e * mat[i][r];
61 }
62 }
63 }
64
65 for(int i = dim - 1; i >= 0; i--)
66 {
67 for(int j = i - 1; j >= 0; j--)
68 {
69 T e = -1 * (mat[j][i] / mat[i][i]);
70 for(int r = i; r < 2 * dim; r++)
71 {
72 mat[j][r] += e * mat[i][r];
73 }
74 }
75 }
76
77
78 for(int i = 0; i < dim; i++)
79 {
80 for(int r = dim; r < 2 * dim; r++)
81 {
82 result(i, r - dim) = mat[i][r];
83 }
84 }
85
86 return result;
87 }
88};
89} // namespace muda::eigen
Definition gauss_elimination.h:8