Question

#include <iostream>
using namespace std;

int main()
{
    double u = 0;
    double w = -u;
    cout << w << endl;
    return 0;
}

Why does this great piece of code output -0 and not 0, as one would expect?

Was it helpful?

Solution

The IEEE 754 standard for floating-point numbers has the sign bit separate from the mantissa, which allows for zero to be negative. Wikipedia should be able to help explain this.

OTHER TIPS

In IEEE floating point 0 and -0 are both distinct values, from here under "Special Values":

Note that -0 and +0 are distinct values, though they both compare as equal.

The IEEE 754 standard for floating point arithmetic makes a distinction between +0 and -0, this can be used when dealing with very small numbers rounded to zero where the sign still has an importance.

Because "negative zero" is a valid number!

http://en.wikipedia.org/wiki/%E2%88%920_(number)

Take a look at this article: http://en.wikipedia.org/wiki/Floating_point. Note that there is a sign bit, even if the value is zero.

Because a double can indeed have values -0, +0, -infinity, +infinity and NaN, which can be a result of various interesting expressions, like 0/0.

Look here for more information.

Because your expectations are wrong.

IEEE requires that positive and negative zero be represented seperately.

That is what you're seeing here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top