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?
问题:
回答1:
Call std::signbit()
to determine the state of the sign bit.
回答2:
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.
回答3:
To test explicitly for a == -0 in C do the following:
if (*((long *)&a) == 0x8000000000000000) { // a is -0 }