eigen2_inverse.cpp revision c981c48f5bc9aefeffc0bcb0cc3934c2fae179dd
1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra. Eigen itself is part of the KDE project.
3//
4// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>
5// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
6//
7// This Source Code Form is subject to the terms of the Mozilla
8// Public License v. 2.0. If a copy of the MPL was not distributed
9// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
10
11#include "main.h"
12#include <Eigen/LU>
13
14template<typename MatrixType> void inverse(const MatrixType& m)
15{
16  /* this test covers the following files:
17     Inverse.h
18  */
19  int rows = m.rows();
20  int cols = m.cols();
21
22  typedef typename MatrixType::Scalar Scalar;
23  typedef typename NumTraits<Scalar>::Real RealScalar;
24  typedef Matrix<Scalar, MatrixType::ColsAtCompileTime, 1> VectorType;
25
26  MatrixType m1 = MatrixType::Random(rows, cols),
27             m2(rows, cols),
28             mzero = MatrixType::Zero(rows, cols),
29             identity = MatrixType::Identity(rows, rows);
30
31  while(ei_abs(m1.determinant()) < RealScalar(0.1) && rows <= 8)
32  {
33    m1 = MatrixType::Random(rows, cols);
34  }
35
36  m2 = m1.inverse();
37  VERIFY_IS_APPROX(m1, m2.inverse() );
38
39  m1.computeInverse(&m2);
40  VERIFY_IS_APPROX(m1, m2.inverse() );
41
42  VERIFY_IS_APPROX((Scalar(2)*m2).inverse(), m2.inverse()*Scalar(0.5));
43
44  VERIFY_IS_APPROX(identity, m1.inverse() * m1 );
45  VERIFY_IS_APPROX(identity, m1 * m1.inverse() );
46
47  VERIFY_IS_APPROX(m1, m1.inverse().inverse() );
48
49  // since for the general case we implement separately row-major and col-major, test that
50  VERIFY_IS_APPROX(m1.transpose().inverse(), m1.inverse().transpose());
51}
52
53void test_eigen2_inverse()
54{
55  for(int i = 0; i < g_repeat; i++) {
56    CALL_SUBTEST_1( inverse(Matrix<double,1,1>()) );
57    CALL_SUBTEST_2( inverse(Matrix2d()) );
58    CALL_SUBTEST_3( inverse(Matrix3f()) );
59    CALL_SUBTEST_4( inverse(Matrix4f()) );
60    CALL_SUBTEST_5( inverse(MatrixXf(8,8)) );
61    CALL_SUBTEST_6( inverse(MatrixXcd(7,7)) );
62  }
63}
64