104 points · by aviramha · 4y ago · 126 comments
This inconsistency infuriated me when I discovered it but the Javadoc for Double.equals explicitly states that this anomaly is there to "allow hash tables to work properly".
If I get floats from $somewhere, I might want to index them into a hash data structure without creating a huge sparse array.
If you assume float numbers have "identity" such that, whatever the precision, "x == x" always holds (other than NaN), then this is a perfectly valid thing to want.
I'm struggling to think of a valid use case where there is no better alternative.
Any design utilizing this language "feature" seems masochistic and begging to get sliced by sheet metal edges.
A hash table of floating-point values can be used for, say, memoizing a function whose argument (or arguments) are floating-point.
A compiler could use a floating-point-keyed hash table for deduplicating identical floating-point constants. Say that constants are stored in some static area, and referenced by address: it's wasteful to repeat those constants. Some constant defining mechanisms (like #define in C) proliferate copies of a constant as a repeated subexpression.
Why would you ever want a number to be stored in a floating point format - that is a much better question.
Most of our numeric values don’t even correspond to the domain of floating point. For business and programming goals, -0 is a complete technical nonsense. NaN too, it should just raise an exception (there are quiet and signalling nans, everyone defaults to quiet). And so should non-low-level integer overflow, really, unless there is a software fallback. Intermediate calculations limited to a low fixed number of digits is nonsense. Accounting for constant rounding/formatting errors is also a nuisance.
Builtin, first class citizen, hardware enabled, base 10 fixed point could be the answer. But there’s almost always either bigint-only which is barely used even in a standard library, or a serious performance hit which nobody wants. There would still be issues, but much less in practice.
Floating point is a niche type suitable for “multimedia”, NNs and maybe few other special contexts. They are the default only because everyone on the hardware..runtime spectrum traditionally believes that ordinary numbers are not their responsibility.
IEEE floating points are 32 bit / 64 bit, so it's not in principle any more insane than using (u)int32 / (u)int64 as keys. It's not like the key space is unbounded or even hard to estimate - it's just not a common thing to see in the wild, and I guess most devs rarely have a reason to consider how many values fit between two floating point numbers.
One possible answer: you're in Javascript or something similar. You wanted integer keys, but all you have is floating-point numbers.
Because it's a cache and you didn't specifically handle that edge case.
https://doc.rust-lang.org/std/collections/struct.HashMap.htm...
https://doc.rust-lang.org/std/cmp/trait.Eq.html
https://doc.rust-lang.org/std/cmp/trait.PartialEq.html
There is also a partial ordering relation `PartialOrd` (and `Ord` for complete relations) Floating point values only implement the partial relation as well because of NaN's. This means that it is a bit harder to sort them, though the floating point standard also has a seperate complete comparison relation with some extra rules which you can use instead.
https://doc.rust-lang.org/std/primitive.f64.html#method.tota...
Drain is interesting, because it resolves the other problem if things are in the collection which can never be retrieved from it. Drain gives you each of the things in the collection, one at a time, to do with as you wish, the collection is now empty. So this means even if the collection has a dozen SillyNonsenses in it, all of which insist they're not the one you were looking for whenever you go looking for a SillyNonsense in the collection, you get all twelve of them out in Drain, and can examine them as you wish.
Of course if you just wanted to fish one thing out and then throw the rest away, you can do that, once you drop the result of Drain the rest of the things being drained are dropped.
(I'm pretty sure I recognize your username as someone with way more rust experience than me. For the crowd an implementation of Eq for floats that used the standard comparison operators would be "incorrect", which is why the stdlib doesn't provide one)
I'd rather panic on NaN comparisons than complicate the fundamental comparison traits. Treat it like integer overflow or array bounds access. We don't have different traits for indexing that might fail or overflow that might happen. There are methods on the trait to handle those cases when you care about them.
But that said, this feels like an XY issue. If you're comparing hashes of floats as keys somewhere you don't want IEEE 754 defined equivalence. You almost certainly want bit equivalence, which means the keys should be type punned to u32/u64. Classic example is memoizing function calls with floats. You don't want to compare the semantic values of the arguments, but the literal bits. For floats that's not the same.
The fundamental comparisons are complicated period. Pretending they’re not and hoping you don’t hit the branches that crash is a terrible idea for writing reliable software.
For everything where the comparisons aren’t complicated (like integers), Rust is easy. For things where the comparisons are complicated, Rust makes you acknowledge this reality and deal with it. This is correct behavior.
For maps with keys that are reflexive with == the Go compiler already optimizes the range loop to a single efficient runtime map clear call: https://go-review.googlesource.com/c/go/+/110055
Most people do use the literals for creating the empty map/slice. "make" is mostly useful when specifying a known length or capacity, which saves unnecessary allocations and improves performance.
https://github.com/golang/go/issues/56351#issuecomment-12914...
"We talked about defining maps.Clear in #55002, but how? It would not be possible to write in pure Go code. Instead it would need some kind of hidden entry point into the runtime.
In the past I've referred to that kind of library change as a "back-door language change", meaning it's a language change - it adds something not possible in pure Go - but pretends not to be one. We try hard to avoid doing that."
> Why is len a function and not a method?
> We debated this issue but decided implementing len and friends as functions was fine in practice and didn't complicate questions about the interface (in the Go type sense) of basic types.
I imagine similar reasoning applies to "clear" here.
When you create a new type like this, you lose all methods from the original type. If the delete operation was implemented as a method on the `map` type, `Header.Del` would need to convert back to a `map` type to call it.
(map[string][]string(h)).Delete(key)For a beginner in Go it makes absolutely no sense at all. Most of the builtins should be methods.
[1] https://docs.oracle.com/en/java/javase/19/docs/api/java.base...
What will help you is that `clear()` is part of `Java.until.Collection` so just about every container has it.
https://en.wikipedia.org/wiki/Transformation_matrix#Affine_t...
I don’t think there’s any real use case for it
I’d say clear() is good for clarity, and that’s it
Histogram where you want to keep a count for each float value you’ve seen (maybe rounded to some precision to reduce the number of buckets)
Not disagreeing with your comment, just saying it’s not uncommon
If you're rounding anyway it's basically the same amount of work.
But the ‘naive’ histogram is an example of a map using float keys.
Hashing the floats themselves isn't going to give you a useful histogram.
Is there a codebase that hashes float to a useful effect? If it exists, I'd be interested to see it
That is not obvious; a compiler could have a pattern match for that exact AST pattern, and transform it to a delete operation. (Except for that pesky issue where two fail to be equivalent due to NaN keys.)
Quick and dirty, not entirely correct proof-of-concept in TXR Lisp:
1> (macroexpand '(my-dohash (k v some.obj.hash) (print [some.obj.hash k])))
(dohash (k v some.obj.hash
())
(print [some.obj.hash
k]))
2> (macroexpand '(my-dohash (k v some.obj.hash) (del [some.obj.hash k])))
(clearhash hash)
Impl: (defmacro my-dohash ((kvar vvar hash : result) . body)
(if-match @(require ((del [@hash @kvar]))
(null result))
body
^(clearhash hash)
^(dohash (,kvar ,vvar ,hash ,result) ,*body))) m = make(map[A]B, cap(m))
just like it already recognized for k := range m {
delete(m, k)
}
and many other similar idioms.(cap because len is not quite the same -- note, cap is not currently defined on maps)
EDIT: Likely because that's an assigment on m, not a mutation of it, so it can't be done e.g. in a function that gets m as argument.
I had to try it in Python (3.10.4, Windows on x86), it worked fine:
>>> import math
>>> a={math.nan: 1}
>>> a
{nan: 1}
>>> del(a[math.nan])
>>> a
{} >>> d = {float('nan'): 1}
>>> d
{nan: 1}
>>> del d[float('nan')]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: nan /* Quick result when objects are the same.
Guarantees that identity implies equality. */
if (v == w) {
if (op == Py_EQ)
return 1;
else if (op == Py_NE)
return 0;
}
`math.nan` is always itself, and thus this shortcut is taken and the key works.Explicitly checking for NaNs would (at least) double the cycle count in cases where that branch is not taken, and having to deal with the custom comparison is even worse. This is not helped by the fact that there isn't a single NaN value: there are both positive and negative NaNs, and there are 23 bits which are usually ignored but for which some values do have specific meaning.
To make it even worse, modern CPUs include vector extensions, allowing you to operate on multiple values at once. With AVX-512, you can compare 32 floats per clock cycle. I would not be surprised if switching to a custom comparison made some edge cases over 100x slower.
It must have been a biggy because this solution means your domain now loses the property that, in general, x == x. This property is a fundamental axiomatic feature of any notion of equality. A non-reflexive equality isn't just weird - it's daft/stupid/surprising.
The same problem that's solved by having a lot of proofs say "for all y != 0, ..." If NaN == NaN, then you can no longer assume that x/z == y/z implies x == y. Which is also a fundamental (though non-axiomatic) result of arithmetic!
NaN is an effort to represent partial functions in code that usually expects totality. It's not the best way but it's pretty good, and making NaN == NaN is also not how we'd do it with decades of hindsight.
People do probably rely on NaN ≠ NaN but I think that's more of a side effect of compatibility than anything else.
return f != f