How do I get the minimum or maximum value of an iterator containing floating point numbers?

Floats have their own min and max methods that handle NaN consistently, so you can fold over the iterator:

use std::f64;

fn main() {
    let x = [2.0, 1.0, -10.0, 5.0, f64::NAN];

    let min = x.iter().fold(f64::INFINITY, |a, &b| a.min(b));
    println!("{}", min);
}

Prints -10.

If you want different NaN handling, you can use PartialOrd::partial_cmp. For example, if you wish to propagate NaNs, fold with:

use std::f64;
use std::cmp::Ordering;

fn main() {
    let x = [2.0, 1.0, -10.0, 5.0, f64::NAN];

    let min = x.iter().fold(f64::INFINITY, |a, &b| {
        match PartialOrd::partial_cmp(&a, &b) {
            None => f64::NAN,
            Some(Ordering::Less) => a,
            Some(_) => b,
        }
    });
    println!("{}", min);
}

Leave a Comment