Doubles and zero/negative zero

  • Thread starter Christopher Benson-Manica
  • Start date
C

Christopher Benson-Manica

How does one determine whether a double is equal to -0.0000...? Will
fabs() from math.h return 0.000... on -0.0000...?
 
P

P.J. Plauger

How does one determine whether a double is equal to -0.0000...?

You have to use a C99 function such as signbit or copysign to
see the sign bit, because -0 == +0.
Will
fabs() from math.h return 0.000... on -0.0000...?

That's what you get with IEEE conformance, but otherwise all bets
are off.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
 
N

Neil Kurzman

Christopher said:
How does one determine whether a double is equal to -0.0000...? Will
fabs() from math.h return 0.000... on -0.0000...?

One way would be:

if( (Number < 0) &&( Number > -0.00001))
You get to figure out how many zeros work for you
 
W

Walter

Neil Kurzman said:
One way would be:

if( (Number < 0) &&( Number > -0.00001))
You get to figure out how many zeros work for you

That won't work, since (Number<0) will be false for Number=-0. The -0
floating point bit pattern is all 0 bits except the sign bit, which is
turned on. The only time the sign of zero matters is when determining which
side of 0 you're on if you're on a singularity at 0 (called a branch cut).
The IEEE floating point arithmetic routines carefully keep track of -0's,
but to test for it you'll need to check directly for the sign bit, which is
easy enough with:

#include <math.h>

if (signbit(x)) ...

fabs, if implemented correctly, will convert -0 to 0.

Here's a brief introduction to IEEE arithmetic:
www.digitalmars.com/ctg/ctgNumerics.html

Here are some math functions, and what they do with -0:
www.digitalmars.com/rtl/math.html

-Walter
www.digitalmars.com free C/C++/D compilers
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top