1
- // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
1
+ // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2
2
// file at the top-level directory of this distribution and at
3
3
// http://rust-lang.org/COPYRIGHT.
4
4
//
9
9
// except according to those terms.
10
10
11
11
#[ forbid( deprecated_mode) ] ;
12
- /// Additional general-purpose comparison functionality.
12
+ //! Additional general-purpose comparison functionality.
13
13
14
14
use core:: f32;
15
15
use core:: f64;
@@ -18,31 +18,49 @@ use core::float;
18
18
const fuzzy_epsilon: float = 1.0e-6 ;
19
19
20
20
pub trait FuzzyEq {
21
- pure fn fuzzy_eq ( other: & self ) -> bool ;
21
+ pure fn fuzzy_eq ( & self , other: & self ) -> bool ;
22
+ pure fn fuzzy_eq_eps ( & self , other: & self , epsilon: & self ) -> bool ;
22
23
}
23
24
24
25
impl float: FuzzyEq {
25
- pure fn fuzzy_eq ( other : & float ) -> bool {
26
- return float:: abs ( self - * other) < fuzzy_epsilon;
26
+ pure fn fuzzy_eq ( & self , other : & float ) -> bool {
27
+ self . fuzzy_eq_eps ( other, fuzzy_epsilon)
28
+ }
29
+
30
+ pure fn fuzzy_eq_eps ( & self , other : & float , epsilon : & float ) -> bool {
31
+ float:: abs ( * self - * other) < * epsilon
27
32
}
28
33
}
29
34
30
35
impl f32 : FuzzyEq {
31
- pure fn fuzzy_eq ( other : & f32 ) -> bool {
32
- return f32:: abs ( self - * other) < ( fuzzy_epsilon as f32 ) ;
36
+ pure fn fuzzy_eq ( & self , other : & f32 ) -> bool {
37
+ self . fuzzy_eq_eps ( other, fuzzy_epsilon as f32 )
38
+ }
39
+
40
+ pure fn fuzzy_eq_eps ( & self , other : & f32 , epsilon : & f32 ) -> bool {
41
+ f32:: abs ( * self - * other) < * epsilon
33
42
}
34
43
}
35
44
36
45
impl f64 : FuzzyEq {
37
- pure fn fuzzy_eq ( other : & f64 ) -> bool {
38
- return f64:: abs ( self - * other) < ( fuzzy_epsilon as f64 ) ;
46
+ pure fn fuzzy_eq ( & self , other : & f64 ) -> bool {
47
+ self . fuzzy_eq_eps ( other, fuzzy_epsilon as f64 )
48
+ }
49
+
50
+ pure fn fuzzy_eq_eps ( & self , other : & f64 , epsilon : & f64 ) -> bool {
51
+ f64:: abs ( * self - * other) < * epsilon
39
52
}
40
53
}
41
54
42
55
#[ test]
43
56
fn test_fuzzy_equals ( ) {
44
- assert ( ( & 1.0 ) . fuzzy_eq ( & 1.0 ) ) ;
45
- assert ( ( & 1.0f32 ) . fuzzy_eq ( & 1.0f32 ) ) ;
46
- assert ( ( & 1.0f64 ) . fuzzy_eq ( & 1.0f64 ) ) ;
57
+ assert ( & 1.0 ) . fuzzy_eq ( & 1.0 ) ;
58
+ assert ( & 1.0f32 ) . fuzzy_eq ( & 1.0f32 ) ;
59
+ assert ( & 1.0f64 ) . fuzzy_eq ( & 1.0f64 ) ;
47
60
}
48
61
62
+ #[ test]
63
+ fn test_fuzzy_eq_eps ( ) {
64
+ assert ( & 1.2 ) . fuzzy_eq_eps ( & 0.9 , & 0.5 ) ;
65
+ assert ! ( & 1.5 ) . fuzzy_eq_eps ( & 0.9 , & 0.5 ) ;
66
+ }
0 commit comments