这两篇写的挺好。浮点数不能用==判断是否相等,但是>或者<可以。
https://blog.youkuaiyun.com/dodott/article/details/53410756
https://www.cnblogs.com/zhloong/p/java-float-number-compare.html
比如JDK中Float的compareTo方法是这样写的。
public static int compare(float f1, float f2) {
if (f1 < f2)
return -1; // Neither val is NaN, thisVal is smaller
if (f1 > f2)
return 1; // Neither val is NaN, thisVal is larger
// Cannot use floatToRawIntBits because of possibility of NaNs.
int thisBits = Float.floatToIntBits(f1);
int anotherBits = Float.floatToIntBits(f2);
return (thisBits == anotherBits ? 0 : // Values are equal
(thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN)
1)); // (0.0, -0.0) or (NaN, !NaN)
}
即使用Float或者Double的compare方法,有时也会产生错误。比如下边的代码我们期望结果相等,但不是:
对于浮点数,我们无法使用==或者包装类型的equals()来精确比较。例如:
// 对f1执行11次加0.1的操作
float f1 = 0.0f;
for (int i = 0; i < 11; i++) {
f1 += 0.1f;
}
// f2是0.1*11的结果
float f2 = 0.1f * 11;
System.out.println(f1 == f2); // 结果为false
执行上述代码,会得到二者不相等,同时如果打印f1和f2,会得到如下结果:
f1 = 1.1000001
f2 = 1.1
本文探讨了浮点数比较的问题,指出直接使用==进行比较可能导致错误结果。通过具体示例展示了即使数学上相等的浮点数,在计算机内部表示可能产生细微差别,导致比较不等。介绍了Java中Float类的compareTo方法实现,并给出了一个典型错误示例。
1457

被折叠的 条评论
为什么被折叠?



