alfC
alfC

Reputation: 16270

What is the canonical way to check for approximate zeros in Catch2?

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, ???));
}

Upvotes: 4

Views: 1571

Answers (2)

mzed
mzed

Reputation: 61

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

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

Upvotes: 1

RaviStrs
RaviStrs

Reputation: 624

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

From the Catch2 GitHub

Upvotes: 8

Related Questions