1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/// Macro to test that two values are approximately equal. It checks that the relative difference between
/// the two values is less than some epsilon value.
///
/// ```ignore
/// use approx_eq::assert_approx_eq;
/// fn main() {
///   assert_approx_eq!(1., 0.99999999999); // should pass
///   assert_approx_eq!(1., 0.99999999999, 1e-5); // should pass
///   assert_approx_eq!(1., 0.99999999999, 1e-20); // should fail
///   assert_approx_eq!(1., 2.) // should fail
/// }
/// ```

#[macro_use]
pub mod approx_eq {
    #[macro_export]
    /// Epsilon takes a default value of 1e-6.
    /// It is also possible to specify the error level to use.
    macro_rules! assert_approx_eq {
        ($x: expr, $y: expr) => {
            let eps = 1e-6;
            let (x, y): (f64, f64) = ($x, $y);
            assert!(&x.signum() == &y.signum());
            let (x, y): (f64, f64) = (x.abs(), y.abs());
            assert!((&x - &y).abs() / [x, y].iter().cloned().fold(f64::NAN, f64::min) < eps);
        };
        ($x: expr, $y: expr, $e: expr) => {
            let (x, y): (f64, f64) = ($x, $y);
            assert!(&x.signum() == &y.signum());
            let (x, y): (f64, f64) = (x.abs(), y.abs());
            assert!((&x - &y).abs() / [x, y].iter().cloned().fold(f64::NAN, f64::min) < $e);
        };
    }
}

#[test]
fn test_noeps() {
    assert_approx_eq!(1., 1.);
    assert_approx_eq!(1., 1.000001);
}

#[test]
fn test_witheps() {
    assert_approx_eq!(1.0000000001, 1., 1e-5);
}

#[test]
#[should_panic(expected = "assertion failed")]
fn test_invalid() {
    assert_approx_eq!(1.0000000001, 1., 1e-10);
}

#[test]
#[should_panic(expected = "assertion failed")]
fn test_sign() {
    assert_approx_eq!(1., -1.);
}