Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Kotlin considers negative zero less than positive zero

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.

like image 927
Abdallah Alaraby Avatar asked Feb 04 '18 15:02

Abdallah Alaraby


People also ask

Is there a difference between positive and negative zero?

In ordinary arithmetic, the number 0 does not have a sign, so that −0, +0 and 0 are identical.

Why does JavaScript have negative zero?

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.

Does negative zero exist?

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.

Does Java have negative zero?

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.


1 Answers

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.

like image 196
hotkey Avatar answered Oct 13 '22 01:10

hotkey