浮动有一个负零? (-0f) [英] Does float have a negative zero? (-0f)

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

问题描述

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



这个问题的启发是另一个问题,你是否可以安全地比较 0.0f 使用 == ,我进一步想知道是否还有其他的方法来表示零

请没有评论比较花车平等的安全性!我不是想把这个溢出来的重复问题加进去。 根据标准,负零存在,但它等于正零。几乎所有的目的,这两者的行为方式相同,许多人认为负面的存在是一个实施细节。然而,有一些函数的表现完全不同,即除法和 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 \ n,1 / x,1 / y,1 / x == 1 / y);
printf(%.08f ==%.08f:%d \\\
,atan2(x,y)atan2(y,y)atan2(x,y)== atan2(y,y ));



$ b $ p

这段代码的结果是:

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

这将意味着代码将正确处理某些限制而不需要明确的处理。不确定的是,依靠这个特性来接近极限的值是一个好主意,因为一个简单的计算错误可以改变符号,使得这个值远远不正确,但是如果避免计算,那么仍然可以利用它改变标志。


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?

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.

[Edit] Please, do not comment about the safety of comparing floats for equality! I am not trying to add to that overflowing bucket of duplicate questions.

解决方案

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\n", x, y, x == y);
    printf("%.08f == %.08f: %d\n", 1 / x, 1 / y, 1 / x == 1 / y);
    printf("%.08f == %.08f: %d\n", atan2(x, y), atan2(y, y), atan2(x, y) == atan2(y, y));
}

The result from this code is:

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天全站免登陆