两个浮点数值相等比较

        因为浮点数的存储和计算都是近似的(详见IEEE754标准),所以我们不能简单地用"=="运算符来比较两个浮点数是否相等。

        我做了几组测试,发现有时能精确计算,有时不能。

        以Java环境为例:(1会被隐式转为1.0)

public class Test {
	public static void main(String[] args) {
		System.out.println(1 - 0.1 == 0.9);
	}
}

         第一个例子结果是true

          但是到了1 - 0.8 == 0.2 ;1 - 0.9 == 0.1就为false,计算一下1  - 0.9发现为0.09999999999999998。这种不确定性非常不好,我们需要一个万全之策:

            

public class Test {
	public static void main(String[] args) {
		final double EPSILON = 1E-14;
		System.out.println(Math.abs(1 - 0.8 - 0.2) < EPSILON);
	}
}

          带变量的版本:

   

public class Test {
	public static void main(String[] args) {
		final double EPSILON = 1E-14;
		double x = 1.0 - 0.9;
		double y = 0.1;
		System.out.println(x - y == 0);
		System.out.println(Math.abs(1 - 0.8 - 0.2) < EPSILON);
	}
}
                 解释一下:希腊字母"epsilon",中文读作伊普西龙,表示一个非常小的值,如果浮点数x, y满足|x - y| < ε,就可以认定x和y非常接近。一般取ε = 1 * 10 ^ -14。

你可能感兴趣的:(javaSE)