num-rational icon indicating copy to clipboard operation
num-rational copied to clipboard

Add explicit and unified interface for approximation

Open cmpute opened this issue 4 years ago • 1 comments

I propose to add a trait to explicitly allow rational approximation for various types. This is motivated by my crate for irrational numbers where I would like to have a unified interface for approximation (see https://github.com/rust-num/num-rational/issues/35#issuecomment-1008221821).

Here's a draft:

pub enum Approximation<T> {
    Approximated(T),
    Exact(T)
}

pub trait RationalApproximation<T: Integer> {
    // Here `limit` determines the (absolute?) maximum of the numerator and denumerator 
    fn approx_rational(&self, limit: &T) -> Approximation<Ratio<T>>;
}

There're several benefits to define this interface:

  1. If we implement RationalApproximation for Ratio<T> itself, then we can have an explicit method to limit the precision of the fraction. (related to #99)
  2. Other number types can use this interface to provide approximation ability (such as my irrational number types)
  3. The existing from_float and approximate_float functions seem messy to me. I would suggest to keep the from_float method, while implements RationalApproximation for f32 and f64.

Thanks!

cmpute avatar Jan 09 '22 05:01 cmpute

Besides, from_float could be implemented as a TryFrom trait. And as we have From<T: Integer>, from_integer seems unnecessary for me. It makes user confusing.

Another option might be deprecate from_float as well, this functionality will be only available through FromPrimitive::{from_f32, from_f64}.

cmpute avatar Jan 11 '22 04:01 cmpute