Need help in understanding floating-point total ordering added in 1.62.0

Previously rust didn't have total ordering for floating point numbers but I see that since 1.62.0 it does (Add a total ordering method for floating-point by scottmcm · Pull Request #53938 · rust-lang/rust · GitHub) this code is valid --
Rust Playground

I see that we are comparing bits for this. I want to understand when this would be a wise thing to do and when the potential pitfalls of floating-point comparisons have to kept in mind. This is partially breaking my brain a bit. Any help would be appreciated!

The code in playground was always "valid", in that it always could be compiled, even in Rust 1.0; and it is still "incorrect", in that you usually can't get any useful information from comparing floating point values for equality (the only exception is when you check if they are literally a copy of each other).

The method you're referring to isn't connected in any way to the == operator; it is to be called explicitly, wherever we need to have an ordering (not an equality) which handles NaNs gracefully.

2 Likes

Thanks for the clarification, I related Eq not being implemented to == not being there. My bad, thanks for your time!

The trait that implements == is PartialEq, not Eq.

Partial equality means that you are allowed to compare two values of the type, but a value may not always be equal to itself. It doesn't mean that equality comparison can't be defined.

1 Like

While I have your attention, can you kindly help with the reason why PartialEq is being implemented for floats but Eq is not being implemented (if we are just comparing bit pattern)?

For the same exact reason. NaN != NaN, which violates the definition of Eq.

The PartialEq/== operation on floats does not just compare bit patterns.

1 Like

FYI here's a couple of cases where float comparison and bitwise comparison disagree Rust Playground

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.