Skip to main content

lib_jsl_utils/
machine_epsilon.rs

1//! Machine epsilon and unit-in-the-last-place helpers.
2//!
3//! See the book entry [Shared types, constants and utilities](https://jwkunz.github.io/lib_jsl/book/foundations/core-utils.html#machine-epsilon-and-ulps).
4
5/// Machine epsilon of `f64`: the gap between 1.0 and the next representable number (2⁻⁵²).
6pub fn machine_epsilon() -> f64 {
7    f64::EPSILON
8}
9
10/// Machine epsilon of `f32` (2⁻²³).
11pub fn machine_epsilon_f32() -> f32 {
12    f32::EPSILON
13}
14
15/// Determines the `f64` machine epsilon empirically by halving until `1 + e/2 == 1`.
16///
17/// Useful to verify that the platform's floating-point behaviour matches the constant (it does not
18/// on, e.g., x87 extended-precision code paths).
19pub fn measure_machine_epsilon() -> f64 {
20    let mut e = 1.0f64;
21    // black_box prevents the optimiser folding the loop condition to a constant comparison.
22    while std::hint::black_box(1.0 + e / 2.0) > 1.0 {
23        e /= 2.0;
24    }
25    e
26}
27
28/// Spacing between `x` and the next larger-magnitude `f64` (the unit in the last place).
29/// `NaN` for non-finite input.
30pub fn ulp(x: f64) -> f64 {
31    if !x.is_finite() {
32        return f64::NAN;
33    }
34    let x = x.abs();
35    if x == f64::MAX {
36        return x - f64::from_bits(x.to_bits() - 1);
37    }
38    f64::from_bits(x.to_bits() + 1) - x
39}
40
41/// Number of representable `f64` values between `a` and `b` (0 if equal; `None` if either is NaN).
42// ANCHOR: ulps
43pub fn ulps_between(a: f64, b: f64) -> Option<u64> {
44    if a.is_nan() || b.is_nan() {
45        return None;
46    }
47    // Map the bit patterns onto a monotonic integer line.
48    let key = |v: f64| {
49        let bits = v.to_bits() as i64;
50        if bits < 0 { i64::MIN - bits } else { bits }
51    };
52    Some(key(a).abs_diff(key(b)))
53}
54// ANCHOR_END: ulps
55
56/// Whether `a` and `b` differ by at most `max_ulps` representable values.
57pub fn approx_eq_ulps(a: f64, b: f64, max_ulps: u64) -> bool {
58    ulps_between(a, b).is_some_and(|d| d <= max_ulps)
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn epsilon_values_agree() {
67        assert_eq!(machine_epsilon(), 2.0f64.powi(-52));
68        assert_eq!(machine_epsilon_f32(), 2.0f32.powi(-23));
69        assert_eq!(measure_machine_epsilon(), machine_epsilon());
70    }
71
72    #[test]
73    fn ulp_properties() {
74        assert_eq!(ulp(1.0), f64::EPSILON);
75        assert_eq!(ulp(-1.0), f64::EPSILON);
76        assert_eq!(ulp(2.0), 2.0 * f64::EPSILON);
77        assert_eq!(ulp(0.0), f64::from_bits(1));
78        assert!(ulp(f64::NAN).is_nan() && ulp(f64::INFINITY).is_nan());
79        assert!(ulp(f64::MAX) > 0.0);
80    }
81
82    #[test]
83    fn ulp_distance() {
84        assert_eq!(ulps_between(1.0, 1.0), Some(0));
85        assert_eq!(ulps_between(1.0, 1.0 + f64::EPSILON), Some(1));
86        assert_eq!(ulps_between(-0.0, 0.0), Some(0));
87        assert_eq!(ulps_between(-f64::from_bits(1), f64::from_bits(1)), Some(2));
88        assert_eq!(ulps_between(f64::NAN, 1.0), None);
89        assert!(approx_eq_ulps(0.1 + 0.2, 0.3, 1));
90        assert!(!approx_eq_ulps(1.0, 1.001, 10));
91    }
92}