原始双精度值是否等于幅值? [英] Primitive double value equal depends on magnitude?

查看:52
本文介绍了原始双精度值是否等于幅值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须检查两个双精度值是否相等,包括大小和精度.我遇到了一个奇怪的情况,即原始的double equals校验不一致,并且取决于值的大小.

I have to check to see whether two double values are equal including magnitude and precision. I encounter a weird scenario where primitive double equals check is not consistent and depend on magnitude of value.

我使用过的Java版本:

Java version i've used:

java version "1.6.0_26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03)
Java HotSpot(TM) Client VM (build 20.1-b02, mixed mode, sharing)

我的代码:

public class Test{
     public static void main(String args[]) throws Exception{
         String val1 = "15.999999999999999";
         String val2 = "16";
         String val3 = "16.999999999999999";
         String val4 = "17";
         double d1 = Double.parseDouble(val1);
         double d2 = Double.parseDouble(val2);
         double d3 = Double.parseDouble(val3);
         double d4 = Double.parseDouble(val4);
         System.out.println(val1 + "=" + val2 + "? ===>" + (d1==d2));
         System.out.println(val3 + "=" + val4 + "? ===>" + (d3==d4));
     }
}

输出:

15.999999999999999=16? ===>false
16.999999999999999=17? ===>true

推荐答案

由于各种无聊而又复杂的原因,您尝试执行的操作将无法正常工作,您可以在此处阅读以下内容:

What you're trying to do won't work for various boring and complicated reasons that you can read about here: http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html

除非您要比较双精度的位表示(可能比较有见或没有见识),否则始终需要某种epsilon值,即处理数字浮点表示时的误差余量.像这样:

Unless you're going to compare the bit-representation of the doubles (which may or may not be insightful), you will always need some sort of epsilon value, i.e. margin of error when dealing with floating-point representations of numbers. Something like:

boolean doublesAreEqual(double d1, double d2)
{
    double d = d1 / d2;
    return (Math.abs(d - 1.0) < 0.00001 /* epsilon */);
}

这篇关于原始双精度值是否等于幅值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆