batbox_approx/
lib.rs

1//! Approximate comparing of things
2#![warn(missing_docs)]
3
4/// Default EPS used for approx equality
5pub const DEFAULT_EPS: f32 = 1e-9;
6
7/// Implement this for types you want to check for approximate equality
8pub trait Approx {
9    /// Get an approximated distance between two values
10    fn approx_distance_to(&self, other: &Self) -> f32;
11
12    /// Check if values are approximately equal using [DEFAULT_EPS]
13    fn approx_eq(&self, other: &Self) -> bool {
14        self.approx_eq_eps(other, DEFAULT_EPS)
15    }
16
17    /// Check if values are approximately equal using supplied eps value
18    fn approx_eq_eps(&self, other: &Self, eps: f32) -> bool {
19        self.approx_distance_to(other) <= eps
20    }
21}
22
23impl<T: batbox_num::Float> Approx for T {
24    fn approx_distance_to(&self, other: &T) -> f32 {
25        (self.as_f32() - other.as_f32()).abs()
26    }
27}
28
29#[test]
30fn test_approx_eq_f32() {
31    assert!(1.0_f32.approx_eq_eps(&1.1_f32, 0.15));
32    assert!(23_424.215_f32.approx_eq(&23_424.215_f32));
33    assert!(!1.0_f32.approx_eq(&1.1_f32));
34    assert!(!24352.64_f32.approx_eq(&-54.0_f32));
35    assert!(!1.0_f32.approx_eq_eps(&2.0_f32, 0.5));
36}
37
38#[test]
39fn test_approx_eq_f64() {
40    assert!(1.0_f64.approx_eq_eps(&1.1_f64, 0.15_f32));
41    assert!(23424.2143_f64.approx_eq(&23424.2143_f64));
42    assert!(!1.0_f64.approx_eq(&1.1_f64));
43    assert!(!24352.64_f64.approx_eq(&-54.0_f64));
44    assert!(!1.0_f64.approx_eq_eps(&2.0_f64, 0.5_f32));
45}