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?
g_assert_cmpfloat_with_epsilon(), with a suitable epsilon.equalityfor floats to allow eg +/- 2 ULP or you will likely find too many false mismatches where working numbers meant to be identical are ever so slightly different in the last few bits of the mantissa. Fora,bcheck that at least one of them,bisn't zero andassert ( abs(1 - a/b), <, N*machine_eps)for your chosen tolerance ofNULP. Some similar helper functions may already exist on your platform.a >= b && a <= b?