@@ -17,12 +17,12 @@ use core::float;
17
17
18
18
pub const FUZZY_EPSILON : float = 1.0e-6 ;
19
19
20
- pub trait FuzzyEq {
20
+ pub trait FuzzyEq < Eps > {
21
21
pure fn fuzzy_eq ( & self , other : & Self ) -> bool ;
22
- pure fn fuzzy_eq_eps ( & self , other : & Self , epsilon : & Self ) -> bool ;
22
+ pure fn fuzzy_eq_eps ( & self , other : & Self , epsilon : & Eps ) -> bool ;
23
23
}
24
24
25
- impl float: FuzzyEq {
25
+ impl float: FuzzyEq < float > {
26
26
pure fn fuzzy_eq ( & self , other : & float ) -> bool {
27
27
self . fuzzy_eq_eps ( other, & FUZZY_EPSILON )
28
28
}
@@ -32,7 +32,7 @@ impl float: FuzzyEq {
32
32
}
33
33
}
34
34
35
- impl f32 : FuzzyEq {
35
+ impl f32 : FuzzyEq < f32 > {
36
36
pure fn fuzzy_eq ( & self , other : & f32 ) -> bool {
37
37
self . fuzzy_eq_eps ( other, & ( FUZZY_EPSILON as f32 ) )
38
38
}
@@ -42,7 +42,7 @@ impl f32: FuzzyEq {
42
42
}
43
43
}
44
44
45
- impl f64 : FuzzyEq {
45
+ impl f64 : FuzzyEq < f64 > {
46
46
pure fn fuzzy_eq ( & self , other : & f64 ) -> bool {
47
47
self . fuzzy_eq_eps ( other, & ( FUZZY_EPSILON as f64 ) )
48
48
}
@@ -64,3 +64,40 @@ fn test_fuzzy_eq_eps() {
64
64
assert ( & 1.2 f) . fuzzy_eq_eps ( & 0.9 , & 0.5 ) ;
65
65
assert ! ( & 1.5 f) . fuzzy_eq_eps ( & 0.9 , & 0.5 ) ;
66
66
}
67
+
68
+ #[ test]
69
+ mod test_complex{
70
+ use cmp:: * ;
71
+
72
+ struct Complex { r : float , i : float }
73
+
74
+ impl Complex : FuzzyEq < float > {
75
+ pure fn fuzzy_eq ( & self , other : & Complex ) -> bool {
76
+ self . fuzzy_eq_eps ( other, & FUZZY_EPSILON )
77
+ }
78
+
79
+ pure fn fuzzy_eq_eps ( & self , other : & Complex ,
80
+ epsilon : & float ) -> bool {
81
+ self . r . fuzzy_eq_eps ( & other. r , epsilon) &&
82
+ self . i . fuzzy_eq_eps ( & other. i , epsilon)
83
+ }
84
+ }
85
+
86
+ #[ test]
87
+ fn test_fuzzy_equals ( ) {
88
+ let a = Complex { r : 0.9 , i : 0.9 } ;
89
+ let b = Complex { r : 0.9 , i : 0.9 } ;
90
+
91
+ assert ( a. fuzzy_eq ( & b) ) ;
92
+ }
93
+
94
+ #[ test]
95
+ fn test_fuzzy_eq_eps ( ) {
96
+ let other = Complex { r : 0.9 , i : 0.9 } ;
97
+
98
+ assert ( & Complex { r : 0.9 , i : 1.2 } ) . fuzzy_eq_eps ( & other, & 0.5 ) ;
99
+ assert ( & Complex { r : 1.2 , i : 0.9 } ) . fuzzy_eq_eps ( & other, & 0.5 ) ;
100
+ assert ! ( & Complex { r: 0.9 , i: 1.5 } ) . fuzzy_eq_eps ( & other, & 0.5 ) ;
101
+ assert ! ( & Complex { r: 1.5 , i: 0.9 } ) . fuzzy_eq_eps ( & other, & 0.5 ) ;
102
+ }
103
+ }
0 commit comments