I've just started learning Kotlin and I came across a weird sentence in the documentation of basic types:
-0.0 is considered less than 0.0
I understand that their values will not be the same in ones' complement, but I don't know how it might be used in code.
The primary purpose of the erased floating point comparison not following the IEEE 754 standard is, when you use floating point numbers in collections and as keys for sorting, you don't want the values that are equal according to the standard to mix with each other. For example, you don't want to mix -0.0
and 0.0
as keys in a map (you might want two different values for these keys).
Likewise, you want a map to match a NaN
with itself, despite the standard stating that NaN
!= NaN
.
And, when you sort a set of items, you want a NaN
to be properly ordered with other numbers, even though the standard says it's incomparable with other elements (following the standard here might even break the sorting algorithm).
Note that these rules only apply when the objects are not statically known to belong to the floating point types, which, practically, matches the generic use cases and collections. The mathematical use cases, on contrary, usually operate with the numeric types directly (not erasing them to Any
or a type parameter) and, accordingly, the IEEE 754 rules are applied.