Search code examples
ieee-754

Can multiplication of non-zero floats yield exactly zero?


Suppose I have a series of small random floating point numbers in either double or float format which are guaranteed to be non-zero, in a CPU which follows the IEEE754 standard, and I make multiplications between two of these small numbers.

If both numbers are different from zero but very small (below machine epsilon), is it possible that a multiplication result would yield zero or negative zero, such that if I interpret the result as a C++ boolean, it would translate into false?


Solution

  • Yes. You can demonstrate that by experiment:

    #include <stdio.h>
    
    int main()
    {
        float x = 0.1 ;
        int it = 0 ;
        
        while( x *= x )
        {
            it++ ;
            printf( "%d %f\n", it, x ) ;
        }
    
        return 0;
    }
    

    Outputs:

    1 0.010000                                                                                                                                                                                    
    2 0.000100                                                                                                                                                                                    
    3 0.000000                                                                                                                                                                                    
    4 0.000000                                                                                                                                                                                    
    5 0.000000 
    

    The fact that the loop terminates, indicates that x is zero and implicitly casts to false.

    The test runs for 8 iterations for double, and 12 for long double on Linux.

    The result is the same for while( -(x *= x) ) - to address the part of your question referring to negative-zero.