21

Here is the simple question, I'm writing a function that returns max value of multiple floats, std::cmp::max gives me:

the trait bound `{float}: std::cmp::Ord` is not satisfied

Do I need to write this for every project:

macro_rules! max {
    ($x: expr) => ($x);
    ($x: expr, $($z: expr),+) => {{
        let y = max!($($z),*);
        if $x > y {
            $x
        } else {
            y
        }
    }}
}

So what is the recommended way to get max value of multiple floats?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
McGrady
  • 10,869
  • 13
  • 47
  • 69
  • 2
    You might be interested in the [`float-ord` crate](https://crates.io/crates/float-ord). – ljedrz Dec 10 '18 at 13:30
  • @E_net4iskindandwelcoming Yeah, I noticed that question, but do I need to create a vector to get the max value? – McGrady Dec 10 '18 at 13:31
  • 1
    No, not really. The duplicate applied to your question is that `std::cmp::max` expects a type that implements `Ord`, but no floating point type implements it for the reasons explained in the answer. You can take a wrapper around `f32` and `f64` that produces an unambiguous total order. – E_net4 Dec 10 '18 at 13:32
  • 24
    Note that there is [`f32::max`](https://doc.rust-lang.org/stable/std/primitive.f32.html#method.max) and [`f64::max`](https://doc.rust-lang.org/stable/std/primitive.f64.html#method.max) – Jmb Dec 10 '18 at 13:34
  • @Jmb Thanks, that's a good way, but still write several `max` method. – McGrady Dec 10 '18 at 13:37
  • 2
    *Do I need to write this* — note that your suggested code does not handle NaN values correctly; `(max!(f64::NAN, 0.0), max!(0.0, f64::NAN))` will result in `(0, NaN)` – Shepmaster Dec 10 '18 at 14:02

0 Answers0