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