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
58
#[macro_export]
macro_rules! assert_approx_eq {
($a:expr, $b:expr) => ({
let eps = 1.0e-6;
let (a, b) = (&$a, &$b);
assert!((*a - *b).abs() < eps,
"assertion failed: `(left !== right)` \
(left: `{:?}`, right: `{:?}`, expect diff: `{:?}`, real diff: `{:?}`)",
*a, *b, eps, (*a - *b).abs());
});
($a:expr, $b:expr, $eps:expr) => ({
let (a, b) = (&$a, &$b);
assert!((*a - *b).abs() < $eps,
"assertion failed: `(left !== right)` \
(left: `{:?}`, right: `{:?}`, expect diff: `{:?}`, real diff: `{:?}`)",
*a, *b, $eps, (*a - *b).abs());
})
}
#[test]
fn it_should_not_panic_if_values_are_approx_equal() {
assert_approx_eq!(64f32.sqrt(), 8f32);
}
#[test]
#[should_panic]
fn it_should_panic_if_values_are_not_approx_equal() {
assert_approx_eq!(3 as f32, 4 as f32);
}
#[test]
fn compare_with_explicit_eps() {
assert_approx_eq!(3f64, 4f64, 2f64);
}
#[test]
#[should_panic]
fn bad_compare_with_explicit_eps() {
assert_approx_eq!(3f64, 4f64, 1e-3f64);
}