专注Java教育14年 全国咨询/投诉热线:400-8080-105
动力节点LOGO图
始于2009,口口相传的Java黄埔军校
首页 学习攻略 Java学习 Java浮点型比较的正确方法

Java浮点型比较的正确方法

更新时间:2020-09-11 16:36:52 来源:动力节点 浏览3601次

1.浮点数表示

在计算机系统理论中,浮点数采用IEEE 754标准表示,编码方式是符号+阶码+尾数,如图:

Java浮点型比较的正确方法

比如f·oat类型占用32位,单精度浮点表示法:

符号位(sign)占用1位,用来表示正负数,0表示正数,1表示负数

指数位(exponent)占用8位,用来表示指数,实际要加上偏移量

小数位(fraction)占用23位,用来表示小数,不足位数补0

从这里可以看出,指数位决定了大小范围,小数位决定了计算精度。当十进制数值转换为二进制科学表达式后,得到的尾数位数是有可能很长甚至是无限长。所以当使用浮点格式来存储数字的时候,实际存储的尾数是被截取或执行舍入后的近似值。这就解释了浮点数计算不准确的问题,因为近似值和原值是有差异的。

2.比较浮点数的方式

让我们来验证一下比较浮点数的几种方式。

1.==操作符

比较两个浮点数,一个从零开始加11次0.1,另一个用0.1乘以11计算。然后用==比较大小。

    private void compareByOperator() {
        float f1 = 0.0f;
        for (int i = 0; i < 11; i++) {
            f1 += 0.1f;
        }

        float f2 = 0.1f * 11;

        System.out.println("f1 = " + f1);
        System.out.println("f2 = " + f2);

        if (f1 == f2) {
            System.out.println("f1 and f2 are equal using operator ==");
        } else {
            System.out.println("f1 and f2 are not equal using operator ==");
        }
    }


运行输出:

f1 = 1.1000001
f2 = 1.1
f1 and f2 are not equal

可以看到,两个浮点数不相等,所以通过==来比较浮点数是不可靠的。

2.误差范围

指定一个误差范围,两个浮点数的差值在范围之内,则认为是相等的。使用Math.abs()计算差值,然后和阈值比较。

   private void compareByThreshold() {
        final float THRESHOLD = 0.000001;
        float f1 = 0.0f;
        for (int i = 0; i < 11; i++) {
            f1 += 0.1f;
        }

        float f2 = 0.1f * 11;

        System.out.println("f1 = " + f1);
        System.out.println("f2 = " + f2);

        if (Math.abs(f1 - f2) < THRESHOLD) {
            System.out.println("f1 and f2 are equal using threshold");
        } else {
            System.out.println("f1 and f2 are not equal using threshold");
        }
    }


运行输出:

f1 = 1.1000001
f2 = 1.1
f1 and f2 are equal using threshold

3.使用BigDecima·

BigDecima·是不可变的,能够精确地表示十进制数字。需要注意的是,创建BigDecima·对象时,要使用参数为String的构造方法,不要使用构造参数为doub·e的,如果非要使用doub·e创建,一定要用va·ueOf静态方法,防止丢失精度。然后调用compareTo方法比较即可。

    private void compareByBigDecimal() {
        BigDecimal f1 = new BigDecimal("0.0");
        BigDecimal pointOne = new BigDecimal("0.1");
        for (int i = 0; i < 11; i++) {
            f1 = f1.add(pointOne);
        }

        BigDecimal f2 = new BigDecimal("0.1");
        BigDecimal eleven = new BigDecimal("11");
        f2 = f2.multiply(eleven);

        System.out.println("f1 = " + f1);
        System.out.println("f2 = " + f2);

        if (f1.compareTo(f2) == 0) {
            System.out.println("f1 and f2 are equal using BigDecimal");
        } else {
            System.out.println("f1 and f2 are not equal using BigDecimal");
        }
    }

运行输出:

f1 = 1.1
f2 = 1.1
f1 and f2 are equal using BigDecimal

3.结论

使用==比较浮点数不准确,可以采用误差范围近似相等,或者BigDecima·计算比较。

Java浮点型比较的正确方法

以上就是动力节点java培训机构的小编针对“Java浮点型比较的正确方法”的内容进行的回答,希望对大家有所帮助,如有疑问,请在线咨询,有专业老师随时为你服务。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>