programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Long.MAX_VALUE and double conversion

Ulas Ergin
Ranch Hand
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
Sheriff
Posts: 24217
38
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.

Ulas Ergin
Ranch Hand
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
Sheriff
Posts: 24217
38
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
Posts: 77
thank you very much