extra_asserts/
lib.rs

1use std::fmt::Debug;
2use std::ops::Sub;
3
4/// Asserts if a floating point is within some epsilon.  This allows
5/// you to compare calculations to make sure it's within some error factor
6/// of accuracy.
7///
8/// This one should pass
9/// ```
10/// use extra_asserts::assert_approx_eq;
11/// let x : f64 = 10.123456789;
12/// let y : f64 = 10.123467890;
13/// assert_approx_eq(x, y, &1e-4);
14/// ```
15///
16/// This one should fail
17/// ```should_panic
18/// use extra_asserts::assert_approx_eq;
19/// let x : f64 = 10.123456789;
20/// let y : f64 = 10.123467890;
21/// assert_approx_eq(x, y, &1e-10);
22/// ```
23pub fn assert_approx_eq<T>(l: T, r: T, epsilon: &T::Output)
24where
25    T: Sub + PartialOrd + Debug + Copy,
26    T::Output: Debug + PartialOrd,
27{
28    let diff = if l < r { r - l } else { l - r };
29    assert!(diff < *epsilon, format!("{:?} != {:?}", l, r));
30}