Distinguish zero and negative zero

流过昼夜 提交于 2019-11-26 22:04:49

问题


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
}


来源:https://stackoverflow.com/questions/20946566/distinguish-zero-and-negative-zero

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!