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

10 points by gus_massa a day ago

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?
sparkie a day ago

It depends on the FP rounding mode. If rounding mode is FE_TOWARDZERO/FE_UPWARD/FE_TONEAREST 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/5qvqsdh9P

  • gus_massa 35 minutes ago

    Thanks! [Sorry for the delay.]

    ---

    FYI: For more context, I'm trying to send a PR to Chez Scheme (and indirectly to Racket) https://github.com/cisco/ChezScheme/pull/959 to reduce expressions like

      (+ 1.0 (length L))  ;  ==>  (+ 1.0 (fixnum->flonum (length L)))
    
    where the "fixnums" are small integers and "flonums" are double.

    It's fine, unless you have the case

      (+ -0.0 (length L))  ;  =wrong=>  (+ -0.0 (fixnum->flonum (length L)))
    
    because if the length is 0, it get's transformed into 0.0 instead of -0.0

    There are a few corner cases, in particular because it's possible to have

       (+ 1.0 x (length L))
    
    and I really want to avoid the runtime check of (length L) == 0 if possible.

    So I took a look, asked there, and now your opinion confirms what I got so far. My C is not very good, so it's nice to have a example of how the rounding directions are used. Luckily Chez Scheme only uses the default rounding and it's probably correct to cut a few corners. I'll take a looks for a few days in case there is some surprise.

kazinator a day ago

What happens if we take the smallest (as in closest to zero) negative subnormal and add it to itself?

gethly 12 hours ago

i would guess that because of how *** * floats are in binary computers, you have something like -0.0000000000000000000000000000000000001 and when you round it you end up with -0.0. Same goes for positive value, you're just not used to write the + sign before every number, so seeing the minus feels strange.

  • dcminter an hour ago

    You're answering a question that OP did not ask.