Is it safe to test float for equal 0.0?

I know it is dangerous to test float for equality due to precision errors, but is it safe to test zero? I can think of some cases, for example, when optimizing special cases in algorithms where you would like to do this. The question is about float, but I would suggest that the answer also applies to doubling.

Consider the following code:

float factor = calculateFactor(); if(factor != 0.0f) applyComplexAlgorithm(factor); 
+7
source share
3 answers

This is safe in the sense that if a value is explicitly specified in 0.0f, it will return true.

This is NOT safe in the sense that you should not expect that the value obtained from the calculations will be equal to 0.0f.

So you really use 0.0f as a special magic value, and not as a real comparison with zero.

+8
source

No, this is not safe, because the calculation in calculateFactor() will probably not lead to 0.0, even through this arithmetic. Trivial example: (0.4-0.1) -0.3, when done using double , leads to 5.551115123125783e-17

+5
source

This is certainly safe, but you need to consider what this means for your algorithms. If your algorithm uses factor as a divisor (and does not check its division by zero), then yes, it is reasonable to check factor != 0.0f before calling applyComplexAlgorithm(factor) .

Now, whether you need to check a value smaller than any epsilon before using factor depends entirely on what your code means and cannot be determined separately from the code you provided.

If (as you noted in another comment), you want to use the special value 0.0f as a sentinel value, which means something specific (for example, the inability to calculate the coefficient), then yes, it is absolutely safe to compare using == . For example, the following use of the 0.0f code is deterministic and never undergoes any rounding error:

 float calculateFactor() { int phase = moon_phase(); if (phase == FULL) { // whatever special case requires returning 0.0f return 0.0f; } else { return 1.0 + (phase * phase); // something that is never 0.0f } } float factor = calculateFactor(); if(factor != 0.0f) applyComplexAlgorithm(factor); 
+3
source

All Articles