什么是一个标准的方法来比较float与零?

问题描述:

可能的问题是:什么是一个标准的方法来比较float与零?

May question is: What is a standard way to compare float with zero?

据我所知直接比较:

if ( x == 0 ) { 
  // x is zero?
} else {
  // x is not zero??

可能会出现浮点变量。

我以前使用

float x = ...
...
if ( std::abs(x) <= 1e-7f ) { 
  // x is zero, do the job1
} else {
 // x is not zero, do the job2
...

相同的方法我发现这里。但我看到两个问题:

Same approach I find here. But I see two problems:


  1. 随机幻数1e-7f(或上方链接的0.00005)。

  2. 代码更难阅读

这是一个常见的比较,我想知道是否有一个标准的短途这个。喜欢

This is such a common comparison, I wonder whether there is a standard short way to do this. Like

 x.is_zero();


要将浮点值与0进行比较,比较:

To compare a floating-point value with 0, just compare it:

if (f == 0)
    // whatever

这个比较没有错。如果它不做你期望的,因为 f 的值不是你想象的。它本质上是这样的问题:

There is nothing wrong with this comparison. If it doesn't do what you expect it's because the value of f is not what you thought it was. Its essentially the same problem as this:

int i = 1/3;
i *= 3;
if (i == 1)
    // whatever

没有错但是 i 的值不是1.几乎所有的程序员都理解整数值的精度损失;很多人不明白浮点值。

There's nothing wrong with that comparison, but the value of i is not 1. Almost all programmers understand the loss of precision with integer values; many don't understand it with floating-point values.

使用几乎相等而不是 == 先进技术;它经常导致意想不到的问题。例如,它不是传递性的;即 a 几乎等于 b b c c> 表示 a $ c>几乎等于 c

Using "nearly equal" instead of == is an advanced technique; it often leads to unexpected problems. For example, it is not transitive; that is, a nearly equals b and b nearly equals c does not mean that a nearly equals c.