Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, ???));
}
like image 435
alfC Avatar asked Jan 26 '23 05:01

alfC


1 Answers

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

From the Catch2 GitHub

like image 50
RaviStrs Avatar answered Feb 16 '23 02:02

RaviStrs