I'm trying to write a "fuzzy compare" function in Rust.
Here is an example:
fn fuzzy_cmp(a: f64, b: f64, tolerance: f64) -> bool {
a >= b - tolerance && a <= b + tolerance
}
I have a problem in transforming it to a generic version. Is there a trait that groups natural and floating point numbers, while allowing to perform arithmetic operations on them? Something like this:
fn fuzzy_cmp<T: Numbers>(a: T, b: T, tolerance: T) -> bool {
a >= b - tolerance && a <= b + tolerance
}
I would like to use this function in cases like:
fuzzy_cmp(x, 20u64, 5u64)
fuzzy_cmp(y, 20f64, 5f64)
// ... etc
I've already tried Ord
trait, but it doesn't work:
28:23 error: binary operation `-` cannot be applied to type `T`
a >= b - tolerance && a <= b + tolerance
^~~~~~~~~~~~~
Trait core::num::Num
seems to be deprecated, so I'm not even trying to use it.
a
andb
are of a significantly higher magnitude, because thenb - epsilon == b
andb + epsilon == b
. You will not have the issue for integrals, obviously. For floating points, therefore, you might want to investigate relative epsilons; that isabs(a - b) / max(abs(a), abs(b)) < epsilon
, which instead guarantees thata
andb
are within N% of each other.