Reputation: 5423
I wanted to test if infinity is equal to infinity in Java:
Double.POSITIVE_INFINITY == Double.POSITIVE_INFINITY
I was surprised by the result when it turned out to be true. My question is how can two infinite values be equal?
Upvotes: 1
Views: 2570
Reputation: 140544
Because Double.POSITIVE_INFINITY
represents a specific number, so comparing it to itself using ==
should return true.
This behaviour is specified explicitly in JLS Sec 15.21.1:
Floating-point equality testing is performed in accordance with the rules of the IEEE 754 standard:
...
Otherwise, two distinct floating-point values are considered unequal by the equality operators.
In particular, there is one value representing positive infinity and one value representing negative infinity; each compares equal only to itself, and each compares unequal to all other values.
Upvotes: 8