How to use floating point tolerances in the Catch framework?

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?


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).

Source : Link , Question Author : R. Martinho Fernandes , Answer Author : R. Martinho Fernandes

Leave a Comment