given the following code:
long l = 1234567890123;
double d = (double) l;
is the following expression guaranteed to be true?
l == (long) d
I should think no, because as numbers get larger, the gaps between two doubles grow beyond 1 and therefore the conversion back yields a different long value. In case the conversion does not take the value that’s greater than the long value, this might also happen earlier.
Is there a definitive answer to that?
Nope, absolutely not. There are plenty of
longvalues which aren’t exactly representable bydouble. In fact, that has to be the case, given that both types are represented in 64 bits, and there are obviously plenty ofdoublevalues which aren’t representable inlong(e.g. 0.5)Simple example (Java and then C#):
I observed something really strange when doing this though… in C#,
long.MaxValue“worked” in terms of printing False… whereas in Java, I had to useLong.MAX_VALUE - 1. My guess is that this is due to some inlining and 80-bit floating point operations in some cases… but it’s still odd 🙂