logo

Module decorum::cmp

source · []
Expand description

Ordering and comparisons.

This module provides traits and functions for comparing floating-point and other partially ordered values. For primitive floating-point types, a total ordering is provided via the FloatEq and FloatOrd traits:

$$-\infin<\cdots<0<\cdots<\infin<\text{NaN}$$

Note that both zero and NaN have more than one representation in IEEE-754 encoding. Given the set of zero representations $Z$ and set of NaN representations $N$, this ordering coalesces -0, +0, and NaNs such that:

$$ \begin{aligned} a=b&\mid a\in{Z},~b\in{Z}\cr[1em] a=b&\mid a\in{N},~b\in{N}\cr[1em] n>x&\mid n\in{N},~x\notin{N} \end{aligned} $$

These same semantics are used in the Eq and Ord implementations for ContrainedFloat, which includes the Total, NotNan, and Finite type definitions.

Examples

Comparing f64 values using a total ordering:

use core::cmp::Ordering;
use decorum::cmp::FloatOrd;
use decorum::Nan;

let x = f64::NAN;
let y = 1.0f64;

let (min, max) = match x.float_cmp(&y) {
    Ordering::Less | Ordering::Equal => (x, y),
    _ => (y, x),
};

Computing a pairwise minimum that propagates NaNs:

use decorum::cmp;
use decorum::Nan;

let x = f64::NAN;
let y = 1.0f64;

// `Nan` is incomparable and represents an undefined computation with respect to
// ordering, so `min` is assigned a `NaN` value in this example.
let min = cmp::min_or_undefined(x, y);

Traits

Equivalence relation for floating-point primitives.

Total ordering of primitive floating-point types.

Partial ordering of types with intrinsic representations for undefined comparisons.

Functions

Partial maximum of types with intrinsic representations for undefined.

Partial minimum of types with intrinsic representations for undefined.