Browse Source

Alternative reduce with specifiable precision

master
Georg Hopp 6 years ago
parent
commit
3e231c2474
Signed by: ghopp GPG Key ID: 4C5D226768784538
  1. 19
      fractional/src/continuous.rs
  2. 23
      fractional/src/fractional.rs

19
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<i64>, f :Fractional) -> Vec<i64> {
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)),
}
}

23
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 = (&regular_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<i64> for Fractional {

Loading…
Cancel
Save