如何获得包含浮点数的迭代器的最小值或最大值?

编程入门 行业动态 更新时间:2024-10-26 15:23:26
本文介绍了如何获得包含浮点数的迭代器的最小值或最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我了解为什么浮点数没有实现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); }

更多推荐

如何获得包含浮点数的迭代器的最小值或最大值?

本文发布于:2023-11-30 10:40:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649687.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最大值   如何获得   最小值   迭代   浮点数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!