how should I compare Double value with Long.MAX_VALUE? and Long.MAX_VALUE+1d

不问归期 提交于 2021-02-10 06:56:15

问题


I want to compare two double value as follow:

Double doubleValue = Double.valueOf(Long.MAX_VALUE);

Double doubleValue2 = Double.valueOf(Long.MAX_VALUE+1d);

Apparently doubleValue and doubleValu2 are not equal, 2nd is larger due to the 1d addition.

but no matter I use compare() or equals() method, both methods return a equal result for two values. Is there any way I can compare and not losing accuracy here.

thanks in advance.


回答1:


This is because of the loss of precision while converting long to double

    double d1 = (double)Long.MAX_VALUE;
    double d2 = Long.MAX_VALUE + 1.0;
    System.out.println(d1);
    System.out.println(d2);

it gives the same numbers

9.223372036854776E18
9.223372036854776E18

long has 32 bits and double's significand has 53 bits http://en.wikipedia.org/wiki/Double-precision_floating-point_format. In decimal terms, max long = 9223372036854775807, it is 19 digits, and double can hold 17 max




回答2:


Long.MAX_VALUE has 63 significant bits. A double cannot exactly represent any number with more than 53 significant bits. If you want to do exact calculations with integers bigger than Long.MAX_VALUE I suggest using java.math.BigInteger.

import java.math.BigInteger;

public class Test {
  public static void main(String[] args) {
    BigInteger longMax = BigInteger.valueOf(Long.MAX_VALUE);
    BigInteger plusOne = longMax.add(BigInteger.ONE);
    System.out.println(longMax.equals(plusOne));
  }
}


来源:https://stackoverflow.com/questions/14189298/how-should-i-compare-double-value-with-long-max-value-and-long-max-value1d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!