当比较两个浮点数或双精浮点数的数值时,只能使用判断差值的是否在精度允许的范围内的方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
public class { public static final double PRECISIOND = 0.0000000000000001; public static final double PRECISIONF = 0.0000001; public static void main(String[] args) { double d1 = 0.1; double d2 = 1-0.9; float f = 0.1f; System.out.println("d1 == d2 : " + (d1 == d2)); System.out.println("Double.compare(d1,d2) : " + Double.compare(d1, d2)); System.out.println("new Double(d1).compareTo(d2) : " + new Double(d1).compareTo(d2)); System.out.println("d1 == f : " + (d1 == f)); if(Math.abs(d1-d2) < PRECISIOND) System.out.println("Math.abs(d1-d2) < PRECISION : d1 == d2"); if(Math.abs(d1-f) < PRECISIONF) System.out.println("Math.abs(d1-f) < PRECISION : d1 == f"); } }
输出: d1 == d2 : false Double.compare(d1,d2) : 1 new Double(d1).compareTo(d2) : 1 Math.abs(d1-d2) < PRECISION : d1 == d2 d1 == f : false Math.abs(d1-f) < PRECISION : d1 == f
|
近期评论