c++floating-pointieee-754negative-zero

What is (+0)+(-0) by IEEE floating point standard?


Am I right that any arithmetic operation on any floating numbers is unambiguously defined by IEEE floating point standard? If yes, just for curiosity, what is (+0)+(-0)? And is there a way to check such things in practice, in C++ or other commonly used programming language?


Solution

  • The IEEE 754 rules of arithmetic for signed zeros state that +0.0 + -0.0 depends on the rounding mode. In the default rounding mode, it will be +0.0. When rounding towards -∞, it will be -0.0.

    You can check this in C++ like so:

    #include <iostream>
    
    int main() {
        std::cout << "+0.0 + +0.0 == " << +0.0 + +0.0 << std::endl;
        std::cout << "+0.0 + -0.0 == " << +0.0 + -0.0 << std::endl;
        std::cout << "-0.0 + +0.0 == " << -0.0 + +0.0 << std::endl;
        std::cout << "-0.0 + -0.0 == " << -0.0 + -0.0 << std::endl;
        return 0;
    }
    

    Output:

    +0.0 + +0.0 == 0
    +0.0 + -0.0 == 0
    -0.0 + +0.0 == 0
    -0.0 + -0.0 == -0