diff --git a/fractional/src/continuous.rs b/fractional/src/continuous.rs index 13fc3d5..b720679 100644 --- a/fractional/src/continuous.rs +++ b/fractional/src/continuous.rs @@ -49,6 +49,22 @@ impl Continuous { inner(&mut v, x, a0, 0, 1, a0); Continuous(v) } + + pub fn into_prec(&self, prec :usize) -> Fractional { + let Continuous(c) = self; + let p = if prec <= c.len() { prec } else { c.len() }; + + let to_frac = |acc :Fractional, x :&i64| { + let Fractional(an, ad) = acc.noreduce_add((*x).into()); + Fractional(ad, an) + }; + + let Fractional(n, d) = c[..p] + . into_iter() + . rev() + . fold(Fractional(0, 1), to_frac); + Fractional(d, n) + } } impl From<&Fractional> for Continuous { @@ -57,11 +73,12 @@ impl From<&Fractional> for Continuous { fn inner(mut v :Vec, f :Fractional) -> Vec { let Fractional(n, d) = f; let a = n / d; - let Fractional(_n, _d) = f - a.into(); + let Fractional(_n, _d) = f.noreduce_sub(a.into()); v.push(a); match _n { 1 => { v.push(_d); v }, + 0 => v, _ => inner(v, Fractional(_d, _n)), } } diff --git a/fractional/src/fractional.rs b/fractional/src/fractional.rs index d177215..42a0e38 100644 --- a/fractional/src/fractional.rs +++ b/fractional/src/fractional.rs @@ -28,6 +28,8 @@ use std::fmt::{Formatter, Display}; use std::num::TryFromIntError; use std::ops::{Add,Sub,Neg,Mul,Div}; +use crate::continuous::Continuous; + #[derive(Debug, Eq, Clone, Copy)] pub struct Fractional (pub i64, pub i64); @@ -67,9 +69,28 @@ impl Fractional { Self(1, _n / _d) } } else { - Self(n / hcf(n, d), d / hcf(n, d)) + //Self(n / hcf(n, d), d / hcf(n, d)) + let regular_reduced = self; + let cont :Continuous = (®ular_reduced).into(); + cont.into_prec(5) } } + + pub fn noreduce_add(self, other: Self) -> Self { + let Fractional(n1, d1) = self; + let Fractional(n2, d2) = other; + let n = n1 * (self.gcd(other) / d1) + n2 * (self.gcd(other) / d2); + Self(n, self.gcd(other)) + } + + pub fn noreduce_sub(self, other: Self) -> Self { + self.noreduce_add(other.noreduce_neg()) + } + + pub fn noreduce_neg(self) -> Self { + let Fractional(n, d) = self; + Self(-n, d) + } } impl From for Fractional {