Search code examples
floating-pointieee-754

Floating-point number multiplication: a * 1.0 == a guaranteed?


Say a is a floating-point number. Is a * 1.0 == a always guaranteed?


Solution

  • Yes. The only exception is when a is NaN where NaN * 1.0 = NaN by definition, but NaN doesn't compare equal to itself. But even then, you can argue it's the same result on both sides. However, the NaN payload might be different, if that's something you care about, which can make a difference if your system distinguishes between quiet and signaling NaNs.

    The general rule of FP arithmetic says the result should be computed as if you have infinite precision, and then rounded (if necessary) using the given rounding mode to fit the final format. Since a is a representable float, the mathematical result of multiplying it by 1.0 precisely gives us a when interpreted as an infinitely precise number. No rounding is necessary, since a is already representable. So, you're guaranteed that a * 1.0 == a, except for the degenerate NaN case as discussed.