Sort Floats With total_cmp

Sort floating-point data with f64::total_cmp, the IEEE-754 total order that gives NaN a deterministic position instead of panicking on incomparable values.

RustData Integrity

Code

rustsnippet
14 lines
fn main() {
    let mut readings = [1.5, f64::NAN, -3.25, 0.0, f64::INFINITY, -3.25];

    // f64 只实现 PartialOrd:NaN 让默认比较无法给出全序,
    // total_cmp 提供 IEEE-754 全序,NaN 位置确定(大于 +inf)
    readings.sort_by(f64::total_cmp);
    println!("ordered: {readings:?}");

    // NaN 与 +inf 的比较结果是确定的,可以稳定断言
    println!(
        "nan vs inf: {:?}",
        f64::NAN.total_cmp(&f64::INFINITY)
    );
}

How it works

Sort Floats With total_cmp keeps everything in the function main.

Applying it

The demo output is labeled (ordered:, nan vs inf:), so every printed line maps back to its originating operation.

Statements that matter

let mut readings = [1.5, f64::NAN, -3.25, 0.0, f64::INFINITY, -3.25];
f64::NAN.total_cmp(&f64::INFINITY)
);
readings.sort_by(f64::total_cmp);

Interactive Tools for This Topic

FAQ

What does Sort Floats With total_cmp print when run?
Invoke the file as-is — the `ordered:`, `nan vs inf:` prefixes identify which step printed each line.