Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Floating point constants in templated code

I have a template function operating on a floating point argument. The function is templated so that a caller can use either float, double or any other floating point data type.

At one point in my code, I compare a value with zero (or any other floating-point constant). Should I use 0.0 or 0.0f for the comparison?

template<T> void f(T a){
  //  should I use 0.0 or 0.0f in the following line?
  if(a == 0.0){
  }
}

While this is not causing any problems at the moment, I'd like to know what the usual practice is.

like image 878
Agnel Kurian Avatar asked May 28 '11 14:05

Agnel Kurian


3 Answers

I'd suggest

if (a == T(0)) ...
like image 94
Alexandre C. Avatar answered Nov 17 '22 08:11

Alexandre C.


I would suggest simply 0. According to the promotion rules for numeric types, 0 will get promoted to the type of the floating-point operand a. Promotion of a constant is a compile-time transformation, it won't slow your program down at all.


On the other hand, using 0.0 will force a run-time conversion of the other operand to double, which probably is a non-issue, as the operand is most likely passed in an FPU register anyway. 0.0f will not cause conversion of floating-point operands, but if the template was ever used with an integral type, you'd get run-time conversion to float.

like image 24
Ben Voigt Avatar answered Nov 17 '22 08:11

Ben Voigt


You should not compare for equality on floating point number with a simple

if (value == 0.0) // or 0.0f, doesn't matter

because most of the time it won't yield the result you are expecting. You should check if value is enough close to the number you are expecting. That is:

if (abs(value - 0.0) < epsilon) 

where epsilon is something little enough for you application domain.

like image 38
Simone Avatar answered Nov 17 '22 09:11

Simone