OpenTally/src/numbers/fixed.rs

471 lines
12 KiB
Rust
Raw Normal View History

2021-06-04 22:05:48 +10:00
/* 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/>.
*/
2021-06-14 20:43:36 +10:00
use super::{Assign, Number};
2021-06-04 22:05:48 +10:00
use ibig::{IBig, ops::Abs};
2021-09-13 03:43:17 +10:00
use num_traits::{Num, One, Signed, Zero};
2021-06-04 22:05:48 +10:00
2021-09-13 04:31:25 +10:00
use std::cell::{Cell, UnsafeCell};
2021-06-04 22:05:48 +10:00
use std::cmp::{Ord, PartialEq, PartialOrd};
use std::ops;
use std::fmt;
2021-09-13 04:31:25 +10:00
thread_local! {
static DPS: Cell<usize> = Cell::new(5);
static FACTOR: UnsafeCell<IBig> = UnsafeCell::new(IBig::from(10).pow(5));
}
2021-06-04 22:05:48 +10:00
pub fn get_dps() -> usize {
2021-09-13 04:31:25 +10:00
return DPS.with(|dps_cell| dps_cell.get());
2021-06-04 22:05:48 +10:00
}
2021-09-13 04:31:25 +10:00
fn get_factor<'a>() -> &'a IBig {
FACTOR.with(|factor_cell| {
let factor_ptr = factor_cell.get();
// SAFETY: Safe if requirements of Fixed::set_dps met
let factor_ref = unsafe { &*factor_ptr };
return factor_ref;
})
2021-06-04 22:05:48 +10:00
}
2021-06-14 20:43:36 +10:00
/// Fixed-point number
2021-06-16 20:28:03 +10:00
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
2021-06-04 22:05:48 +10:00
pub struct Fixed(IBig);
impl Fixed {
2021-06-16 17:20:29 +10:00
/// Set the number of decimal places to compute results to
2021-09-13 04:31:25 +10:00
///
/// SAFETY: This must be called before, and never after, any operations on [Fixed].
2021-06-04 22:05:48 +10:00
pub fn set_dps(dps: usize) {
2021-09-13 04:31:25 +10:00
DPS.with(|dps_cell| {
dps_cell.set(dps);
});
FACTOR.with(|factor_cell| {
let factor = IBig::from(10).pow(dps);
let factor_ptr = factor_cell.get();
// SAFETY: Safe if requirements above met
unsafe {
*factor_ptr = factor;
}
});
2021-06-04 22:05:48 +10:00
}
}
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) {
2021-09-13 03:43:17 +10:00
if exponent < 0 {
todo!();
}
2021-06-04 22:05:48 +10:00
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();
2021-06-04 22:05:48 +10:00
let factor = IBig::from(10).pow(get_dps() - dps);
self.0 /= &factor;
self.0 += IBig::one();
2021-06-04 22:05:48 +10:00
self.0 *= factor;
}
}
fn round_mut(&mut self, dps: usize) {
// Only do something if truncating
if dps < get_dps() {
2021-09-13 03:43:17 +10:00
let mut factor = IBig::from(10).pow(get_dps() - dps);
factor /= IBig::from(2);
2021-09-13 03:43:17 +10:00
self.0 += factor;
self.floor_mut(dps);
}
}
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());
2021-09-13 03:43:17 +10:00
if whole.is_negative() {
return Self(whole - decimal);
} else {
return Self(whole + decimal);
}
}
// Parse integer
if let Ok(value) = Self::from_str_radix(s, 10) {
return value;
} else {
panic!("Syntax Error");
}
}
2021-06-04 22:05:48 +10:00
}
2021-09-13 03:43:17 +10:00
#[test]
fn rounding() {
2021-09-13 04:31:25 +10:00
Fixed::set_dps(5);
2021-09-13 03:43:17 +10:00
2021-09-13 04:31:25 +10:00
let mut x = Fixed::parse("55.550"); x.floor_mut(2); assert_eq!(x, Fixed::parse("55.55"));
let mut x = Fixed::parse("55.552"); x.floor_mut(2); assert_eq!(x, Fixed::parse("55.55"));
let mut x = Fixed::parse("55.555"); x.floor_mut(2); assert_eq!(x, Fixed::parse("55.55"));
let mut x = Fixed::parse("55.557"); x.floor_mut(2); assert_eq!(x, Fixed::parse("55.55"));
2021-09-13 03:43:17 +10:00
2021-09-13 04:31:25 +10:00
let mut x = Fixed::parse("55.550"); x.ceil_mut(2); assert_eq!(x, Fixed::parse("55.55"));
let mut x = Fixed::parse("55.552"); x.ceil_mut(2); assert_eq!(x, Fixed::parse("55.56"));
let mut x = Fixed::parse("55.555"); x.ceil_mut(2); assert_eq!(x, Fixed::parse("55.56"));
let mut x = Fixed::parse("55.557"); x.ceil_mut(2); assert_eq!(x, Fixed::parse("55.56"));
2021-09-13 03:43:17 +10:00
2021-09-13 04:31:25 +10:00
let mut x = Fixed::parse("55.550"); x.round_mut(2); assert_eq!(x, Fixed::parse("55.55"));
let mut x = Fixed::parse("55.552"); x.round_mut(2); assert_eq!(x, Fixed::parse("55.55"));
let mut x = Fixed::parse("55.555"); x.round_mut(2); assert_eq!(x, Fixed::parse("55.56"));
let mut x = Fixed::parse("55.557"); x.round_mut(2); assert_eq!(x, Fixed::parse("55.56"));
2021-09-13 03:43:17 +10:00
}
2021-06-04 22:05:48 +10:00
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() }
}
2021-09-14 02:23:51 +10:00
#[test]
fn assign() {
Fixed::set_dps(2);
let a = Fixed::parse("123.45");
let b = Fixed::parse("678.90");
let mut x = a.clone(); x.assign(b.clone()); assert_eq!(x, b);
let mut x = a.clone(); x.assign(&b); assert_eq!(x, b);
}
2021-06-04 22:05:48 +10:00
impl From<usize> for Fixed {
fn from(n: usize) -> Self { Self(IBig::from(n) * get_factor()) }
}
2021-06-16 17:20:29 +10:00
// TODO: Fix rounding
2021-06-04 22:05:48 +10:00
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();
}
2021-06-04 22:05:48 +10:00
//let should_add_minus = (self.0 < IBig::zero()) && result != "0";
let should_add_minus = self.0 < IBig::zero();
2021-06-04 22:05:48 +10:00
// 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);
}
}
2021-09-14 02:23:51 +10:00
#[test]
fn display_debug() {
Fixed::set_dps(2);
let x = Fixed::parse("123.4"); assert_eq!(format!("{}", x), "123.40");
let x = Fixed::parse("123.4"); assert_eq!(format!("{:?}", x), "Fixed(12340)");
}
2021-06-04 22:05:48 +10:00
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;
2021-06-16 13:00:54 +10:00
fn add(self, rhs: Self) -> Self::Output { Self(self.0 + rhs.0) }
2021-06-04 22:05:48 +10:00
}
impl ops::Sub for Fixed {
type Output = Self;
2021-09-13 03:43:17 +10:00
fn sub(self, rhs: Self) -> Self::Output { Self(self.0 - rhs.0) }
2021-06-04 22:05:48 +10:00
}
impl ops::Mul for Fixed {
type Output = Self;
fn mul(self, rhs: Self) -> Self::Output { Self(self.0 * rhs.0 / get_factor()) }
2021-06-04 22:05:48 +10:00
}
impl ops::Div for Fixed {
type Output = Self;
2021-06-16 13:00:54 +10:00
fn div(self, rhs: Self) -> Self::Output { Self(self.0 * get_factor() / rhs.0) }
2021-06-04 22:05:48 +10:00
}
impl ops::Rem for Fixed {
type Output = Self;
2021-09-14 02:23:51 +10:00
fn rem(self, rhs: Self) -> Self::Output { Self(self.0 % rhs.0) }
2021-06-04 22:05:48 +10:00
}
2021-09-13 03:43:17 +10:00
#[test]
fn arith_owned_owned() {
Fixed::set_dps(2);
let a = Fixed::parse("123.45");
let b = Fixed::parse("678.90");
assert_eq!(a.clone() + b.clone(), Fixed::parse("802.35"));
assert_eq!(a.clone() - b.clone(), Fixed::parse("-555.45"));
assert_eq!(a.clone() * b.clone(), Fixed::parse("83810.20")); // = 83810.205 rounds to 83810.20
assert_eq!(a.clone() / b.clone(), Fixed::parse("0.18"));
2021-09-14 02:23:51 +10:00
assert_eq!(b.clone() % a.clone(), Fixed::parse("61.65"));
2021-09-13 03:43:17 +10:00
}
2021-06-04 22:05:48 +10:00
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;
2021-06-07 20:52:18 +10:00
fn sub(self, rhs: &Self) -> Self::Output { Self(self.0 - &rhs.0) }
2021-06-04 22:05:48 +10:00
}
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;
2021-09-14 02:23:51 +10:00
fn rem(self, rhs: &Self) -> Self::Output { Self(self.0 % &rhs.0) }
2021-06-04 22:05:48 +10:00
}
2021-09-13 03:43:17 +10:00
#[test]
fn arith_owned_ref() {
Fixed::set_dps(2);
let a = Fixed::parse("123.45");
let b = Fixed::parse("678.90");
assert_eq!(a.clone() + &b, Fixed::parse("802.35"));
assert_eq!(a.clone() - &b, Fixed::parse("-555.45"));
assert_eq!(a.clone() * &b, Fixed::parse("83810.20"));
assert_eq!(a.clone() / &b, Fixed::parse("0.18"));
2021-09-14 02:23:51 +10:00
assert_eq!(b.clone() % &a, Fixed::parse("61.65"));
2021-09-13 03:43:17 +10:00
}
2021-06-04 22:05:48 +10:00
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 {
2021-09-14 02:23:51 +10:00
fn rem_assign(&mut self, rhs: Self) { self.0 %= rhs.0; }
2021-06-04 22:05:48 +10:00
}
2021-09-13 03:43:17 +10:00
#[test]
fn arithassign_owned() {
Fixed::set_dps(2);
let a = Fixed::parse("123.45");
let b = Fixed::parse("678.90");
let mut x = a.clone(); x += b.clone(); assert_eq!(x, Fixed::parse("802.35"));
let mut x = a.clone(); x -= b.clone(); assert_eq!(x, Fixed::parse("-555.45"));
let mut x = a.clone(); x *= b.clone(); assert_eq!(x, Fixed::parse("83810.20"));
let mut x = a.clone(); x /= b.clone(); assert_eq!(x, Fixed::parse("0.18"));
2021-09-14 02:23:51 +10:00
let mut x = b.clone(); x %= a.clone(); assert_eq!(x, Fixed::parse("61.65"));
2021-09-13 03:43:17 +10:00
}
2021-06-04 22:05:48 +10:00
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;
2021-06-04 22:05:48 +10:00
}
}
impl ops::RemAssign<&Self> for Fixed {
2021-09-14 02:23:51 +10:00
fn rem_assign(&mut self, rhs: &Self) { self.0 %= &rhs.0; }
2021-06-04 22:05:48 +10:00
}
2021-09-13 03:43:17 +10:00
#[test]
fn arithassign_ref() {
Fixed::set_dps(2);
let a = Fixed::parse("123.45");
let b = Fixed::parse("678.90");
let mut x = a.clone(); x += &b; assert_eq!(x, Fixed::parse("802.35"));
let mut x = a.clone(); x -= &b; assert_eq!(x, Fixed::parse("-555.45"));
let mut x = a.clone(); x *= &b; assert_eq!(x, Fixed::parse("83810.20"));
let mut x = a.clone(); x /= &b; assert_eq!(x, Fixed::parse("0.18"));
2021-09-14 02:23:51 +10:00
let mut x = b.clone(); x %= &a; assert_eq!(x, Fixed::parse("61.65"));
2021-09-13 03:43:17 +10:00
}
2021-06-04 22:05:48 +10:00
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;
2021-06-09 20:09:20 +10:00
fn add(self, rhs: Self) -> Self::Output { Fixed(&self.0 + &rhs.0) }
2021-06-04 22:05:48 +10:00
}
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;
2021-06-16 13:00:54 +10:00
fn mul(self, rhs: Self) -> Self::Output { Fixed(&self.0 * &rhs.0 / get_factor()) }
2021-06-04 22:05:48 +10:00
}
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;
2021-09-14 02:23:51 +10:00
fn rem(self, rhs: Self) -> Self::Output { Fixed(&self.0 % &rhs.0) }
2021-06-04 22:05:48 +10:00
}
2021-09-13 03:43:17 +10:00
#[test]
fn arith_ref_ref() {
Fixed::set_dps(2);
let a = Fixed::parse("123.45");
let b = Fixed::parse("678.90");
assert_eq!(&a + &b, Fixed::parse("802.35"));
assert_eq!(&a - &b, Fixed::parse("-555.45"));
assert_eq!(&a * &b, Fixed::parse("83810.20"));
assert_eq!(&a / &b, Fixed::parse("0.18"));
2021-09-14 02:23:51 +10:00
assert_eq!(&b % &a, Fixed::parse("61.65"));
2021-09-13 03:43:17 +10:00
}
2021-06-04 22:05:48 +10:00
/*
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 {
}
*/