1 // Copyright 2012-2013 The Rust Project Developers. See the
2 // COPYRIGHT file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Additional general-purpose comparison functionality.
17 pub static FUZZY_EPSILON: float = 1.0e-6;
19 pub trait FuzzyEq<Eps> {
20 fn fuzzy_eq(&self, other: &Self) -> bool;
21 fn fuzzy_eq_eps(&self, other: &Self, epsilon: &Eps) -> bool;
24 impl FuzzyEq<float> for float {
25 fn fuzzy_eq(&self, other: &float) -> bool {
26 self.fuzzy_eq_eps(other, &FUZZY_EPSILON)
29 fn fuzzy_eq_eps(&self, other: &float, epsilon: &float) -> bool {
30 float::abs(*self - *other) < *epsilon
34 impl FuzzyEq<f32> for f32 {
35 fn fuzzy_eq(&self, other: &f32) -> bool {
36 self.fuzzy_eq_eps(other, &(FUZZY_EPSILON as f32))
39 fn fuzzy_eq_eps(&self, other: &f32, epsilon: &f32) -> bool {
40 f32::abs(*self - *other) < *epsilon
44 impl FuzzyEq<f64> for f64 {
45 fn fuzzy_eq(&self, other: &f64) -> bool {
46 self.fuzzy_eq_eps(other, &(FUZZY_EPSILON as f64))
49 fn fuzzy_eq_eps(&self, other: &f64, epsilon: &f64) -> bool {
50 f64::abs(*self - *other) < *epsilon
55 fn test_fuzzy_equals() {
56 assert!((&1.0f).fuzzy_eq(&1.0));
57 assert!((&1.0f32).fuzzy_eq(&1.0f32));
58 assert!((&1.0f64).fuzzy_eq(&1.0f64));
62 fn test_fuzzy_eq_eps() {
63 assert!((&1.2f).fuzzy_eq_eps(&0.9, &0.5));
64 assert!(!(&1.5f).fuzzy_eq_eps(&0.9, &0.5));
71 struct Complex { r: float, i: float }
73 impl FuzzyEq<float> for Complex {
74 fn fuzzy_eq(&self, other: &Complex) -> bool {
75 self.fuzzy_eq_eps(other, &FUZZY_EPSILON)
78 fn fuzzy_eq_eps(&self, other: &Complex,
79 epsilon: &float) -> bool {
80 self.r.fuzzy_eq_eps(&other.r, epsilon) &&
81 self.i.fuzzy_eq_eps(&other.i, epsilon)
86 fn test_fuzzy_equals() {
87 let a = Complex {r: 0.9, i: 0.9};
88 let b = Complex {r: 0.9, i: 0.9};
90 assert!((a.fuzzy_eq(&b)));
94 fn test_fuzzy_eq_eps() {
95 let other = Complex {r: 0.9, i: 0.9};
97 assert!((&Complex {r: 0.9, i: 1.2}).fuzzy_eq_eps(&other, &0.5));
98 assert!((&Complex {r: 1.2, i: 0.9}).fuzzy_eq_eps(&other, &0.5));
99 assert!(!(&Complex {r: 0.9, i: 1.5}).fuzzy_eq_eps(&other, &0.5));
100 assert!(!(&Complex {r: 1.5, i: 0.9}).fuzzy_eq_eps(&other, &0.5));