Reputation: 5120
The sun jdk implementation looks like this:
return v != v;
Can anyone explain how that works?
Upvotes: 8
Views: 5303
Reputation: 89729
A nan is the only double that is not equal to itself. Thus, checking v!=v will only produce True for NaN.
Here is what the Java spec has to say:
Floating-point operators produce no exceptions (§11). An operation that overflows produces a signed infinity, an operation that underflows produces a denormalized value or a signed zero, and an operation that has no mathematically definite result produces NaN. All numeric operations with NaN as an operand produce NaN as a result. As has already been described, NaN is unordered, so a numeric comparison operation involving one or two NaNs returns false and any != comparison involving NaN returns true, including x!=x when x is NaN.
Upvotes: 4
Reputation: 175335
NaN values are not equal to anything (if one side of an equality is NaN, the equality is false), so NaN != NaN. Obviously every normal double does equal itself
Upvotes: 13