Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing a floating point to one or zero with Wfloat-equal option

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?

like image 330
Karena D. Avatar asked Oct 17 '22 13:10

Karena D.


1 Answers

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))) {
   ....
  }
}
like image 151
Martein Txz Avatar answered Oct 21 '22 07:10

Martein Txz