Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What trait can I use for a "fuzzy compare" of numeric types?

Tags:

rust

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.

like image 626
antonone Avatar asked Dec 18 '14 11:12

antonone


1 Answers

You do not need to specify that T should be a built-in number type, only that it must support the addition, subtraction and comparison traits required by your formula:

fn fuzzy_cmp<T: Add<T, T> + Sub<T, T> + PartialOrd>(a: T, b: T, tolerance: T) -> bool {
    a >= b - tolerance && a <= b + tolerance
}
like image 90
dummydev Avatar answered Oct 10 '22 02:10

dummydev