Float type that implements `Eq` in rust

1.5k Views Asked by At

In rust, is there a version of f32 / f64 that implements Eq?
The only reason I can see for f32 / f64 not implementing Eq is that NaN != NaN.
Potential ways such a type could behave:

  1. The type could just make NaN == NaN for that type which would be really useful because I often assume that a == a is always true.
  2. Another approach would be to disallow NaN entirely in that type so that there is no NaN that could be unequal to itself.

Ideally there would be a way to use that type just by using a suffix (similar to 2.3_f32) but I don't think that is possible.

1

There are 1 best solutions below

0
Chayim Friedman On

Since Rust 1.62.0, you can use the total_cmp() methods of f32 and f64. Not a type on their own, but you can build a type on top of them if you want.

Or you can use the ordered-float crate. It provides the NotNan and OrderedFloat types, each matching one behavior you described.