What the hell can I use to “fuzzy compare” numeric types?

I am trying to write a "fuzzy comparison" 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 converting it to a generic version. Is there a property that groups the numbers of natural numbers and floating point numbers, allowing you to perform arithmetic operations on them? Something like that:

 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 already tried the sign of Ord , but it does not work:

 28:23 error: binary operation `-` cannot be applied to type `T` a >= b - tolerance && a <= b + tolerance ^~~~~~~~~~~~~ 

The core::num::Num value seems deprecated, so I'm not even trying to use it.

+6
source share
1 answer

You do not need to indicate that T should be a built-in number type, only to support the addition, subtraction and comparison characteristics 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 } 
+5
source

Source: https://habr.com/ru/post/979850/


All Articles