Make it so that multiplication doesn't overflow so easily

This commit is contained in:
Gwilym Kuiper 2021-06-05 23:50:49 +01:00 committed by Corwin
parent 026dad0773
commit 1bb05560cb

View file

@ -145,7 +145,11 @@ where
{ {
type Output = Self; type Output = Self;
fn mul(self, rhs: T) -> Self::Output { fn mul(self, rhs: T) -> Self::Output {
Num((self.0 * rhs.into().0) >> N) let rhs: Self = rhs.into();
Num(((self.floor() * rhs.floor()) << N)
+ (self.floor() * rhs.frac() + rhs.floor() * self.frac())
+ ((self.frac() * rhs.frac()) >> N))
} }
} }
@ -245,6 +249,10 @@ impl<I: FixedWidthUnsignedInteger, const N: usize> Num<I, N> {
self.0 >> N self.0 >> N
} }
pub fn frac(&self) -> I {
self.0 & ((I::one() << N) - I::one())
}
pub fn new(integral: I) -> Self { pub fn new(integral: I) -> Self {
Self(integral << N) Self(integral << N)
} }