Is floating point multiplication by zero guaranteed to produce zero?

前端 未结 2 1196
天命终不由人
天命终不由人 2021-01-01 17:10

I understand floating point has rounding errors, but I\'m wondering if there are certain situations where the error does not apply, such as multiplication by zero .

相关标签:
2条回答
  • 2021-01-01 17:40

    False:

    0f * NAN == NAN
    0f * INFINITY == NAN
    

    and ...

    0f * -1f == -0f (negative 0f), with 0f == -0f :-)
    

    (on Intel, VC++, and probably on any platform that uses IEEE 754-1985 floating points)

    Example on ideone (that uses GCC on some Intel compatible platform probably)

    0 讨论(0)
  • 2021-01-01 17:48

    In addition to @xanatos fine answer, consider some of OP's middle-of-the-post concerns:

    I'm wondering if there are certain situations where the (rounding) error does not apply

    Candidates include some_double_y = some_double_x * 1.0 and some_double_y = some_double_x + 0.0 may never incur a rounding error.

    Yet even those are suspect due to a compiler may evaluate double at higher precision considering the FLT_EVAL_METHOD == 2 where "evaluate all operations and constants to the range and precision of the long double type." In that case, an intermediate some_double_x may exist as a long double differing from an apparent double value of 0.0 or 1.0.

    0 讨论(0)
提交回复
热议问题