Skip to content

Commit fce6446

Browse files
committed
add a FuzzyEq method that accepts an epsilon value
1 parent abb79cb commit fce6446

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

src/libstd/cmp.rs

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
1+
// Copyright 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
//
@@ -19,24 +19,37 @@ const fuzzy_epsilon: float = 1.0e-6;
1919

2020
pub trait FuzzyEq {
2121
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 {
2526
pure fn fuzzy_eq(&self, other: &float) -> bool {
2627
float::abs(*self - *other) < fuzzy_epsilon
2728
}
29+
30+
pure fn fuzzy_eq_eps(&self, other: &float, epsilon: &float) -> bool {
31+
float::abs(*self - *other) < *epsilon
32+
}
2833
}
2934

3035
impl f32: FuzzyEq {
3136
pure fn fuzzy_eq(&self, other: &f32) -> bool {
3237
f32::abs(*self - *other) < (fuzzy_epsilon as f32)
3338
}
39+
40+
pure fn fuzzy_eq_eps(&self, other: &f32, epsilon: &f32) -> bool {
41+
f32::abs(*self - *other) < *epsilon
42+
}
3443
}
3544

3645
impl f64: FuzzyEq {
3746
pure fn fuzzy_eq(&self, other: &f64) -> bool {
3847
f64::abs(*self - *other) < (fuzzy_epsilon as f64)
3948
}
49+
50+
pure fn fuzzy_eq_eps(&self, other: &f64, epsilon: &f64) -> bool {
51+
f64::abs(*self - *other) < *epsilon
52+
}
4053
}
4154

4255
#[test]
@@ -45,3 +58,9 @@ fn test_fuzzy_equals() {
4558
assert (&1.0f32).fuzzy_eq(&1.0f32);
4659
assert (&1.0f64).fuzzy_eq(&1.0f64);
4760
}
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

Comments
 (0)