I'm somewhat familiar with the issues around performing floating point equality comparisons in code.
Currently the code base I'm compiling on (GCC, Clang) have the following option enabled: -Wfloat-equal
And in the code base there's the following example comparison:
template <typename FloatType>
void foo(FloatType v) {
if (v == FloatType(1)) {
...
}
else if (v == FloatType(0)) {
....
}
}
The foo function is invoked as follows:
double d = 123.98;
float f = 123.98f;
foo(d);
foo(f);
Given the special case of 1 and 0 which each have exact representations in floating points (double, float) and where the code is clearly after an exact equality and not something that is close by some minor difference -
Is there a way to rewrite the code such that it will not raise the associated Wfloat-equal diagnostic and will also be portable and support both float and double types?
How about using std::equal_to
. As far as GCC is concerned it will disable a whole bunch of checks when processing the system headers including the float-equal
template <typename FloatType>
void foo(FloatType v) {
if (std::equal_to<FloatType>()(v,FloatType(1))) {
...
}
else if (std::equal_to<FloatType>()(v,FloatType(0))) {
....
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With