• Java浮点类型与精度


    Java浮点类型与精度


    public static void main(String[] args) throws Exception {
        float a = 1.0f - 0.9f;
        float b = 0.9f - 0.8f;
        System.out.println(a == b);//false
    
        Float c = a;
        Float d = b;
        System.out.println(c.equals(d));//false
    
        System.out.println(a);//0.100000024
        System.out.println(b);//0.099999964
    }
    
    public static void main(String[] args) throws Exception {
        double a = 1.0 - 0.9;
        double b = 0.9 - 0.8;
        System.out.println(a == b);//true
    
        Double c = a;
        Double d = b;
        System.out.println(c.equals(d));//true
    
        System.out.println(a);//0.09999999999999998
        System.out.println(b);//0.09999999999999998
    }
    

    “浮点数之间的等值判断,基本数据类型不能用 == 来比较,包装数据类型不能用equals来判断。”

    ​ —— 《Java开发手册》

    浮点数值不适用于无法接收舍入误差的计算中。这种舍入误差的主要原因是浮点数采用二进制系统表示,而在二进制系统中无法精确地表示分数1/10,就好像十进制无法精确地表示分数1/3一样。

    解决办法

    1. 指定一个误差范围,两个浮点数的差值在此范围之内,才认为是相等的。
    public static void main(String[] args) throws Exception {
        float a = 1.0f - 0.9f;
        float b = 0.9f - 0.8f;
        float diff = 1e-6f;
        //absolute value
        System.out.println(Math.abs(a - b) < diff);//true
    }
    
    1. 使用BigDecimal 来定义值,再进行浮点数的运算操作。
    public static void main(String[] args) throws Exception {
        BigDecimal a = BigDecimal.valueOf(1.0);
        BigDecimal b = BigDecimal.valueOf(0.9);
        BigDecimal c = BigDecimal.valueOf(0.8);
        
        BigDecimal x = a.subtract(b);
        BigDecimal y = b.subtract(c);
        System.out.println(x.equals(y));//true
        
        System.out.println(x);//0.1
        System.out.println(y);//0.1
    }
    
  • 相关阅读:
    一次线上遇到磁盘IO瓶颈的问题处理
    修改mysql错误日志级别
    binlog_format日志错误
    mysql重启遇到的问题
    Mysql两张表的关联字段不一致
    多线程中的join总结笔记
    java后端实习生面试题目
    javascript 中的 innerHTML 是什么意思
    为什么java实体类需要重写toString方法
    关于maven中的快照版本(snapshot)与正式版本(release)解析。
  • 原文地址:https://www.cnblogs.com/XiaoZhengYu/p/12844495.html
Copyright © 2020-2023  润新知