lib_jsl_utils/
machine_epsilon.rs1pub fn machine_epsilon() -> f64 {
7 f64::EPSILON
8}
9
10pub fn machine_epsilon_f32() -> f32 {
12 f32::EPSILON
13}
14
15pub fn measure_machine_epsilon() -> f64 {
20 let mut e = 1.0f64;
21 while std::hint::black_box(1.0 + e / 2.0) > 1.0 {
23 e /= 2.0;
24 }
25 e
26}
27
28pub 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
41pub fn ulps_between(a: f64, b: f64) -> Option<u64> {
44 if a.is_nan() || b.is_nan() {
45 return None;
46 }
47 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}
54pub 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}