Why does Rust not implement total ordering via the Ord trait for f64 and f32?

后端 未结 1 1393
闹比i
闹比i 2020-11-29 13:09

While all the integer types in Rust implement Ord which emphasizes total ordering, the floating point types only implement PartialOrd. This means that there could be floatin

相关标签:
1条回答
  • 2020-11-29 13:37

    What is your question, precisely? Are you asking whether NaN exists, or whether it can be obtained as the result of accidental or voluntary computations? Yes, it does and it can. The sort of data structure that requires a total order for keys breaks down completely when the provided order is not a total order. You do not want even one exceptional value be different from itself, because it would break invariants of the structure and mean that anything can happen henceforth. NaN is not something that should be assumed to be innocuous as long as no problem has been shown, although that has been tried in other languages.

    IEEE 754's definition of the ordinary comparison operators <, <=, … makes them very useful in general—if not when you need a total order. In particular, it is easy to write conditions so that NaN inputs will be sent to the error branch:

    if (!(x <= MAX)) { // NaN makes this condition true
      error();
    }
    
    if (!(x >= MIN)) { // NaN makes this condition true
      error();
    }
    

    Because < and <= are so useful, they are the operations implemented as single, fast instructions in modern processors—the totalOrder predicate from IEEE 754 is typically not implemented in hardware. Programming languages map the fast instructions to constructs in the language and leave anyone who exceptionally needs totalOrder to pick it from a library or even to define it themselves.

    0 讨论(0)
提交回复
热议问题