1- // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
1+ // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
22// file at the top-level directory of this distribution and at
33// http://rust-lang.org/COPYRIGHT.
44//
99// except according to those terms.
1010
1111#[ forbid( deprecated_mode) ] ;
12- /// Additional general-purpose comparison functionality.
12+ //! Additional general-purpose comparison functionality.
1313
1414use core:: f32;
1515use core:: f64;
@@ -18,31 +18,49 @@ use core::float;
1818const fuzzy_epsilon: float = 1.0e-6 ;
1919
2020pub 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 ;
2223}
2324
2425impl 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
2732 }
2833}
2934
3035impl 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
3342 }
3443}
3544
3645impl 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
3952 }
4053}
4154
4255#[ test]
4356fn 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 ) ;
4760}
4861
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