背景
使用了“==”和“!=”来判断duble类型,使用sonar等代码规范扫描会报如下错误:Floating point math is imprecise because of the challenges of storing such values in a binary representation. Even worse, floating point math is not associative; push a float or a double through a series of simple mathematical operations and the answer will be different based on the order of those operation because of the rounding that takes place at each step.
原因
duble类型只可以判断大小,不可以判断是否相等,这样会失去精度,使判断没有意义。
解决方案
为两个duble类型的值设置误差,通过判断大小来判断是否相等,代码演示如下:
public static void main(String[] args) {
double preErrorKey=1e-6; //1*10的-6次方即0.000001
double key1=0.0000001d;
double key2=0d;
System.out.println(key1==key2); //结果是flase
System.out.println(Math.abs(key1-key2)<preErrorKey); //允许一定的误差范围,判断结果为true
}
本文探讨了使用“==”和“!=”直接比较double类型数值可能导致的问题,由于浮点数运算的不精确性,直接比较可能导致误判。文章提供了一种解决方案:通过设定一个合理的误差范围来进行比较。

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



