如何对“NaN”进行排序,使其大于任何其他数字,并且等于任何其他“NaN”?

时间:2016-11-03 17:58:42

标签: sorting floating-point rust

我正在根据两个标准对矢量进行排序。第一个是浮点,可以是NaN,第二个是用于按字典顺序断开关系的字符串。

vec.sort_by(|a, b| {
    match (foo(a) as f64 / bar(a) as f64).partial_cmp(&(foo(b) as f64 / bar(b) as f64)) {
        Some(x) => {
            Ordering::Equal => name(a).cmp(name(b)),
            other => other,
        }
        None() => {
            //Not sure what to put here.
        }
    }
}

foo(a)返回int> 0, bar(a)返回int> = 0, name(a)会返回& String

如何对NaN进行排序,使其大于任何其他数字,并且等于任何其他NaN(词典排序)?

1 个答案:

答案 0 :(得分:4)

您已经知道如何处理关系,您只需要以所需方式比较浮点数。只是...写下你描述的代码:

use std::cmp::Ordering;
use std::f32;

fn main() {
    let mut vec = [91.0, f32::NAN, 42.0]; 

    vec.sort_by(|&a, &b| {
        match (a.is_nan(), b.is_nan()) {
            (true, true) => Ordering::Equal,
            (true, false) => Ordering::Greater,
            (false, true) => Ordering::Less,
            (false, false) => a.partial_cmp(&b).unwrap(),
        }
    });

    println!("{:?}", vec);
}

你可能很想要将它包装在代表键的结构中:

use std::cmp::Ordering;
use std::f32;

fn main() {
    let mut vec = [91.0, f32::NAN, 42.0];

    vec.sort_by_key(|&a| MyNanKey(a));

    println!("{:?}", vec);
}

#[derive(Debug, Copy, Clone, PartialEq)]
struct MyNanKey(f32);

impl Eq for MyNanKey {}

impl PartialOrd for MyNanKey {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for MyNanKey {
    fn cmp(&self, other: &Self) -> Ordering {
        match (self.0.is_nan(), other.0.is_nan()) {
            (true, true) => Ordering::Equal,
            (true, false) => Ordering::Greater,
            (false, true) => Ordering::Less,
            (false, false) => self.0.partial_cmp(&other.0).unwrap(),
        }
    }
}

我没有想过这是否适用于各种无穷大或非规范化浮点值,所以要小心。