本征库:计算逆时静态和动态大小矩阵之间的不同行为

Eigen Library : Different behaviors between static and dynamic size matrices when computing inverse

我在计算小 float 矩阵的逆时遇到了 Eigen 库的一些奇怪行为。我发现对静态和动态矩阵大小使用相同数据之间存在意想不到的差异。

更令人惊讶的是,与我使用 double 矩阵得到的结果相比,似乎只有动态版本才能提供令人满意的结果。

那么我在这里错过了什么?这是否意味着我应该在所有情况下都使用动态版本?就是不对。

这是一个代码示例,使用 Visual Studio 2012,发布,x64 编译。

#include <iostream>
#include <Eigen/Dense>

int main()
{
    //some static size 4x3 matrix
    Eigen::Matrix<float,4,3> m;
    m <<
        -166.863f,  -172.49f,   -172.49f,
        107.422f,   101.71f,    107.422f,
        708.306f,   706.599f,   708.029f,
        1.0f,       1.0f,       1.0f ;

    //same but dynamic size
    Eigen::MatrixXf mx = m;

    //first result
    std::cout << (m.transpose()*m).inverse()  << std::endl << std::endl ;
    /*
        0.00490293 0.000445721 -0.00533875
        0.000445721  0.00502179  -0.0054378
        -0.00533875  -0.0054378   0.0107567
    */

    //second result, completely different from the first one
    std::cout << (mx.transpose()*mx).inverse() << std::endl << std::endl ;
    /*
        0.0328157 0.00291519 -0.0356753
        0.00287851  0.0337197  -0.036493
        -0.0356387 -0.0365297  0.0720099
    */

    //third result, same as the second one, only small differences due to better accuracy
    std::cout << (m.transpose()*m).cast<double>().inverse() << std::endl << std::endl ;
    /*
        0.032961 0.00297425 -0.0358793
        0.00297425  0.0337394 -0.0366082
        -0.0358793 -0.0366082  0.0723284
    */

    //the condition number of the inversed matrix is quite huge if that matters : 175918
    Eigen::JacobiSVD<Eigen::MatrixXf> svdF(m.transpose()*m);
    std::cout << svdF.singularValues()(0) / svdF.singularValues()(svdF.singularValues().size()-1) << std::endl;
}

如 Eigen 所述,inverse 对小型固定矩阵(最多 4x4)使用不同的算法。

对于小的固定矩阵,Eigen 使用 cofactors 方法(Cramers 规则)。该方法基于行列式的计算,行列式是通过减去乘积计算得出的。对于高条件数 and/or 低浮点精度,您会获得高相对误差。

对于其他矩阵,Eigen使用Partial Pivoting LU分解,比cofactors方法更稳定。