c++linear-algebraeigen

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.


Solution

  • 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();
    }