8

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.

3 Answers 3

13

I'd suggest

if (a == T(0)) ...
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for the solution itself, but I wish the answer had the explanation of the others!
7

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.

7 Comments

Thanks. What about other constant values?
@Agnel: Non-integral constant values? Don't use floating-point equality tests then.
You are right. I would use an epsilon. But even then the question remains: do I use a float literal or a double literal?
@Agnel: A double, unless the literal can be exactly expressed as a float. You can still force compile-time conversion to T using static_cast (or the constructor notation shown by @Alexandre).
According to the promotion rules for numeric types, 0 will get promoted to the type of the floating-point operand a. How does the compiler handle cases involving a cast like in (float)a * 100. As casts have precedence, what type does it promote for 100 here?
|
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.