对于任何有限的浮点值,是否保证x - x == 0? [英] For any finite floating point value, is it guaranteed that x - x == 0?

查看:188
本文介绍了对于任何有限的浮点值,是否保证x - x == 0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

浮点数的值是不精确的,这就是为什么我们应该很少使用严格的数值相等的原因比较。例如,在Java中,打印 false 在ideone.com上看到):

  System.out.println(.1 + .2 == .3); 
// false

通常,比较浮点运算结果的正确方法是看如果对一些预期值的绝对差异小于一些容忍的 epsilon

$ b.b

  System.out.println(Math.abs(.1 + .2  -  .3)< .00000000000001); 
// true

问题是关于是否 操作可以产生确切的结果。我们知道,对于任何非有限浮点值 x (即 NaN 或无穷大), x - x ALWAYS NaN



但是如果 x 是有限的,这是有保证的吗?


  1. x * -1 == -x

  2. x - x == 0




(特别是我对Java的行为最感兴趣,但也欢迎其他语言的讨论。)






我认为(我可能在这里错了)答案是肯定的!我认为它归结为是否有任何有限的浮点值,其有限的浮点值加法倒数是al方式可以精确计算。由于例如 float double has 一个专用位仅仅用于符号,这似乎是这种情况,因为它只需要翻转符号位以找到加法逆(即有效数字应该保持不变)。


$ b

h3>


虽然 x - x 可能会给你 -0 而不是真正的 0 -0 比较a s等于 0 ,所以你可以放心,假设任何有限数的减号本身都会比较为零。



请参阅有没有x的浮点值,其中xx == 0是false?了解更多详情。


Floating point values are inexact, which is why we should rarely use strict numerical equality in comparisons. For example, in Java this prints false (as seen on ideone.com):

System.out.println(.1 + .2 == .3);
// false

Usually the correct way to compare results of floating point calculations is to see if the absolute difference against some expected value is less than some tolerated epsilon.

System.out.println(Math.abs(.1 + .2 - .3) < .00000000000001);
// true

The question is about whether or not some operations can yield exact result. We know that for any non-finite floating point value x (i.e. either NaN or an infinity), x - x is ALWAYS NaN.

But if x is finite, is any of this guaranteed?

  1. x * -1 == -x
  2. x - x == 0

(In particular I'm most interested in Java behavior, but discussions for other languages are also welcome.)


For what it's worth, I think (and I may be wrong here) the answer is YES! I think it boils down to whether or not for any finite IEEE-754 floating point value, its additive inverse is always computable exactly. Since e.g. float and double has one dedicated bit just for the sign, this seems to be the case, since it only needs flipping of the sign bit to find the additive inverse (i.e. the significand should be left intact).

Related questions

解决方案

Although x - x may give you -0 rather than true 0, -0 compares as equal to 0, so you will be safe with your assumption that any finite number minus itself will compare equal to zero.

See Is there a floating point value of x, for which x-x == 0 is false? for more details.

这篇关于对于任何有限的浮点值,是否保证x - x == 0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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