Rust 中 f64 的最大值

max of f64 in Rust

我有一个价格向量 (f64)。我想计算最高价。

在 rust 中计算 f64 集合最大值的当前最简单和最惯用的方法是什么?

已经有一些关于 Ordf64 的讨论,但我不确定什么是最新的和不太老套的方法。

我依赖以下但我想有一些内置操作

let max = prices.iter().fold(None, |r, &n| match r {
    Some(p) => Some(f64::max(p, n)),
    None => Some(e),
});

(这只是一些免费幺半群的折叠)

我不知道这样做的不同方法,但我过去使用过以下方法:

let arr = [1.0, -42.0, 0.0, -5.0, 42.0, 7.0];
let max = arr.iter().copied().fold(f64::NAN, f64::max) // 42.0

另一种解决方案,使用流行的 ordered-float crate,允许您使用 built-in Iterator::max 方法:

use ordered_float::NotNan; // 2.0.0

let max = arr
    .iter()
    .copied()
    .map(NotNan::new)
    .flatten() // ignore NAN values (errors from the previous line)
    .max()
    .map(NotNan::into_inner);

这与您编写的用于从整数数组中查找最大值的惯用代码基本相同:

let max = arr.iter().copied().max();

不同之处在于它在每个值周围添加了一个 NotNan 包装器,它实现了 Ord。找到结果后,它会展开值以获取内部浮点数。您可以将此模式应用于大多数使用整数的现有代码,以更新它以改为使用浮点数。

另一种选择:它仍然是 unstable/nightly-only,但是有一个 total_cmp method on f32 and f64 that you could use with max_by

arr.iter().max_by(|a, b| a.total_cmp(b))

Rust playground

从 Rust 1.43 开始,你可以这样写:

my_iterator.fold(f64::NEG_INFINITY, f64::max)

说明:使用f64::NEG_INFINITY作为初始值,因为它是f64::max操作的中性元素。