【libm】 16 IEEE 754-2019 maximum 函数实现(fmaximum_num.rs)
一、源码
这段代码实现了一个符合 IEEE 754-2019 标准的 maximumNumber 函数,用于计算两个浮点数的最大值,但与普通的 maximum 函数相比,它对 NaN 的处理略有不同。
/* SPDX-License-Identifier: MIT OR Apache-2.0 */
//! IEEE 754-2019 `maximumNumber`.
//!
//! Per the spec, returns:
//! - `x` if `x > y`
//! - `y` if `y > x`
//! - Non-NaN if one operand is NaN
//! - Logic following +0.0 > -0.0
//! - Either `x` or `y` if `x == y` and the signs are the same
//! - qNaN if either operand is a NaN
//!
//! Excluded from our implementation is sNaN handling.use super::super::Float;#[inline]
pub fn fmaximum_num<F: Float>(x: F, y: F) -> F {let res =if x.is_nan() || x < y || (x.to_bits() == F::NEG_ZERO.to_bits() && y.is_sign_positive()) {y} else {x};// Canonicalizeres * F::ONE
}
二、代码分析
- 许可证声明
/* SPDX-License-Identifier: MIT OR Apache-2.0 */
- 代码使用 MIT 或 Apache-2.0 许可证。
- 文档注释
//! IEEE 754-2019 `maximumNumber`.
//!
//! Per the spec, returns:
//! - `x` if `x > y`
//! - `y` if `y > x`
//! - Non-NaN if one operand is NaN
//! - Logic following +0.0 > -0.0
//! - Either `x` or `y` if `x == y` and the signs are the same
//! - qNaN if either operand is a NaN
//!
//! Excluded from our implementation is sNaN handling.
-
这是一个模块级文档注释,说明这个模块实现了 IEEE 754-2019 标准的 maximumNumber 函数。
-
与 maximum 的区别:
-
如果其中一个操作数是 NaN,而另一个不是,则返回非 NaN 的值(maximum 会返回 NaN)。
-
如果 x == y 且符号相同,返回 x 或 y(实现可能选择任意一个)。
-
仍然遵循 +0.0 > -0.0 的逻辑。
-
如果两个操作数都是 NaN,返回 qNaN(静默 NaN)。
-
不处理 sNaN(信号 NaN)。
-
- 导入依赖
use super::super::Float;
- 从上级模块导入 Float trait,该 trait 定义了浮点数类型的基本操作和常量(如 NEG_ZERO)。
- 函数定义
#[inline]
pub fn fmaximum_num<F: Float>(x: F, y: F) -> F {
-
#[inline]:提示编译器将函数内联,以提高性能。
-
pub fn fmaximum_num<F: Float>(x: F, y: F) -> F:
-
定义一个公共泛型函数 fmaximum_num,接受两个相同浮点数类型 F 的参数,返回一个 F 类型的值。
-
F 必须实现 Float trait。
-
- 函数实现
let res =if x.is_nan() || x < y || (x.to_bits() == F::NEG_ZERO.to_bits() && y.is_sign_positive()) {y} else {x};
-
条件判断:
-
x.is_nan():
- 如果 x 是 NaN,返回 y(即使 y 也是 NaN,此时返回 y,即 qNaN)。
-
x < y:
- 如果 x 小于 y,返回 y。
-
x.to_bits() == F::NEG_ZERO.to_bits() && y.is_sign_positive():
- 如果 x 是负零 (-0.0),并且 y 是正数(包括 +0.0),则返回 y(因为 +0.0 > -0.0)。
-
-
否则:
- 返回 x(即 x >= y 或 x 不是 NaN)。
- 规范化结果
// Canonicalizeres * F::ONE
- 将结果乘以 F::ONE(即 1.0)进行规范化,确保结果的二进制表示是规范化的形式(例如,确保 NaN 的 payload 是规范的)。
三、总结
- 与 maximum 的区别:
-
maximum:如果任一操作数是 NaN,返回 NaN。
-
maximumNumber:如果只有一个是 NaN,返回非 NaN 的值;如果两个都是 NaN,返回 qNaN。
- 特殊处理:
-
正确处理 +0.0 > -0.0。
-
如果 x == y 且符号相同,返回 x 或 y(实现可能选择任意一个)。
- 规范化:
- 确保返回值的二进制表示是规范的(例如,避免非规范的 NaN 表示)。
这个函数适用于需要更宽松的 NaN 处理逻辑的场景,例如某些数值计算库或编译器优化。