Add demo file for decimal implementation.

This commit is contained in:
yukirij 2023-08-29 14:53:01 -07:00
parent 4cd0f03b0a
commit 6daedfe5d4

94
src/bin/decimal.rs Normal file
View File

@ -0,0 +1,94 @@
#![allow(dead_code)]
#[derive(Clone, Copy)]
struct Decimal<const E:u8> {
data:i64,
}
impl<const E:u8> Decimal<E> {
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<const D:u8>(other:&Decimal<D>) -> 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<const E:u8> std::ops::Add for Decimal<E> {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Decimal::<E>::from_raw(self.data + rhs.data)
}
}
impl<const E:u8> std::ops::Sub for Decimal<E> {
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
Decimal::<E>::from_raw(self.data - rhs.data)
}
}
impl<const E:u8> std::ops::Mul for Decimal<E> {
type Output = Self;
fn mul(self, rhs: Self) -> Self::Output {
Decimal::<E>::from_raw(((self.data as i128 * rhs.data as i128) >> E) as i64)
}
}
impl<const E:u8> std::ops::Div for Decimal<E> {
type Output = Self;
fn div(self, rhs: Self) -> Self::Output {
Decimal::<E>::from_raw(((self.data as i128 * (1i64 << E) as i128) / rhs.data as i128) as i64)
}
}
fn print_bytes(bytes:&Vec<u8>)
{
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());
}