Search code examples
c++eigen3

Why do I get the wrong answer when using eigen3 to inverse matrix


I'm using eigen3 to take the inverse of the matrix,but the inverse is wrong. I tried several examples,but the following this is wrong.

#include <iostream>
#include <Eigen/Dense>
using namespace Eigen;
using namespace std;
int main(){
    Matrix3d Mat1;
Mat1 << 99.999999999999972 ,-29024.672261149386 ,29024.848775176863,-29024.672261149386, 8629880.2300641891 ,-8629930.2299046051,29024.848775176863,-8629930.2299046051 , 8629980.2300641891 ;
cout << "Mat1=\n" << Mat1 << endl;
   Matrix3d Mat2=Mat1.inverse();
cout << "Mat1逆矩阵:\n" << Mat2 << endl;
cout << "Mat1*Mat2:\n" << Mat1*Mat2 << endl;
cout << "Mat2*Mat1:\n" << Mat2*Mat1 << endl;
cout << "Mat1行列式:\n" << Mat1.determinant() << endl;

the result is:
Mat1=
         100     -29024.7      29024.8
    -29024.7  8.62988e+06 -8.62993e+06
     29024.8 -8.62993e+06  8.62998e+06
Mat1逆矩阵:
    44.3313    -12557.7    -12557.8
   -12557.7 3.58199e+06 3.58201e+06
   -12557.8 3.58201e+06 3.58204e+06
Mat1*Mat2:
           1 -0.000198364  0.000823975
    -80.0958     0.785156    -0.242188
     80.0963   -0.0634151     0.972687
Mat2*Mat1:
           1     -80.0958      80.0963
-0.000198364     0.785156      -0.0625
 0.000818345    -0.243301     0.972687
Mat1行列式:
5.73875

Shouldn't mat1*mat2 be a unit matrix?


Solution

  • Try using pseudo-inverse instead. That problem maybe a precision issues as @paddy said.

    Got that code from here

    #include <Eigen/QR>    
    Eigen::MatrixXd A = ... // fill in A
    Eigen::MatrixXd pinv = A.completeOrthogonalDecomposition().pseudoInverse();
    

    My result:

    Mat3*Mat1:
           1  3.05176e-05 -3.05176e-05
           0            1   -0.0078125
     2.88524e-05   -0.0137121      1.00454
    Mat1*Mat3:
     1.00004   -0.0101929   -0.0101624
    -3.05176e-05      1.00781            0
     5.83113e-05   -0.0134087     0.996313