Skip to content

Floating point printing should print shortest round-trip value #3197

Description

@brevzin

Description

Currently, Catch2 uses iostream with fixed precision for printing float and double. This is fine, until it's not. Consider comparing two doubles that are 1 ULP apart:

CHECK(5.000000000000001e-05 == 5e-05);

This fails with the amusingly unhelpful:

/app/example.cpp:4: FAILED:
  CHECK( 5.000000000000001e-05 == 5e-05 )
with expansion:
  0.00005 == 0.00005

I have to go through and change Catch::StringMaker<double>::precision to be at least 20 to see the difference, but really also exactly 20 to have sensible output. Here are different precision outputs, compared to the output we get with format (std::format / fmt::format / std::to_chars):

precision output
19 0.00005 == 0.00005
20 0.00005000000000000001 == 0.00005
21 0.000050000000000000009 == 0.000050000000000000002
fmt 5.000000000000001e-05 == 5e-05

The last line is just a lot better. I don't think there's even a set of options across iostreams/iomanip to give you this output.

Additional context

Out of the box std::to_chars would give this result. I don't know what the compiler requirements are for Catch2 to know whether that's a viable option. Otherwise, there's an increasing number of impressive floating point writing algorithms that you could just consume, e.g. zmij.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions