负零(-0.0)与正零(+0.0)相比的行为 [英] Behaviour of negative zero (-0.0) in comparison with positive zero (+0.0)

查看:1137
本文介绍了负零(-0.0)与正零(+0.0)相比的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,

  float f = -0.0; //负数

负零比较

  f == -0.0f 



结果将会是 true



但是

  float f = 0.0; //正数

负零相比较

  f == -0.0f 

结果也是 true 而不是 false



=http://coliru.stacked-crooked.com/a/4962a3b70d76a260 =nofollow noreferrer>一个MCVE来测试它(live coliru):

  #include< iostream> 

int main()
{
float f = -0.0;

std :: cout<<====><< f< std :: endl< std :: endl;

if(f == -0.0f)
{
std :: cout<<true<< std :: endl;
}
else
{
std :: cout<<false<< std :: endl;




输出: p>

  ====> -0 //这里打印负零



$ div class =h2_lin>解决方案

C ++中的浮点运算通常是 IEEE-754 。这个标准与实数集合的数学定义不同。 为零值定义了两个不同的表示:正零和负零。这也是定义,这两个表示必须比较等于,所以定义:

  +0.0 == -0.0 

至于为何如此,请在


在IEEE算术中,定义log 0 =-∞和log x当x <1时是一个NaN是自然的。假设x表示一个下溢到零的小负数。由于签名为零,x将是负数,所以日志可以返回一个NaN。但是,如果没有有符号零,日志函数不能区分下溢负数和0,因此必须返回-∞。


In my code,

float f = -0.0; // Negative 

and compared with negative zero

f == -0.0f

result will be true.

But

float f = 0.0; // Positive

and compared with negative zero

f == -0.0f

also, result will be true instead of false

Why in both cases result to be true?


Here is a MCVE to test it (live on coliru):

#include <iostream>

int main()
{
    float f = -0.0;

    std::cout<<"==== > " << f <<std::endl<<std::endl;

    if(f == -0.0f)
    {
        std::cout<<"true"<<std::endl;
    }
    else
    {
        std::cout<<"false"<<std::endl;
    }
}

Output:

==== > -0  // Here print negative zero

true

解决方案

Floating point arithmetic in C++ is often IEEE-754. This norm differs from the mathematical definition of the real number set.

This norm defines two different representations for the value zero: positive zero and negative zero. It is also defined that those two representations must compare equals, so by definition:

+0.0 == -0.0

As to why it is so, in its paper What Every Computer Scientist Should Know About Floating Point Arithmetic, David Goldberg, 1991-03 (linked in the IEEE-754 page on the IEEE website) writes:

In IEEE arithmetic, it is natural to define log 0 = -∞ and log x to be a NaN when x < 0. Suppose that x represents a small negative number that has underflowed to zero. Thanks to signed zero, x will be negative, so log can return a NaN. However, if there were no signed zero, the log function could not distinguish an underflowed negative number from 0, and would therefore have to return -∞.

这篇关于负零(-0.0)与正零(+0.0)相比的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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