4

What is the canonical way to compare to approximate zeros in Catch2?

I found this way given a tolerance of 1e-12, but it is not clear it is the best way:

TEST("a approx. equal to b", "[test]"){
    REQUIRE( a - b == (0_a).margin(1e-12) );
}

I am not asking how to compare floats in general. I know that is not a simple problem. I am asking how to use Catch2 given a certain tolerance known in advance.

What follows didn't work, because relative (epsilon) errors do not behave well near zero:

TEST("a approx. equal to b", "[test]"){
    REQUIRE( a - b == (0_a).epsilon(1e-5) );
}

Other possible (not so nice)( alternatives seem to be

TEST("a approx. equal to b", "[test]"){
    REQUIRE( std::abs( a - b ) < 1e-12 );
}
TEST("a approx. equal to b", "[test]"){
    REQUIRE_THAT( a - b, WithinULP(0., ???));
}
TEST("a approx. equal to b", "[test]"){
    REQUIRE_THAT( a, WithinULP(b, ???));
}
alfC
  • 14,261
  • 4
  • 67
  • 118

2 Answers2

8
(a == Approx(b).margin(1e-12))

From the Catch2 GitHub

Das_Geek
  • 2,775
  • 7
  • 20
  • 26
RaviStrs
  • 574
  • 5
  • 9
1

Catch is now recommending matchers, rather than approx. Like:

REQUIRE_THAT(a, WithinAbs(b, 1e-12));

mzed
  • 61
  • 2