Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double value as a negative zero

Tags:

c

I have a program example:

int main()
{
    double x;
    x=-0.000000;
    if(x<0)
    {
        printf("x is less");
    }
    else 
    {
        printf("x is greater");
    }
}

Why does the control goes in the first statement - x is less . What is -0.000000?

like image 846
james Avatar asked Mar 19 '26 17:03

james


1 Answers

IEEE 754 defines a standard floating point numbers, which is very commonly used. You can see its structure here:

Finite numbers, which may be either base 2 (binary) or base 10 (decimal). Each finite number is described by three integers: s = a sign (zero or one), c = a significand (or 'coefficient'), q = an exponent. The numerical value of a finite number is

  (−1)^s × c × bq

where b is the base (2 or 10). For example, if the sign is 1 (indicating negative), the significand is 12345, the exponent is −3, and the base is 10, then the value of the number is −12.345.

Double FP number

So if the fraction is 0, and the sign is 0, you have +0.0.
And if the fraction is 0, and the sign is 1, you have -0.0.

The numbers have the same value, but they differ in the positive/negative check. This means, for instance, that if:

x = +0.0;
y = -0.0;

Then you should see:

(x -y) == 0

However, for x, the OP's code would go with "x is greater", while for y, it would go with "x is less".

Edit: Artur's answer and Jeffrey Sax's comment to this answer clarify that the difference in the test for x < 0 in the OP's question is actually a compiler optimization, and that actually the test for x < 0 for both positive and negative 0 should always be false.

like image 187
Nathan Fellman Avatar answered Mar 22 '26 10:03

Nathan Fellman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!