Skip to main content

xingo_statla/
real.rs

1//! # Chapter 12.0.3 — Comparisons
2//!
3//! ## Purpose
4//! The rule of Chapter 5.C of `xingo-sparse` holds here too: **every
5//! comparison of scalar values goes through the helpers of this module**,
6//! and every threshold lives in an options struct ([`crate::CholOptions`],
7//! [`crate::QrOptions`]) — never a literal in a kernel (D-0088). The
8//! helpers of Chapter 5.6 are `pub(crate)` in `xingo-sparse`, so this is a
9//! private copy *with the same definitions* (D-0127, §3), restricted to the
10//! ones this crate uses.
11//!
12//! ## Notation
13//! For finite `a`, `b` and `ε ≥ 0`, `s(a, b) = max(1, |a|, |b|)`:
14//! * `lt(a, b)` — `a < b` exactly, written `b − a > 0·s(a, b)` for finite
15//!   values and `a < b` otherwise (`Tolerances::lt(a, b, 0.0)`);
16//! * `le_exact(a, b)` — `a ≤ b` exactly, without the scale;
17//! * `is_exact_zero(x)` — `x = 0` (or `−0`): a structural test;
18//! * `is_nan(x)` — `x ≠ x`.
19//!
20//! ## Invariant
21//! (C1) No helper is called with NaN except `is_nan` (debug builds assert
22//!      it): the public functions reject non-finite input first.
23//!
24//! ## References
25//! Chapter 5.6 of `xingo-sparse` (`real.rs`), whose definitions these are.
26
27use xingo_sparse::Real;
28
29/// The scale `s(a, b) = max(1, |a|, |b|)`.
30#[inline]
31fn scale<T: Real>(a: T, b: T) -> T {
32    T::ONE.max(a.abs()).max(b.abs())
33}
34
35/// `a < b` exactly (`Tolerances::lt(a, b, 0.0)`).
36#[inline]
37pub(crate) fn lt<T: Real>(a: T, b: T) -> bool {
38    debug_assert!(!is_nan(a) && !is_nan(b), "lt called with NaN");
39    if a.is_finite() && b.is_finite() {
40        b - a > T::ZERO * scale(a, b)
41    } else {
42        a < b
43    }
44}
45
46/// `a ≤ b` exactly, without the scale.
47#[inline]
48pub(crate) fn le_exact<T: Real>(a: T, b: T) -> bool {
49    debug_assert!(!is_nan(a) && !is_nan(b), "le_exact called with NaN");
50    a <= b
51}
52
53/// `x = 0` exactly (or `−0`): a structural test.
54#[inline]
55pub(crate) fn is_exact_zero<T: Real>(x: T) -> bool {
56    x == T::ZERO
57}
58
59/// `x` is NaN (it is not equal to itself).
60#[inline]
61#[allow(clippy::eq_op)] // the NaN test is x ≠ x
62pub(crate) fn is_nan<T: Real>(x: T) -> bool {
63    x != x
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69
70    #[test]
71    fn comparisons_match_their_definitions() {
72        assert!(lt(1.0, 2.0) && !lt(2.0, 2.0) && !lt(3.0, 2.0));
73        assert!(lt(f64::NEG_INFINITY, 0.0) && !lt(f64::INFINITY, 1e308));
74        assert!(le_exact(2.0, 2.0) && !le_exact(2.0 + f64::EPSILON * 2.0, 2.0));
75        assert!(is_exact_zero(-0.0) && !is_exact_zero(f64::MIN_POSITIVE));
76        assert!(is_nan(f64::NAN) && !is_nan(f64::INFINITY));
77    }
78}