aspose file tools
The moose likes Java in General and the fly likes Long.MAX_VALUE and double conversion Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Long.MAX_VALUE and double conversion" Watch "Long.MAX_VALUE and double conversion" New topic
Author

Long.MAX_VALUE and double conversion

Ulas Ergin
Ranch Hand

Joined: Oct 10, 2002
Posts: 77
The below code segment

long l1 = Long.MAX_VALUE;
double d1 = (double)l1;
double d2 = (double)l1;
long l2 = (long)d1;
d2=d2-1;
System.out.println(d2==d1);
System.out.println(d2<d1);

produces:

true
false

but why?

initially d1 and d2 are equal but on the fifth line I substract 1 from d2,
but they are still same, is this a bug?
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24057
    
  13

No, not a bug. Floating point types like double have a large range, but only finite precision. Whereas longs can only represent values from (roughly) plus or minus 2 billion, doubles can represent values between plus and minus 10^308 -- hundreds of orders of magnitude larger. But to get that range, you have to sacrifice precision. Whereas in a long, all 64 bits are dedicated to representing the exact value, in a double, nine bits or so are held aside to represent the exponent, and the rest hold the "mantissa", the specific value. So as it turns out, as far as double is concerned, Long.MAX_VALUE and Long.MAX_VALUE + 1 are identical.


[Jess in Action][AskingGoodQuestions]
Ulas Ergin
Ranch Hand

Joined: Oct 10, 2002
Posts: 77
I understand that Long.MAX_VALUE and Long.MAX_VALUE+1 are identical for long values but that is not my case.


I am subtracting 1 from its double counterpart.

And regarding the precision, long is 32 bits and double is 64 bits (1 bit sign,11 bits exponent and 52 bits fraction)

so since 52 bits is more that 32 bits my example shouldn't have problems?
[ May 13, 2005: Message edited by: Ulas Ergin ]
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24057
    
  13

Java longs and doubles are both 64 bits. 64 is more than 52.

The answer is the same for Long.MAX_VALUE+1 or MAX_VALUE-1 -- at the precision of a double, they're both identical to MAX_VALUE.
Ulas Ergin
Ranch Hand

Joined: Oct 10, 2002
Posts: 77
thank you very much
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Long.MAX_VALUE and double conversion
 
Similar Threads
ques
${25/5} output 5.0 why not 5?
pls help on NaN
Is this Console reading Code poor?
double call by reference?