您的位置:首页 > 其它

浮点数到底能不能用 == 进行比较

2013-02-25 11:46 211 查看
今天看c语言,遇到一个问题,浮点类型能不能用 == 进行比较,其实这个问题以前也碰到过,在面试的时候,只知道尽量不要使用 == 对浮点数进行比较。那么为什么呢,计算机中的计算不是确定的么?

首先我们要了解浮点数在计算机中怎么存放的。《深入理解计算机系统》中这样说过,浮点数普遍的作为实数运算的近似值的计算,是很有用的。这里说的是实数的近似值的计算,所以浮点数在计算机中其实是一种不精确的表示。它存在舍入(rounding)误差。IEEE浮点标准用符号,尾数和阶码将浮点数的位表示划分为三个字段,单精度为32位,双精度为64位,因为表示方法限制了浮点数的范围和精度,浮点运算只能近似的表示实数运算。而 == 表示的是在计算机中的内存表示完全一样,这样使用
== 来表示两个浮点数的相等就会出现问题了,比如下面的例子:

when can I use operator '==' to compare two float?

Whenever you want.

A better questsion is "Why shouldn't I use == to compare floats?". The

answer is: rounding. If you're comparing values that are the result of a

mathematical expression that "should" be equal, there's a very good chance

that they won't be.

float x = 1.0f;

float y = 1.0f / 3;

if (3f * y == x)

{

// this code will likely never run

}

On the other hand, if you've assigned a value from one variable of type

float to another variable of type float, then you can safely compare them

for equality:

float x = 1.0f / 3.0f;

float y = x;

if (x == y)

{

// this code will always run

}

Of course, this is an unusual situation - the normal recommendation is to

never compare floats to equality: compare for an acceptably small difference

in value:

if (fabs(x-y) < 0.00001)

{

// ... this will reliably execute when x and y are "equal"

}

上面给出的例子的意思是在数学表达式中,不能用 == 来表示浮点数和一个结果为浮点数的数学表达式相等。

其实我们在判断两个浮点数是否相等时,最好不要用 == 来判断,要使用上面 的最后一个的判断方法,即判断一下这两个数的绝对值,即在数轴上的距离是否小于某个精度。

c++中判断一个浮点数是否为0是通过下面的方法来实现的。

const float EPSINON = 0.000001;

if ((x >= - EPSINON) && (x <= EPSINON))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: