Skip to content

Commit 5e77d55

Browse files
committed
Merge pull request #4664 from thestinger/fuzzy
FuzzyEq improvements
2 parents f1ddb2a + e0728d4 commit 5e77d55

File tree

1 file changed

+30
-12
lines changed

1 file changed

+30
-12
lines changed

src/libstd/cmp.rs

Lines changed: 30 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
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
//
@@ -9,7 +9,7 @@
99
// except according to those terms.
1010

1111
#[forbid(deprecated_mode)];
12-
/// Additional general-purpose comparison functionality.
12+
//! Additional general-purpose comparison functionality.
1313
1414
use core::f32;
1515
use core::f64;
@@ -18,31 +18,49 @@ use core::float;
1818
const fuzzy_epsilon: float = 1.0e-6;
1919

2020
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;
2223
}
2324

2425
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
2732
}
2833
}
2934

3035
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
3342
}
3443
}
3544

3645
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
3952
}
4053
}
4154

4255
#[test]
4356
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);
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

Comments
 (0)