问题描述
class Test{
public static void main(String[] args){
float f1=3.2f;
float f2=6.5f;
if(f1==3.2){
System.out.println("same");
}else{
System.out.println("different");
}
if(f2==6.5){
System.out.println("same");
}else{
System.out.println("different");
}
}
}
输出:
different
same
为什么是这样的输出?我希望 same
与第一种情况的结果相同.
Why is the output like that? I expected same
as the result in first case.
推荐答案
不同的是,6.5 可以用 float 和 double 精确表示,而 3.2 不能用任何一种类型精确表示.并且两个最接近的近似值是不同的.
The difference is that 6.5 can be represented exactly in both float and double, whereas 3.2 can't be represented exactly in either type. and the two closest approximations are different.
float 和 double 之间的相等比较首先将 float 转换为 double,然后比较两者.所以数据丢失.
An equality comparison between float and double first converts the float to a double and then compares the two. So the data loss.
您永远不应该比较浮点数或双精度数是否相等;因为您不能真正保证分配给 float 或 double 的数字是准确的.
You shouldn't ever compare floats or doubles for equality; because you can't really guarantee that the number you assign to the float or double is exact.
这种舍入误差是浮点计算的一个特征.
将无限多个实数压缩为有限位数需要一个近似的表示.虽然有无限许多整数,在大多数程序中整数计算的结果可以以 32 位存储.
Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation. Although there are infinitely many integers, in most programs the result of integer computations can be stored in 32 bits.
相反,给定任意固定位数,大多数实数计算将产生的数量不能用那么多位精确表示.因此浮点计算的结果通常必须按顺序四舍五入以适应其有限的表示.这个舍入误差是浮点计算的特征.
In contrast, given any fixed number of bits, most calculations with real numbers will produce quantities that cannot be exactly represented using that many bits. Therefore the result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is the characteristic feature of floating-point computation.
查看每个计算机科学家都应该了解的浮点运算知识更多!
这篇关于为什么在 Java 中比较浮点数不一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!