Search code examples
c#ieee-754

Could x * y == y when x != 1 and y != 0?


If x and y are IEEE 754 floating point numbers (single or double precision), could we ever have

x * y == y

where x != 1 and y != 0 (and nor is y equal to +inf, -inf, or nan).


Solution

  • Yes; this might happen when you get near to extreme small factors and/or denormal numbers.

    Example:

    float x = 1.0000001f;
    float y = 0.00000000000000000000000000000000000000001f;
    Console.WriteLine("x: " + x);
    Console.WriteLine("y: " + y);
    Console.WriteLine(x * y == y);
    Console.WriteLine("x*y: " + (x * y));
    

    yields

    x: 1.0000001
    y: 1E-41
    True
    x*y: 1E-41
    

    (dotnetfiddle with .NET Core 3.1)

    All numbers are well-defined, but the multiplication cannot be carried out at this precision.

    Fun fact: Running the same with .NET Framework 4.7.2 yields the following:

    x: 1
    y: 9.999666E-42
    False
    x*y: 9.999666E-42
    

    (dotnetfiddle with .NET Framework 4.7.2)

    So, the implementations behave differently for very small numbers.