Re: What is the behaviour of double / float primitive == comparison?
Endre Stølsvik <[email protected]>
| Newsgroups | gmane.comp.windows.devel.java.advanced |
|---|---|
| Message-ID | <[email protected]> |
Carfield Yim wrote:
>> The == comparison will return true if the actual bits are the same.
...
>>
> This is very useful, in fact I have read the equals() method of
> java.lang.Double but I don't know if double primitive do this
> samething.
The deal here is that Double's should be able to _compare_ against
eachother. For example when you stash them into a TreeSet() (which is a
SortedSet)..
Then you have the 'NaN' - Not a Number. For NaN's, you have "NaN == NaN
-> FALSE". (Thus, a way to check for NaN is 'x != x' - if that
comparison is TRUE, then x is a NaN!).
So, it wouldn't do very good for a TreeSet if a Double representing a
NaN was inserted into the Set, but didn't compare to _anything_ - where
should it be inserted?
That's why Double.compareTo() does a bit of logic to make sure that
every type of number actually gets some sort order against any other
type of number.
Double's implementation of equals() should however be consistent with
Double's implemenation of Comparable.compareTo(). And this is what's
happening with the equal-method you saw.
So - actually - what I stated in my first reply ("The == comparison will
return true if the actual bits are the same") is only correct for actual
numbers: when you ==-compare a NaN against some other NaN you get FALSE,
not true as you would have with gotten with an exact "bit comparison".
The latter is what "equals" implement.
PS: Also, IEEE defines a NaN as a number having the exponent bits all
set to 1, while the significand having /some/ non-zero number - which
implies that there are "rather many" different bit patterns that encode
a NaN (However, even a NaN with the exact same bits as another NaN won't
==-compare to true).
The doubleToRawLongBits give you the raw stuff, preserving the exact
bit pattern, including any NaN. The doubleToLongBits collapse any NaN to
one specific (canonical) bit pattern (0x7ff8000000000000L - the "purest"
"non-signalling NaN"). That method actually invokes the
doubleToRawLongBits, and then checks for the exponent being all 1s, and
the significand being != 0. If this isn't so (it is an actual number),
it returns the result, otherwise it returns the canonical NaN
representation..
Kind regards,
Endre.
===================================
This list is hosted by DevelopMentor® http://www.develop.com
View archives and manage your subscription(s) at http://discuss.develop.com