Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a double is equal to -0.00

I am making this big program in C, which is a part of my homework. My problem is that my program is outputing x = -0.00 instead of x = 0.00. I have tried comparing like if(x==-0.00) x=fabs(x) but I've read that it won't work like that with doubles. So my question is are there any other ways to check if double is equal to negative zero?

like image 541
Kenan Hatibović Avatar asked Nov 06 '18 14:11

Kenan Hatibović


2 Answers

You can use the standard macro signbit(arg) from math.h. It will return nonzero value if arg is negative and ​0​ otherwise.

From the man page:

signbit() is a generic macro which can work on all real floating- point types. It returns a nonzero value if the value of x has its sign bit set.

This is not the same as x < 0.0, because IEEE 754 floating point allows zero to be signed. The comparison -0.0 < 0.0 is false, but signbit(-0.0) will return a nonzero value.

NaNs and infinities have a sign bit.

Also, from cppreference.com:

This macro detects the sign bit of zeroes, infinities, and NaNs. Along with copysign, this macro is one of the only two portable ways to examine the sign of a NaN.

like image 74
Giovanni Cerretani Avatar answered Sep 27 '22 15:09

Giovanni Cerretani


Very few calculations actually give you a signed negative zero. What you're probably observing is a negative value close to zero that has been truncated by your formatting choice when outputting the value.

Note that -0.0 is defined to be equal to 0.0, so a simple comparison to 0.0 is enough to verify a signed zero.

If you want to convert an exact signed zero -0.0 to 0.0 then add 0.0 to it.

like image 31
Bathsheba Avatar answered Sep 27 '22 16:09

Bathsheba