Compare commits

...

4 Commits

Author SHA1 Message Date
17d43852d3 wip: partial cmp 2024-08-27 13:29:24 -07:00
12b825bb15 wip 2024-08-27 13:28:54 -07:00
cd70967c08 it's distinct enough for a crate 2024-08-27 13:28:54 -07:00
626eb7e9e2 ratio 2024-08-27 13:28:53 -07:00
6 changed files with 107 additions and 0 deletions

1
deferred_division/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target

14
deferred_division/Cargo.lock generated Normal file
View File

@ -0,0 +1,14 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "deferred_division"
version = "0.1.0"
dependencies = [
"fixed_wide_traits",
]
[[package]]
name = "fixed_wide_traits"
version = "0.1.0"

View File

@ -0,0 +1,11 @@
[package]
name = "deferred_division"
version = "0.1.0"
edition = "2021"
[features]
default=["fixed_wide_traits"]
fixed_wide_traits=["dep:fixed_wide_traits"]
[dependencies]
fixed_wide_traits = { version = "0.1.0", path = "../fixed_wide_traits", optional = true }

View File

@ -0,0 +1,8 @@
pub mod ratio;
#[cfg(feature="fixed_wide_traits")]
mod wide;
#[cfg(test)]
mod tests;

View File

@ -0,0 +1,10 @@
#[derive(Clone,Copy,Debug,Hash)]
pub struct Ratio<Num,Den>{
pub(crate)num:Num,
pub(crate)den:Den,
}
//this trait is like a constructor for Ratio
pub trait DeferredDiv<Rhs=Self>{
type Output;
fn deferred_div(self,rhs:Rhs)->Self::Output;
}

View File

@ -0,0 +1,63 @@
use std::ops::{Add,Mul};
use std::cmp::Ordering;
use crate::ratio::Ratio;
use fixed_wide_traits::wide::{WideMul,WideDiv};
impl<Num,Den,T> PartialOrd<T> for Ratio<Num,Den>
{
fn partial_cmp(&self,other:&T)->Option<Ordering>{
//a < c*b
match self.den.cmp(0){
Ordering::Less=>Some(self.num.partial_cmp(self.den.mul(other))),
Ordering::Equal=>None,//divide by zero
Ordering::Greater=>Some(self.num.partial_cmp(self.den.mul(other)).reverse()),
}
}
}
impl<Num,Den:Copy> Ratio<Num,Den>
{
pub fn rational_add<T>(self,rhs:T)->Ratio<<Num as Add<<Den as Mul<T>>::Output>>::Output,Den>
where
Den:Mul<T>,
Num:Add<<Den as Mul<T>>::Output>,
{
Ratio{
num:self.num+self.den.mul(rhs),
den:self.den,
}
}
pub fn wide_rational_add<T>(self,rhs:T)->Ratio<<Num as Add<<Den as WideMul<T>>::Output>>::Output,Den>
where
Den:WideMul<T>,
Num:Add<<Den as WideMul<T>>::Output>,
{
Ratio{
num:self.num+self.den.wide_mul(rhs),
den:self.den,
}
}
}
impl<Num,Den,T> WideMul<T> for Ratio<Num,Den>
where
Num:WideMul<T>,
{
type Output=Ratio<<Num as WideMul<T>>::Output,Den>;
fn wide_mul(self,rhs:T)->Ratio<<Num as WideMul<T>>::Output,Den>{
Ratio{
num:self.num.wide_mul(rhs),
den:self.den,
}
}
}
impl<Num,Den,T> WideDiv<T> for Ratio<Num,Den>
where
Den:WideMul<T>,
{
type Output=Ratio<Num,<Den as WideMul<T>>::Output>;
fn wide_div(self,rhs:T)->Ratio<Num,<Den as WideMul<T>>::Output>{
Ratio{
num:self.num,
den:self.den.wide_mul(rhs),
}
}
}