什么是一个标准的方法来比较float与零? [英] What is a standard way to compare float with zero?

查看:151
本文介绍了什么是一个标准的方法来比较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 表示 a 几乎等于 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.

这篇关于什么是一个标准的方法来比较float与零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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