3

I have a C++ code where I sometimes get very small double numbers and after rounding they become either +0 or -0. Is it guaranteed that -0 will always behave like normal zero in comparisons? For example, see this code:

#include <iostream>
#include <cmath>

int main() {

    double accum = 0;
    for (int step = 0; step < 32; ++step) {
        double result = .1 * step - accum;
        accum += .1;

        result = round(result * 1e8) * 1e-8;

        std::cout << result << " ";
        if (result < 0) {
            std::cout << "< 0";
        }
        else if (result == 0) {
            std::cout << "== 0";
        }
        else {
            std::cout << "> 0";
        }
        std::cout << "\n";
    }
    return 0;
}

If I run it online it always says that -0 is equal to 0 as seen here.

The question is, is it guaranteed to behave like this on any computer?

spiderface
  • 1,025
  • 2
  • 11
  • 16
  • 1
    [" in computing, some number representations allow for the existence of two zeros ... regarded as equal by the numerical comparison operations"](https://en.wikipedia.org/wiki/Signed_zero) – BoBTFish Mar 29 '17 at 07:30
  • So does IEEE 754 specify the behavior in comparisons? – spiderface Mar 29 '17 at 07:42
  • 3
    @spiderface If the computer and compiler is IEEE compliant, comparison should be OK. Note that some operations differ, i.e. some operations on the extended real line are defined, and e.g. 1/-0 = -infinity, while 1/+0=+infinity. See https://en.wikipedia.org/wiki/Signed_zero – Erik Alapää Mar 29 '17 at 07:47
  • 1
    A very interesting publication about floating point arithmetic is http://www.lsi.upc.edu/~robert/teaching/master/material/p5-goldberg.pdf. and i would suggest to avoid direct comparison between floating point numbers of any kind. – Fryz Mar 29 '17 at 12:59

0 Answers0