Compare Eigen matrices in Google Test or Google Mock

杀马特。学长 韩版系。学妹 提交于 2019-12-03 13:45:31

Why not use the isApprox or isMuchSmallerThan member functions of Eigen Matrix types?

The documentation of these above functions are available here

So for most cases ASSERT_TRUE(C_actual.isApprox(C_expect)); is what you need. You can also provide a precision parameter as the second arguement to isApprox.

A simplified solution would be to compare the norm of the difference with some epsilon, i.e.

(C_expect - C_actual).norm() < 1e-6 

In a vector space || X - Y || == 0 if and only if X == Y, and the norm is always non-negative (real). This way, you won't have to manually do the loop and compare element-wise (of course the norm will perform more calculations in the background than simple element-wise comparisons)

PS: the Matrix::norm() implemented in Eigen is the Frobenius norm, which is computationally very fast to evaluate, see http://mathworld.wolfram.com/FrobeniusNorm.html

EXPECT_PRED2 from GoogleTest can be used for this.

Under C++11 using a lambda works fine but looks unseemly:

  ASSERT_PRED2([](const MatrixXf &lhs, const MatrixXf &rhs) {
                  return lhs.isApprox(rhs, 1e-4);
               },
               C_expect, C_actual);

If that fails, you get a print-out of the input arguments.

Instead of using a lambda, a normal predicate function can be defined like this:

bool MatrixEquality(const MatrixXf &lhs, const MatrixXf &rhs) {
  return lhs.isApprox(rhs, 1e-4);
}

TEST(Eigen, MatrixMultiplication) {
  ...

  ASSERT_PRED2(MatrixEquality, C_expected, C_actual);
}

The later version also works on pre-C++11.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!