How to use floating point tolerances in the Catch framework?

R. Martinho Fernandes picture R. Martinho Fernandes · Jul 16, 2011 · Viewed 7.1k times · Source

I'm using the Catch test framework.

In the introductory blog post the author mentions the following feature:

  • Floating point tolerances supported in an easy to use way

I couldn't find any documentation on how to do this. How is this done in Catch?

Answer

R. Martinho Fernandes picture R. Martinho Fernandes · Jul 16, 2011

It's simple. There is a class called Approx that lets you do this test in a very readable manner:

#include <limits>
TEST_CASE("demo/approx", "Approx demo") {
    double a = 1.0;
    double b = a + std::numeric_limits<double>::epsilon();
    REQUIRE_FALSE(b == a);
    REQUIRE(b == Approx(a));
}

The tolerance can be changed by using the member functions epsilon() and scale() of the Approx object, like so: Approx(a).epsilon(e).