当前位置:网站首页>Equivalent judgment between floating point numbers

Equivalent judgment between floating point numbers

2020-11-09 16:06:06 Game life

(1) Specify an error range , The difference between two floating-point numbers is in this range , It is considered equal .

float a = 1.0F - 0.9F;
float b = 0.9F - 0.8F;
float diff = 1e-6F;
if (Math.abs(a - b) < diff) {
 System.out.println("true");
}


(2) Use BigDecimal To define the value , And then the floating-point operation .

BigDecimal a = new BigDecimal("1.0");
BigDecimal b = new BigDecimal("0.9");
BigDecimal c = new BigDecimal("0.8");
BigDecimal x = a.subtract(b);
BigDecimal y = b.subtract(c);
if (x.compareTo(y) == 0) {
 System.out.println("true");
}


As shown above BigDecimal The equivalent comparison of should use compareTo() Method , instead of equals() Method .
explain :equals() Methods compare values and precision (1.0 And 1.00 The return result is false), and compareTo() Precision is ignored .


come from :Java Development Manual ( Song Mountain version )

版权声明
本文为[Game life]所创,转载请带上原文链接,感谢