Catch2 icon indicating copy to clipboard operation
Catch2 copied to clipboard

Stringification of small numbers

Open hr87 opened this issue 4 years ago • 5 comments

If a test with small numbers fail, the output is not helpful. We get for example:

  CHECK( constants::electric == 8.8541878128e-12 )
with expansion:
  0.0 == 0.0

The output should fall back to exponential format for small numbers.

hr87 avatar May 27 '21 21:05 hr87

You can set precision of floating-point values (at present, only for float and double, not for long double, see #1731). Just add this in your test case:

Catch::StringMaker<float>::precision = 25;
Catch::StringMaker<double>::precision = 25;

Unfortunately, the std::fixed is hard coded, I don't see how the user could change that. But I agree, there should be a way to switch to std::scientific.

Also see SO related question: https://stackoverflow.com/questions/55867570/

skramm avatar Jun 04 '21 21:06 skramm

Hi! Thanks for the amazing work on Catch2!

But I agree, there should be a way to switch to std::scientific.

Is there any progress related to this? Thanks

weslleyspereira avatar Jun 17 '22 16:06 weslleyspereira

I offer freely the following change to fpToString

    ReusableStringStream rss;
    if (value != 0 && std::abs(value) < std::pow(T(.1),T(precision1))) {
        rss << std::scientific << value;
        return rss.str();
    }else{
        // previous code
        rss << std::setprecision( precision )
            << std::fixed
            << value;
    }

to anyone who has the time and inclination to usher the change into place.

The resulting error message is

somefile.cc:42: FAILED:
  REQUIRE( err < 1e-12 )
with expansion:
  2.725983e-14 < 1.000000e-18

vs. the inscrutable

somefile.cc:42: FAILED:
  REQUIRE( err < 1e-12 )
with expansion:
  0.0 < 0.0

mborgerding avatar Sep 16 '22 17:09 mborgerding

I can write a PR with @mborgerding's proposal if this is something the Catch2 team would be willing to merge.

weslleyspereira avatar Sep 25 '22 11:09 weslleyspereira

I edited the above proposed change to bypass the (not shown) trimming of trailing zeros in fpToString. Otherwise, something like REQUIRE(err < 1e-10) expands the last part to "1e-1" vs. "1e-10"

mborgerding avatar Sep 28 '22 16:09 mborgerding