HACKER Q&A
📣 gus_massa

How is it possible to get -0.0 in a sum?


I'm looking for corner cases where he result is -0.0. As far as I know, the only way to get -0.0 in a sum is

  (-0.0) + (-0.0)
Does someone know any other case in IEEE 754?

Bonus question: What happens in subtractions? I only know

  (-0.0) - (+0.0)
Is there any other case?


  👤 jjgreen Accepted Answer ✓

  irb(main):005> -0.0 * +0.0
  => -0.0

👤 sparkie
It depends on the FP rounding mode. If rounding mode is FE_TOWARDZERO then the case you gave is the only one I'm aware of. If rounding mode is FE_DOWNWARD (towards negative infinity) then other calculations that result in a zero will give a -0.0.

Here's an example of -1.0f + 1.0f resulting in -0.0: https://godbolt.org/z/KPh7W6zjW


👤 kazinator
[delayed]