浮点数的比较
来源网站:http://blog.sina.com.cn/s/blog_53a8498d0101a6cd.html
来源博客:螃蟹的博客
浮点数的精度和有效位影响比较的正确性,如:
#include <iostream>
using namespace std;
int main()
{
float f1 = 7.123456789;
float f2 = 7.123456785;
if ( f1==f2 ) cout<<"f1 equal to f2\n";
double d1 = 7.123456789;
double d2 = 7.123456785;
if ( d1!=d2 ) cout<<"d1 not equal to d2\n";
float f = 1.0/3.0;
double d = 1.0/3.0;
if ( f!=d ) cout<<"f not equal to d\n";
return 0;
return 0;
}
结果为:
f1 equal to f2
d1 not equal to d2
f not equal to d
由于十进制单精度浮点数的有效位数为7,两个前7位相等而后面不同的数有可能在计算机中表示为同一个浮点数,因为float表示的精度有限而不能分辨出其差异,这就是错误的根源。如果要分辨,则应该用表示能力更强的数据类型double或long double来表示这两个数。
提倡使用double,因为对于浮点数的运算在计算机内部也是先转换为double进行处理。
浮点数计算的近似性使精确性比较失败,如:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double d1 = 123456789.9*9;
double d2 = 1111111109.1;
cout<<"d1="<<d1<<" d2="<<d2<<endl;
if ( d1!=d2 ) cout<<"精确比较:d1 and d2 , Not same \n";
else cout <<"Same\n";
if ( abs(d1-d2)<1e-5 ) cout <<"近似比较:d1 and d2 , Same\n" ;
else cout <<"d1 and d2 , Not same\n";
return 0;
}
结果为:
使用浮点数进行相等(==)和不相等(!=)比较时的操作通常是有问题的。浮点数的相等比较,一般总是使用两者相减的值是否落在0的领域中来判断。
来源网站:http://blog.csdn.net/shandongdaya/article/details/8608568
来源博客:shandongdaya的专栏
今天看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))
浙公网安备 33010602011771号