我如何获得包含浮点数的迭代器的最小值? [英] How do I get the minimum value of an iterator containing floating point numbers?
问题描述
我明白为什么浮点数没有Ord的实现,但是当我想要懒惰并使用Iterator的时候,这并不是特别有用。
任何人都有工作或简单的方法来获取包含浮点数的迭代器的最小值(min,min_by)?我知道一个可以排序(这是慢的)或者用另一种类型来包装它,然后实现所需的交易(这是很详细的),但是我希望能有一些更优雅的东西。
游戏拥有自己的 min
方法一致地处理NaN,所以你可以折叠迭代器:
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);
$ b $ p $打印 -10
。
如果你想要不同的NaN处理,你可以使用 PartialOrd :: partial_cmp
。例如,如果您想传播NaN,请使用以下内容进行折叠:
使用std :: f64;
使用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,
一些(_)=> b,
}
});
println!({},min);
}
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.
Does anybody have a work around 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.
解决方案 Floats have their own min
method that handles 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);
}
这篇关于我如何获得包含浮点数的迭代器的最小值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!