10

I have run into a situation in my code where a function returns a double, and it is possible for this double to be a zero, a negative zero, or another value entirely. I need to distinguish between zero and negative zero, but the default double comparison does not. Due to the format of doubles, C++ does not allow for comparison of doubles using bitwise operators, so I am unsure how to procede. How can I distinguish between the two?

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
Dan Brenner
  • 880
  • 10
  • 23

3 Answers3

18

Call std::signbit() to determine the state of the sign bit.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
9

Due to the format of doubles, C++ does not allow for comparison of doubles using bitwise operators, so I am unsure how to procede.

First off, C++ doesn't mandate any standard for float/double types.

Assuming you're talking about IEEE 754's binary32 and binary64 formats, they're specifically designed to maintain their order when their bit patterns are interpreted as integers so that a non-FPU can sort them; this is the reason they have a biased exponent.

There're many SO posts discussing such comparisons; here's the most relevant one. A simple check would be

bool is_negative_zero(float val)
{
   return ((val == 0.0f) && std::signbit(val));
}

This works since 0.0f == -0.0f, although there're places where the sign makes a difference like atan2 or when dividing by -0 as opposed to +0 leads to the respective infinities.

Community
  • 1
  • 1
legends2k
  • 31,634
  • 25
  • 118
  • 222
-3

To test explicitly for a == -0 in C do the following:

if (*((long *)&a) == 0x8000000000000000) {
    //  a is -0
}
user113670
  • 29
  • 3
  • 2
    ... if (_and only if_) you know the platform uses IEC 60559 representation in that endianness, and if `long` is the same size as `double` ... – Toby Speight Aug 08 '19 at 17:49