Alex Kuznetsov
09/23/2024, 7:30 PM"hash code discrepancies" {
val p0 = 0.0
val p1 = -0.0
(p0 == p1) shouldBe true
val n0: Number = 0.0
val n1: Number = -0.0
n0.hashCode() shouldBe n1.hashCode()
}
expected:<-2147483648> but was:<0>
Expected :-2147483648
Actual :0
is there a reason what is essentially one and the same number has two different hashcodes?Adam S
09/23/2024, 7:51 PMephemient
09/23/2024, 8:29 PMval p0 = Double.NaN
println(p0.hashCode() == p0.hashCode())
println(p0 == p0)
println(p0 as Number == p0)
ephemient
09/23/2024, 8:30 PM+0.0 != -0.0
and NaN == NaN
for hashCode
reasons (otherwise HashMap
is broken), while also wanting +0.0 == -0.0
and NaN != NaN
for IEEE 754 complianceephemient
09/23/2024, 8:31 PMAlex Kuznetsov
09/26/2024, 1:20 PM0.0 == -0.0
so it would seem logical that both should have the same hashCode
, correct?ephemient
09/26/2024, 1:46 PM==
to itself, so you'll never be able to retrieve or remove it from a HashMap
ephemient
09/26/2024, 1:48 PM>>> d = {float('NaN'): 1, float('NaN'): 2}
>>> d
{nan: 1, nan: 2}
>>> d[float('NaN')]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: nan
Alex Kuznetsov
09/26/2024, 1:49 PM0.0
, and -0.0
should be the same key, right?ephemient
09/26/2024, 1:49 PMhashCode
is defined in terms of the toRawBits()
representationephemient
09/26/2024, 1:49 PM+0.0
and -0.0
have different representationsAlex Kuznetsov
09/26/2024, 1:51 PMephemient
09/26/2024, 1:52 PMephemient
09/26/2024, 1:53 PM1 / +0.0 == +Infinity
1 / -0.0 == -Infinity
Alex Kuznetsov
09/26/2024, 1:54 PM