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
use super::traits::{Real, Scalar};

/// Returns true if x and y are equal with an absolute error of e
pub fn equal_with_abs_error<T>(x: T, y: T, e: T) -> bool
where
    T: Scalar,
{
    let a = if x > y { x - y } else { y - x };
    a <= e
}

/// Returns true if x and y are equal with a relative error of e
pub fn equal_with_rel_error<T>(x: T, y: T, e: T) -> bool
where
    T: Real,
{
    let a = if x > y { x - y } else { y - x };
    let b = if x > T::zero() { x } else { -x };
    a <= e * b
}

#[test]
fn test_equal_with_error() {
    let x: f32 = 1.0;
    let y: f32 = 1.0001;
    assert!(equal_with_abs_error(x, y, 0.001));
    assert!(!equal_with_abs_error(x, y, 0.00001));

    assert!(equal_with_rel_error(x, y, 0.001));
    assert!(!equal_with_rel_error(x, y, 0.00001));
}