zoukankan      html  css  js  c++  java
  • 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
    }
    
  • 相关阅读:
    【九】纯配置版本的微服务
    Eclipse 项目导航字体设置 左侧树字体
    【八】Spring Cloud Config
    Lua Table 操作
    根据角度和距离生成游戏物体(以圆心向圆圈线上生成物体)
    Unity UI和引用的管理中心
    利用三角函数实现按钮上下漂浮
    DoTween学习笔记(二) UGUI结合使用(实现一些简单效果)
    DoTween学习笔记(一)
    人物角色群体攻击判定四(三角区域判断)
  • 原文地址:https://www.cnblogs.com/XiaoZhengYu/p/12844495.html
Copyright © 2011-2022 走看看