Search code examples
c++floating-pointfloating-accuracyfloating-point-precisiondivide-by-zero

Division by zero prevention: Checking the divisor's expression doesn't result in zero vs. checking the divisor isn't zero?


Is division by zero possible in the following case due to the floating point error in the subtraction?

float x, y, z;
...
if (y != 1.0)
    z = x / (y - 1.0);

In other words, is the following any safer?

float divisor = y - 1.0;
if (divisor != 0.0)
    z = x / divisor;

Solution

  • This will prevent you from dividing by exactly zero, however that does not mean still won't end up with +/-inf as a result. The denominator could still be small enough so that the answer is not representable with a double and you will end up with an inf. For example:

    #include <iostream>
    #include <limits>
    
    int main(int argc, char const *argv[])
    {
        double small = std::numeric_limits<double>::epsilon();
        double large = std::numeric_limits<double>::max() / small;
        std::cout << "small: " << small << std::endl;
        std::cout << "large: " << large << std::endl;
        return 0;
    }
    

    In this program small is non-zero, but it is so small that large exceeds the range of double and is inf.