Reply to topic

Handy way to check whether two VectorXd are close enough?

bravegag
Registered Member
Posts
50
Karma
0
I have needed this in the context of GoogleTest tests so I implemented it like a macro:

Code: Select all
/// Convenience macro to compare two VectorXd
#define EXPECT_VECTORXD_NEAR(first, second, epsilon) \
   ASSERT_EQ(first.rows(), second.rows()); \
   for (int i = 0; i < first.rows(); ++i) { \
      EXPECT_NEAR(first(i), second(i), epsilon); \
   }


but I also need something that simply returns true if two VectorXd are close element-wise to an epsilon. This would be a quick and dirty implementation:

Code: Select all
inline bool is_near(const VectorXd& first, const VectorXd& second, double epsilon) {
   bool result = first.rows() == second.rows();
   for (int i = 0; result && (i < first.rows()); ++i) {
      result = abs(first(i) - second(i)) < epsilon;
   }
   return result;
}


How can I do that in the most succint way?
User avatar ggael
Moderator
Posts
2740
Karma
17
OS
What about A.isApprox(B), though the comparison is not done the exact same way. See http://eigen.tuxfamily.org/dox/classEig ... 98db8e8966.

Your definition is equivalent to:
Code: Select all
((A-B).array().abs() < epsilon).all()

but that's assuming that the expected magnitudes of A and B elements are always the same.
bravegag
Registered Member
Posts
50
Karma
0
As usual :) thank you for the excellent support!

 
Reply to topic

Bookmarks



Who is online

Registered users: Baidu [Spider], Bing [Bot], davidemme, Exabot [Bot], Google [Bot], google01103, hftom, joaob, jstaniek, phd21, ralphl, rumangerst, sschwarzer, Vandalk, Yahoo [Bot]