cfloating-pointequalityglibassertion

How do I use g_assert_cmpfloat () to check if two floats are equal without generating a safety warning?


I'm writing some testcases for a program using the GLib testing facilities. I want to assert that two floats have the same value, and g_assert_cmpfloat () seemed like an appropriate function for that. I used it like so:

g_assert_cmpfloat (10.0f, ==, 10.0f);

(obviously with the constant values replaced with the actual values I'm checking equivalence for, but this is simpler and reproduces the issue)

The project I'm adding the testcases to is using -Wfloat-equal, which sensibly warns about the problems with comparing floats like this. But it makes me wonder, how am I supposed to assert that two floats are equal using this function then? I don't want to use g_assert_true () since that won't log the actual values of the two floats. I've seen the answers to Compare two floats, but I'm not sure how I implement them while still using this function.

For context, the testcase ensures that a string representation such as "4.25" gets properly converted to the equivalent floating point value properly.

How can I use g_assert_cmpfloat () with -Wfloat-equal to assert that two floats are equal without generating a compiler warning?


Solution

  • I want to assert that two floats have the same value, and g_assert_cmpfloat () seemed like an appropriate function for that. I used it like so:

    g_assert_cmpfloat (10.0f, ==, 10.0f);
    

    ... which asserts exact equality of two floating-point values.

    The project I'm adding the testcases to is using -Wfloat-equal, which sensibly warns about the problems with comparing floats like this.

    Sensibly indeed. There are special cases for which testing exact equality of FP values makes sense, but generally speaking, tests for exact FP equality are extremely sensitive to computational and implementation details, and exact equality is rarely what you really require anyway. So don't do that.

    How can I use g_assert_cmpfloat () with -Wfloat-equal to assert that two floats are equal without generating a compiler warning?

    You can't. Macros expand to ordinary code. In any case that satisfies that description, the macro expands to code that involves an == comparison of two FP values, which will trigger a warning. If you don't want that, then you need to choose a different kind of comparison.

    You could make two uses of g_assert_cmpfloat () with different operators (from among <, <=, >, >=) to perform an approximate equality test, but as long as you're looking at GLib's assertion macros, I guess you have overlooked g_assert_cmpfloat_with_epsilon(), which provides for that type of bounded approximate equality test with a single macro invocation.