问题描述
我了解为什么浮点数没有实现Ord
的实现,但这对我没有特别的帮助当我想变得懒惰并使用迭代器时.
I understand why the floats don't have an implementation for Ord
but that doesn't particularly help me when I want to be lazy and use iterators.
是否有一种解决方法或一种简单的方法来获取包含浮点数的迭代器的最小值/min/min_by?
Is there a workaround or an easy way to take the minimum / min / min_by of an iterator containing floating point numbers?
我知道人们可以对它进行排序(很慢)或将其包装为另一种类型并实现所需的交易(这很冗长),但是我希望有一些更优雅的东西.
I know one can sort (which is slow) or wrap it in another type and implement the needed trades (which is verbose) but I am hoping for something a little more elegant.
推荐答案
浮点数具有自己的 min
和 max
方法可以始终如一地处理NaN,因此您可以覆盖迭代器:
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);
}
打印-10
.
如果要使用其他NaN处理,则可以使用PartialOrd::partial_cmp
.例如,如果您要传播NaN,请折叠:
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);
}
这篇关于如何获得包含浮点数的迭代器的最小值或最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!