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.
Code
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
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.