54void mat_mul(
const std::valarray<std::valarray<double>> &A,
55 const std::valarray<std::valarray<double>> &B,
56 std::valarray<std::valarray<double>> *OUT) {
62 perror(
"Matrix dimensions mismatch!");
66 for (
int i = 0; i < R1; i++) {
67 for (
int j = 0; j < C2; j++) {
69 for (
int k = 0; k < C1; k++) {
70 OUT[0][i][j] += A[i][k] * B[k][j];
98std::valarray<double>
eigen_values(std::valarray<std::valarray<double>> *A,
99 bool print_intermediates =
false) {
100 int rows = A->size();
102 int counter = 0, num_eigs = rows - 1;
105 std::valarray<std::valarray<double>> Q(rows);
106 std::valarray<std::valarray<double>> R(columns);
109 std::valarray<double> eigen_vals(rows);
110 for (
int i = 0; i < rows; i++) {
111 Q[i] = std::valarray<double>(columns);
112 R[i] = std::valarray<double>(columns);
116 while (num_eigs > 0) {
118 while (std::abs(A[0][num_eigs][num_eigs - 1]) >
119 std::numeric_limits<double>::epsilon()) {
121 last_eig = A[0][num_eigs][num_eigs];
122 for (
int i = 0; i < rows; i++) {
123 A[0][i][i] -= last_eig;
128 if (print_intermediates) {
129 std::cout << *A <<
"\n";
130 std::cout << Q <<
"\n";
131 std::cout << R <<
"\n";
132 printf(
"-------------------- %d ---------------------\n",
139 for (
int i = 0; i < rows; i++) {
140 A[0][i][i] += last_eig;
145 eigen_vals[num_eigs] = last_eig;
147 if (print_intermediates) {
148 std::cout <<
"========================\n";
149 std::cout <<
"Eigen value: " << last_eig <<
",\n";
150 std::cout <<
"========================\n";
157 eigen_vals[0] = A[0][0][0];
159 if (print_intermediates) {
160 std::cout << Q <<
"\n";
161 std::cout << R <<
"\n";
178 std::valarray<std::valarray<double>> X = {{5, 7}, {7, 11}};
179 double y[] = {15.56158, 0.384227};
181 std::cout <<
"------- Test 1 -------" << std::endl;
184 for (
int i = 0; i < 2; i++) {
185 std::cout << i + 1 <<
"/2 Checking for " << y[i] <<
" --> ";
187 for (
int j = 0; j < 2 && !result; j++) {
188 if (std::abs(y[i] - eig_vals[j]) < 0.1) {
190 std::cout <<
"(" << eig_vals[j] <<
") ";
194 std::cout <<
"found\n";
196 std::cout <<
"Test 1 Passed\n\n";
211 std::valarray<std::valarray<double>> X = {{-4, 4, 2, 0, -3},
215 {-3, -1, -3, -3, 0}};
216 double y[] = {9.27648, -9.26948, 2.0181, -1.03516,
219 std::cout <<
"------- Test 2 -------" << std::endl;
222 std::cout << X <<
"\n"
223 <<
"Eigen values: " << eig_vals <<
"\n";
225 for (
int i = 0; i < 5; i++) {
226 std::cout << i + 1 <<
"/5 Checking for " << y[i] <<
" --> ";
228 for (
int j = 0; j < 5 && !result; j++) {
229 if (std::abs(y[i] - eig_vals[j]) < 0.1) {
231 std::cout <<
"(" << eig_vals[j] <<
") ";
235 std::cout <<
"found\n";
237 std::cout <<
"Test 2 Passed\n\n";