OpenTally/src/numbers/fixed.rs

349 lines
7.8 KiB
Rust

/* OpenTally: Open-source election vote counting
* Copyright © 2021 Lee Yingtong Li (RunasSudo)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use super::{Assign, Number};
use ibig::{IBig, ops::Abs};
use num_traits::{Num, One, Zero};
use std::cmp::{Ord, PartialEq, PartialOrd};
use std::ops;
use std::fmt;
static mut DPS: Option<usize> = None;
static mut FACTOR: Option<IBig> = None;
#[inline]
pub fn get_dps() -> usize {
unsafe { DPS.unwrap() }
}
#[inline]
fn get_factor() -> &'static IBig {
unsafe { FACTOR.as_ref().unwrap() }
}
/// Fixed-point number
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Fixed(IBig);
impl Fixed {
/// Set the number of decimal places to compute results to
pub fn set_dps(dps: usize) {
unsafe {
DPS = Some(dps);
FACTOR = Some(IBig::from(10).pow(dps));
}
}
}
impl Number for Fixed {
fn new() -> Self { Self(IBig::zero()) }
fn describe() -> String { format!("--numbers fixed --decimals {}", get_dps()) }
fn pow_assign(&mut self, exponent: i32) {
self.0 = self.0.pow(exponent as usize) * get_factor() / get_factor().pow(exponent as usize);
}
fn floor_mut(&mut self, dps: usize) {
// Only do something if truncating
if dps < get_dps() {
let factor = IBig::from(10).pow(get_dps() - dps);
self.0 /= &factor;
self.0 *= factor;
}
}
fn ceil_mut(&mut self, dps: usize) {
// Only do something if truncating
if dps < get_dps() {
self.0 -= IBig::one();
let factor = IBig::from(10).pow(get_dps() - dps);
self.0 /= &factor;
self.0 += IBig::one();
self.0 *= factor;
}
}
fn parse(s: &str) -> Self {
// Parse decimal
if s.contains('.') {
let (whole, decimal) = s.split_once('.').unwrap();
let whole = match IBig::from_str_radix(whole, 10) {
Ok(value) => value,
Err(_) => panic!("Syntax Error"),
} * get_factor();
let decimal = match IBig::from_str_radix(decimal, 10) {
Ok(value) => value,
Err(_) => panic!("Syntax Error"),
} * get_factor() / IBig::from(10).pow(decimal.len());
return Self(whole + decimal);
}
// Parse integer
if let Ok(value) = Self::from_str_radix(s, 10) {
return value;
} else {
panic!("Syntax Error");
}
}
}
impl Num for Fixed {
type FromStrRadixErr = ibig::error::ParseError;
fn from_str_radix(str: &str, radix: u32) -> Result<Self, Self::FromStrRadixErr> {
match IBig::from_str_radix(str, radix) {
Ok(value) => Ok(Self(value * get_factor())),
Err(err) => Err(err)
}
}
}
impl Assign for Fixed {
fn assign(&mut self, src: Self) { self.0 = src.0 }
}
impl Assign<&Self> for Fixed {
fn assign(&mut self, src: &Self) { self.0 = src.0.clone() }
}
impl From<usize> for Fixed {
fn from(n: usize) -> Self { Self(IBig::from(n) * get_factor()) }
}
// TODO: Fix rounding
impl fmt::Display for Fixed {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let dps = match f.precision() {
Some(precision) => if precision < get_dps() { precision } else { get_dps() },
None => get_dps(),
};
let mut result;
if dps == get_dps() {
result = self.0.clone().abs().to_string();
} else {
// Rounding required
let factor = IBig::from(10).pow(get_dps() - dps - 1); // -1 to account for rounding digit
let mut rounded = (&self.0 / factor).abs() + IBig::from(5); // Add 5 to force round-to-nearest
rounded /= IBig::from(10); // Remove rounding digit
result = rounded.to_string();
}
//let should_add_minus = (self.0 < IBig::zero()) && result != "0";
let should_add_minus = self.0 < IBig::zero();
// Add leading 0s
result = format!("{0:0>1$}", result, dps + 1);
// Add the decimal point
if dps > 0 {
result.insert(result.len() - dps, '.');
}
// Add the sign
if should_add_minus {
result.insert(0, '-');
}
return f.write_str(&result);
}
}
impl One for Fixed {
fn one() -> Self { Self(get_factor().clone()) }
}
impl Zero for Fixed {
fn zero() -> Self { Self::new() }
fn is_zero(&self) -> bool { self.0.is_zero() }
}
impl ops::Neg for Fixed {
type Output = Self;
fn neg(self) -> Self::Output { Self(-self.0) }
}
impl ops::Add for Fixed {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output { Self(self.0 + rhs.0) }
}
impl ops::Sub for Fixed {
type Output = Self;
fn sub(self, _rhs: Self) -> Self::Output {
todo!()
}
}
impl ops::Mul for Fixed {
type Output = Self;
fn mul(self, _rhs: Self) -> Self::Output {
todo!()
}
}
impl ops::Div for Fixed {
type Output = Self;
fn div(self, rhs: Self) -> Self::Output { Self(self.0 * get_factor() / rhs.0) }
}
impl ops::Rem for Fixed {
type Output = Self;
fn rem(self, _rhs: Self) -> Self::Output {
todo!()
}
}
impl ops::Add<&Self> for Fixed {
type Output = Self;
fn add(self, rhs: &Self) -> Self::Output { Self(self.0 + &rhs.0) }
}
impl ops::Sub<&Self> for Fixed {
type Output = Self;
fn sub(self, rhs: &Self) -> Self::Output { Self(self.0 - &rhs.0) }
}
impl ops::Mul<&Self> for Fixed {
type Output = Self;
fn mul(self, rhs: &Self) -> Self::Output { Self(self.0 * &rhs.0 / get_factor()) }
}
impl ops::Div<&Self> for Fixed {
type Output = Self;
fn div(self, rhs: &Self) -> Self::Output { Self(self.0 * get_factor() / &rhs.0) }
}
impl ops::Rem<&Self> for Fixed {
type Output = Self;
fn rem(self, _rhs: &Self) -> Self::Output {
todo!()
}
}
impl ops::AddAssign for Fixed {
fn add_assign(&mut self, rhs: Self) { self.0 += rhs.0; }
}
impl ops::SubAssign for Fixed {
fn sub_assign(&mut self, rhs: Self) { self.0 -= rhs.0; }
}
impl ops::MulAssign for Fixed {
fn mul_assign(&mut self, rhs: Self) {
self.0 *= rhs.0;
self.0 /= get_factor();
}
}
impl ops::DivAssign for Fixed {
fn div_assign(&mut self, rhs: Self) {
self.0 *= get_factor();
self.0 /= rhs.0;
}
}
impl ops::RemAssign for Fixed {
fn rem_assign(&mut self, _rhs: Self) {
todo!()
}
}
impl ops::AddAssign<&Self> for Fixed {
fn add_assign(&mut self, rhs: &Self) { self.0 += &rhs.0; }
}
impl ops::SubAssign<&Self> for Fixed {
fn sub_assign(&mut self, rhs: &Self) { self.0 -= &rhs.0; }
}
impl ops::MulAssign<&Self> for Fixed {
fn mul_assign(&mut self, rhs: &Self) {
self.0 *= &rhs.0;
self.0 /= get_factor();
}
}
impl ops::DivAssign<&Self> for Fixed {
fn div_assign(&mut self, rhs: &Self) {
self.0 *= get_factor();
self.0 /= &rhs.0;
}
}
impl ops::RemAssign<&Self> for Fixed {
fn rem_assign(&mut self, _rhs: &Self) {
todo!()
}
}
impl ops::Neg for &Fixed {
type Output = Fixed;
fn neg(self) -> Self::Output { Fixed(-&self.0) }
}
impl ops::Add<Self> for &Fixed {
type Output = Fixed;
fn add(self, rhs: Self) -> Self::Output { Fixed(&self.0 + &rhs.0) }
}
impl ops::Sub<Self> for &Fixed {
type Output = Fixed;
fn sub(self, rhs: Self) -> Self::Output { Fixed(&self.0 - &rhs.0) }
}
impl ops::Mul<Self> for &Fixed {
type Output = Fixed;
fn mul(self, rhs: Self) -> Self::Output { Fixed(&self.0 * &rhs.0 / get_factor()) }
}
impl ops::Div<Self> for &Fixed {
type Output = Fixed;
fn div(self, rhs: Self) -> Self::Output { Fixed(&self.0 * get_factor() / &rhs.0) }
}
impl ops::Rem<Self> for &Fixed {
type Output = Fixed;
fn rem(self, _rhs: Self) -> Self::Output {
todo!()
}
}
/*
impl ops::Add<&&Rational> for &Rational {
}
impl ops::Sub<&&Rational> for &Rational {
}
impl ops::Mul<&&Rational> for &Rational {
}
impl ops::Div<&&Rational> for &Rational {
}
impl ops::Rem<&&Rational> for &Rational {
}
*/