]> git.tdb.fi Git - libs/math.git/blob - tests/matrix.cpp
Use numeric_limits in Matrix test cases
[libs/math.git] / tests / matrix.cpp
1 #include <limits>
2 #include <msp/linal/matrix.h>
3 #include <msp/linal/squarematrix.h>
4 #include <msp/test/test.h>
5
6 using namespace std;
7 using namespace Msp;
8
9 class MatrixTests: public Test::RegisteredTest<MatrixTests>
10 {
11 public:
12         MatrixTests();
13
14         static const char *get_name() { return "Matrix"; }
15
16 private:
17         void multiply();
18         void invert();
19 };
20
21
22 MatrixTests::MatrixTests()
23 {
24         add(&MatrixTests::multiply, "Multiplication");
25         add(&MatrixTests::invert,   "Inversion");
26 }
27
28 void MatrixTests::multiply()
29 {
30         static double data[] =
31         {
32                 1, 2, 1, 2, 1, 2,
33                 3, 0, 3, 0, 0, 3,
34                 3, 6, 3, 3, 6, 3, 6, 3, 6,
35                 9, 3, 9, 6
36         };
37
38         LinAl::Matrix<double, 3, 2> a(data);
39         LinAl::Matrix<double, 2, 3> b(data+6);
40         EXPECT_EQUAL(a*b, (LinAl::Matrix<double, 3, 3>(data+12)));
41         EXPECT_EQUAL(b*a, (LinAl::Matrix<double, 2, 2>(data+21)));
42 }
43
44 template<typename T, unsigned N>
45 bool is_identity(const LinAl::Matrix<T, N, N> &m)
46 {
47         static const T limit = numeric_limits<T>::epsilon()*4;
48         for(unsigned i=0; i<N; ++i)
49                 for(unsigned j=0; j<N; ++j)
50                         if(abs(T(i==j)-m(i, j))>limit)
51                                 return false;
52         return true;
53 }
54
55 void MatrixTests::invert()
56 {
57         static double data[] =
58         {
59                 1, 4, 2, 4, 8, 6, 2, 2, 4
60         };
61
62         LinAl::SquareMatrix<double, 3> m(data);
63         LinAl::SquareMatrix<double, 3> i = LinAl::invert(m);
64         EXPECT(is_identity(i*m));
65 }