From d522cf78ecc96dfdefcadadbdd259f503861effb Mon Sep 17 00:00:00 2001 From: Georg Hopp Date: Thu, 5 Dec 2019 16:40:33 +0100 Subject: [PATCH] reduce very large fractions close to a whole number to the whole number --- fractional/src/fractional.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/fractional/src/fractional.rs b/fractional/src/fractional.rs index b97d688..007da4a 100644 --- a/fractional/src/fractional.rs +++ b/fractional/src/fractional.rs @@ -86,7 +86,17 @@ impl Fractional { #[inline] pub fn reduce(self) -> Self { let Fractional(n, d) = self; - Self(n / hcf(n, d), d / hcf(n, d)) + let (_n, _d) = if n > d { (n, d) } else { (d, n) }; + + // if the difference from _n % _d to _n is very big we are close to + // a whole number and can ignore the fractional part... this reduces + // the precision but ensures smaller numbers for numerator and + // denominator. + if _d > 1 && (_n % _d) * 10000000 < _n { + Self(_n / _d, 1) + } else { + Self(n / hcf(n, d), d / hcf(n, d)) + } } #[inline]