Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare vectors approximately in Eigen?

Is there a function in Eigen to compare vectors (matrices) using both relative and absolute tolerance aka numpy.allclose? Standard isApprox fails if one of the vectors is very close to zero.

like image 733
DikobrAz Avatar asked Feb 24 '13 11:02

DikobrAz


2 Answers

There is no built-in function implementing numpy.allclose, but you easily write one yourself if that's really what you need. However, I'd rather suggest the use of isMuchSmallerThan with reference value:

(a-b).isMuchSmallerThan(ref)

where ref is a representative non zero for your problem.

EDIT: for reference here is a possible implementation of allclose:

template<typename DerivedA, typename DerivedB>
bool allclose(const Eigen::DenseBase<DerivedA>& a,
              const Eigen::DenseBase<DerivedB>& b,
              const typename DerivedA::RealScalar& rtol
                  = Eigen::NumTraits<typename DerivedA::RealScalar>::dummy_precision(),
              const typename DerivedA::RealScalar& atol
                  = Eigen::NumTraits<typename DerivedA::RealScalar>::epsilon())
{
  return ((a.derived() - b.derived()).array().abs()
          <= (atol + rtol * b.derived().array().abs())).all();
}
like image 176
ggael Avatar answered Oct 12 '22 22:10

ggael


There is also isApprox function which was not working for me. I am just using ( expect - res).norm() < some small number.

like image 25
nnrales Avatar answered Oct 12 '22 22:10

nnrales