From 6daedfe5d4232596f7c988f72afc00727d15e6ed Mon Sep 17 00:00:00 2001 From: yukirij Date: Tue, 29 Aug 2023 14:53:01 -0700 Subject: [PATCH] Add demo file for decimal implementation. --- src/bin/decimal.rs | 94 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 src/bin/decimal.rs diff --git a/src/bin/decimal.rs b/src/bin/decimal.rs new file mode 100644 index 0000000..0e40789 --- /dev/null +++ b/src/bin/decimal.rs @@ -0,0 +1,94 @@ +#![allow(dead_code)] + +#[derive(Clone, Copy)] +struct Decimal { + data:i64, +} +impl Decimal { + pub fn new() -> Self + { + Self { data:0 } + } + + pub fn with(value:f64) -> Self + { + let whole = value as i64; + let decimal = ((value - value.trunc()).abs() * (1i64 << E) as f64).floor() as i64; + Self { + data:(whole << E) + (decimal as i64), + } + } + + pub fn from(other:&Decimal) -> Self + { + let data :i64; + if E > D { data = other.data << (E - D); } + else if D > E { data = other.data >> (D - E); } + else { data = other.data; } + + Self { data:data } + } + + pub fn from_raw(data:i64) -> Self + { + Self { data:data } + } + + pub fn raw(&self) -> i64 + { + self.data + } + + pub fn f32(&self) -> f32 + { + (self.data >> E) as f32 + ((self.data & ((1i64 << E) - 1)) as f32 / (1i64 << E) as f32) + } + + pub fn f64(&self) -> f64 + { + (self.data >> E) as f64 + ((self.data & ((1i64 << E) - 1)) as f64 / (1i64 << E) as f64) + } +} +impl std::ops::Add for Decimal { + type Output = Self; + fn add(self, rhs: Self) -> Self::Output { + Decimal::::from_raw(self.data + rhs.data) + } +} +impl std::ops::Sub for Decimal { + type Output = Self; + fn sub(self, rhs: Self) -> Self::Output { + Decimal::::from_raw(self.data - rhs.data) + } +} +impl std::ops::Mul for Decimal { + type Output = Self; + fn mul(self, rhs: Self) -> Self::Output { + Decimal::::from_raw(((self.data as i128 * rhs.data as i128) >> E) as i64) + } +} +impl std::ops::Div for Decimal { + type Output = Self; + fn div(self, rhs: Self) -> Self::Output { + Decimal::::from_raw(((self.data as i128 * (1i64 << E) as i128) / rhs.data as i128) as i64) + } +} + +fn print_bytes(bytes:&Vec) +{ + for b in bytes { + print!("{:02x} ", b); + } print!("\n"); +} + +fn main() +{ + let a = Decimal::<16>::with(1.0); + let b = Decimal::<16>::with(1.0); + println!("a = {}", a.f64()); + println!("b = {}", b.f64()); + println!("add = {}", (a + b).f64()); + println!("sub = {}", (a - b).f64()); + println!("mul = {}", (a * b).f64()); + println!("div = {}", (a / b).f64()); +}