Search code examples
c++floating-pointfloating-accuracy

Float comparison with zero-initialised value in C++


Is it safe to use the '==' operator to determine if a double variable in C++ has changed since its initialization to 0.0?

For performance reasons I want to avoid re-calcuation of a value inside a nested for-loop if it has been already calculated.

If it is considered unsafe: Can this lead to false positives (i.e. the expression returns true although the value does not equal 0.0), false negatives (i.e. the expression returns false although the values is indeed 0.0) or both/undetermined behaviour?

I am using C++-14 and the GNU C++ compiler v5.4.


Solution

  • In C++, the expression x == 0. evaluates to true if and only if x is zero.

    The only senses in which you could have a false positive or false negative are:

    • x is the result of calculations that produced zero when the ideal exact mathematical result would be non-zero or vice-versa. In other words, the problem is that x does not contain the value you want, not that comparing with zero does not work properly.
    • Rather than a simple object x, the comparison uses a floating-point expression, as in x/y == 0.. C++ allows expressions to be evaluated with more precision than the nominal type. This excess precision is discarded when the value is assigned or converted by a cast. So the comparison could indicate the expression is non-zero even though assigning it to an object would produce zero in the object.