double类型判断是否相等

背景

使用了“==”和“!=”来判断duble类型,使用sonar等代码规范扫描会报如下错误:Floating point math is imprecise because of the challenges of storing such values in a binary representation. Even worse, floating point math is not associative; push a float or a double through a series of simple mathematical operations and the answer will be different based on the order of those operation because of the rounding that takes place at each step.

原因

duble类型只可以判断大小,不可以判断是否相等,这样会失去精度,使判断没有意义。

解决方案

为两个duble类型的值设置误差,通过判断大小来判断是否相等,代码演示如下:

public static void main(String[] args) {

        double preErrorKey=1e-6; //1*10的-6次方即0.000001
        double key1=0.0000001d;
        double key2=0d;
        System.out.println(key1==key2); //结果是flase
        System.out.println(Math.abs(key1-key2)<preErrorKey);    //允许一定的误差范围,判断结果为true
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值