Skip to content

Commit e4c7d8e

Browse files
committed
Add type parameter for epsilon value
1 parent b081f59 commit e4c7d8e

File tree

1 file changed

+42
-5
lines changed

1 file changed

+42
-5
lines changed

src/libstd/cmp.rs

Lines changed: 42 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,12 @@ use core::float;
1717

1818
pub const FUZZY_EPSILON: float = 1.0e-6;
1919

20-
pub trait FuzzyEq {
20+
pub trait FuzzyEq<Eps> {
2121
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;
2323
}
2424

25-
impl float: FuzzyEq {
25+
impl float: FuzzyEq<float> {
2626
pure fn fuzzy_eq(&self, other: &float) -> bool {
2727
self.fuzzy_eq_eps(other, &FUZZY_EPSILON)
2828
}
@@ -32,7 +32,7 @@ impl float: FuzzyEq {
3232
}
3333
}
3434

35-
impl f32: FuzzyEq {
35+
impl f32: FuzzyEq<f32> {
3636
pure fn fuzzy_eq(&self, other: &f32) -> bool {
3737
self.fuzzy_eq_eps(other, &(FUZZY_EPSILON as f32))
3838
}
@@ -42,7 +42,7 @@ impl f32: FuzzyEq {
4242
}
4343
}
4444

45-
impl f64: FuzzyEq {
45+
impl f64: FuzzyEq<f64> {
4646
pure fn fuzzy_eq(&self, other: &f64) -> bool {
4747
self.fuzzy_eq_eps(other, &(FUZZY_EPSILON as f64))
4848
}
@@ -64,3 +64,40 @@ fn test_fuzzy_eq_eps() {
6464
assert (&1.2f).fuzzy_eq_eps(&0.9, &0.5);
6565
assert !(&1.5f).fuzzy_eq_eps(&0.9, &0.5);
6666
}
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

Comments
 (0)