6

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.

1
  • 3
    Note: this seems to be the typical "epsilon" method to compare floating point numbers, however be aware that there is an issue with this method => magnitude variations. An absolute "epsilon" will not work when a and b are of a significantly higher magnitude, because then b - epsilon == b and b + epsilon == b. You will not have the issue for integrals, obviously. For floating points, therefore, you might want to investigate relative epsilons; that is abs(a - b) / max(abs(a), abs(b)) < epsilon, which instead guarantees that a and b are within N% of each other. Commented Dec 18, 2014 at 12:58

1 Answer 1

5

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
}
2
  • I've just came up with a similar solution. T: PartialOrd + Add<T,T> + Sub<T,T> + Copy.
    – antekone
    Commented Dec 18, 2014 at 12:35
  • Indeed, thanks for the correction. I typed too fast and didn't check through the entirety of OP's use case. Above post has been edited.
    – dummydev
    Commented Dec 18, 2014 at 13:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.