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.
In ordinary arithmetic, the number 0 does not have a sign, so that −0, +0 and 0 are identical.
It turns out the reason that JavaScript has -0 is because it is a part of the IEEE 754 floating-point specification. Two zeroes are also present in other languages like Ruby as well.
There's no such thing as negative zero. For a binary integer, setting the sign bit to 1 and all other bits to zero, you get the smallest negative value for that integer size. (Assuming signed numbers.) Negative zero is actually used in mathematical analysis, especially in limit calculations.
The mystery of negative zero (-0) in Java. Mathematically the number 0 does not have a sign, therefore -0, +0 and 0 are identical. We say that zero is neither positive nor negative. In computing numbers are stored in binary and there is concept of a sign bit.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With