Forums Register Login

Long.MAX_VALUE and double conversion

+Pie Number of slices to send: Send
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?
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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 ]
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
thank you very much
Something about .... going for a swim. With this tiny ad ...
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 2262 times.
Similar Threads
pls help on NaN
${25/5} output 5.0 why not 5?
Is this Console reading Code poor?
ques
double call by reference?
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 15:26:33.