-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmath_test.cc
82 lines (56 loc) · 1.39 KB
/
math_test.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Author: Mingcheng Chen ([email protected])
#include "math.h"
#include "sparse_matrix.h"
#include <cstdio>
#include <vector>
void conjugate_gradient_test() {
printf("conjugate_gradient_test {\n");
// Test Case 1
SparseMatrix a(4, 2);
a.set_element(0, 0, 1.0);
a.set_element(0, 1, 2.0);
a.set_element(1, 0, 2.0);
a.set_element(1, 1, -3.0);
a.set_element(2, 0, 4.0);
a.set_element(2, 1, -1.0);
a.set_element(3, 0, -5.0);
a.set_element(3, 1, 2.0);
// Suppose solution is (2, 3).
std::vector<double> b(4);
b[0] = 3.0; // 8.0
b[1] = 2.0; // -5.0
b[2] = -4.0;
b[3] = 5.0;
std::vector<double> x(2);
x[0] = x[1] = 0.0;
Math::conjugate_gradient(a, &b[0], 2, &x[0]);
std::vector<double> c(4);
a.multiply_column(&x[0], &c[0]);
printf("x: %lf %lf\n", x[0], x[1]);
for (int i = 0; i < 4; i++) {
printf(" %lf(%lf)", c[i], b[i]);
}
printf("\n");
// Test Case 2
a = SparseMatrix(1, 2);
a.set_element(0, 0, 1.0);
a.set_element(0, 1, 2.0);
b.resize(1);
b[0] = 3.0;
// x[0] = x[1] = 0.0;
x[0] = 7.0;
x[1] = -3.0;
Math::conjugate_gradient(a, &b[0], 1, &x[0]);
c.resize(1);
a.multiply_column(&x[0], &c[0]);
printf("x: %lf %lf\n", x[0], x[1]);
for (int i = 0; i < 1; i++) {
printf(" %lf(%lf)", c[i], b[i]);
}
printf("\n");
printf("} conjugate_gradient_test\n");
}
int main() {
conjugate_gradient_test();
return 0;
}