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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With