浮点数是否为负零?(-0f) [英] Does float have a negative zero? (-0f)

查看:39
本文介绍了浮点数是否为负零?(-0f)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

IEEE 浮点数分配了一个位来指示符号,这意味着从技术上讲,您可以使用不同的二进制表示零(+0 和 -0).有没有我可以做的算术运算,例如在 C 中导致负零浮点值?

IEEE floating point numbers have a bit assigned to indicate the sign, which means you can technically have different binary representations of zero (+0 and -0). Is there an arithmetic operation I could do for example in C which result in a negative zero floating point value?

这个问题的灵感来自另一个问题,它质疑您是否可以使用 == 安全地比较 0.0f,我进一步想知道是否有其他方法来表示零会导致 float1 == 0.0f 打破看似完全相等的值.

This question is inspired by another which called into question whether you can safely compare 0.0f using ==, and I wondered further if there is are other ways to represent zero which would cause float1 == 0.0f to break for seemingly perfectly equal values.

请不要评论比较浮动是否相等的安全性!我并不是要添加到那堆满溢的重复问题中.

推荐答案

按照标准,负零存在,但等于正零.对于几乎所有目的,两者的行为方式相同,并且许多人认为否定的存在是实现细节.但是,有些函数的行为完全不同,即除法和 atan2:

According to the standard, negative zero exists but it is equal to positive zero. For almost all purposes, the two behave the same way and many consider the existence of a negative to be an implementation detail. There are, however, some functions that behave quite differently, namely division and atan2:

#include <math.h>
#include <stdio.h>

int main() {
    double x = 0.0;
    double y = -0.0;
    printf("%.08f == %.08f: %d
", x, y, x == y);
    printf("%.08f == %.08f: %d
", 1 / x, 1 / y, 1 / x == 1 / y);
    printf("%.08f == %.08f: %d
", atan2(x, y), atan2(y, y), atan2(x, y) == atan2(y, y));
}

这段代码的结果是:

0.00000000 == -0.00000000: 1
1.#INF0000 == -1.#INF0000: 0
3.14159265 == -3.14159265: 0

这意味着代码可以正确处理某些限制,而无需显式处理.对于接近极限的值依赖这个特性并不是一个好主意,因为一个简单的计算错误可能会改变符号并使值远离正确,但如果你避免计算,你仍然可以利用它换个牌子.

This would mean that code would correctly handle certain limits without a need for explicit handling. It's not certain that relying on this feature for values close to the limits is a good idea, since a simple calculation error can change the sign and make the value far from correct, but you can still take advantage of it if you avoid calculations that would change the sign.

这篇关于浮点数是否为负零?(-0f)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆