diff --git a/pallas-math/Cargo.toml b/pallas-math/Cargo.toml index c214d9a20..b52238856 100644 --- a/pallas-math/Cargo.toml +++ b/pallas-math/Cargo.toml @@ -12,8 +12,9 @@ authors = ["Andrew Westberg "] exclude = ["tests/data/*"] [dependencies] -dashu-int = "0.4.1" -dashu-base = "0.4.1" +num-integer = "0.1" +num-bigint = "0.4" +num-traits = "0.2" regex = "1.10.5" thiserror = "1.0.61" diff --git a/pallas-math/src/lib.rs b/pallas-math/src/lib.rs index bac9cb091..4c75768a4 100644 --- a/pallas-math/src/lib.rs +++ b/pallas-math/src/lib.rs @@ -1,2 +1,2 @@ pub mod math; -pub mod math_dashu; +pub mod math_bigint; diff --git a/pallas-math/src/math.rs b/pallas-math/src/math.rs index 369a44ae4..d2b0ce6eb 100644 --- a/pallas-math/src/math.rs +++ b/pallas-math/src/math.rs @@ -7,7 +7,7 @@ use std::ops::{Div, Mul, Neg, Sub}; use std::sync::LazyLock; use thiserror::Error; -pub type FixedDecimal = crate::math_dashu::Decimal; +pub type FixedDecimal = crate::math_bigint::Decimal; pub static ZERO: LazyLock = LazyLock::new(|| FixedDecimal::from(0u64)); pub static MINUS_ONE: LazyLock = LazyLock::new(|| FixedDecimal::from(-1i64)); @@ -95,7 +95,6 @@ pub struct ExpCmpOrdering { #[cfg(test)] mod tests { use super::*; - use dashu_base::Abs; use proptest::prelude::Strategy; use proptest::proptest; use std::fs::File; diff --git a/pallas-math/src/math_dashu.rs b/pallas-math/src/math_bigint.rs similarity index 80% rename from pallas-math/src/math_dashu.rs rename to pallas-math/src/math_bigint.rs index 560b30af3..5021367c5 100644 --- a/pallas-math/src/math_dashu.rs +++ b/pallas-math/src/math_bigint.rs @@ -3,8 +3,9 @@ */ use crate::math::{Error, ExpCmpOrdering, ExpOrdering, FixedPrecision, DEFAULT_PRECISION}; -use dashu_base::{Abs, DivRem, Sign}; -use dashu_int::{IBig, UBig}; +use num_bigint::{BigInt, BigUint}; +use num_integer::Integer; +use num_traits::{One, Signed, Zero}; use regex::Regex; use std::cmp::Ordering; use std::fmt::{Display, Formatter}; @@ -15,8 +16,8 @@ use std::sync::LazyLock; #[derive(Debug, Clone)] pub struct Decimal { precision: u64, - precision_multiplier: IBig, - data: IBig, + precision_multiplier: BigInt, + data: BigInt, } impl PartialEq for Decimal { @@ -55,7 +56,7 @@ impl Display for Decimal { impl From for Decimal { fn from(n: u64) -> Self { let mut result = Decimal::new(DEFAULT_PRECISION); - result.data = IBig::from(n) * &result.precision_multiplier; + result.data = BigInt::from(n) * &result.precision_multiplier; result } } @@ -63,46 +64,46 @@ impl From for Decimal { impl From for Decimal { fn from(n: i64) -> Self { let mut result = Decimal::new(DEFAULT_PRECISION); - result.data = IBig::from(n) * &result.precision_multiplier; + result.data = BigInt::from(n) * &result.precision_multiplier; result } } -impl From for Decimal { - fn from(n: IBig) -> Self { +impl From for Decimal { + fn from(n: BigInt) -> Self { let mut result = Decimal::new(DEFAULT_PRECISION); result.data = n * &result.precision_multiplier; result } } -impl From<&IBig> for Decimal { - fn from(n: &IBig) -> Self { +impl From<&BigInt> for Decimal { + fn from(n: &BigInt) -> Self { let mut result = Decimal::new(DEFAULT_PRECISION); result.data = n * &result.precision_multiplier; result } } -impl From for Decimal { - fn from(n: UBig) -> Self { +impl From for Decimal { + fn from(n: BigUint) -> Self { let mut result = Decimal::new(DEFAULT_PRECISION); - result.data = IBig::from(n) * &result.precision_multiplier; + result.data = BigInt::from(n) * &result.precision_multiplier; result } } -impl From<&UBig> for Decimal { - fn from(n: &UBig) -> Self { +impl From<&BigUint> for Decimal { + fn from(n: &BigUint) -> Self { let mut result = Decimal::new(DEFAULT_PRECISION); - result.data = IBig::from(n.clone()) * &result.precision_multiplier; + result.data = BigInt::from(n.clone()) * &result.precision_multiplier; result } } impl From<&[u8]> for Decimal { fn from(n: &[u8]) -> Self { - Decimal::from(UBig::from_be_bytes(n)) + Decimal::from(BigUint::from_bytes_be(n)) } } @@ -127,27 +128,14 @@ impl Neg for &Decimal { } } -impl Abs for Decimal { - type Output = Self; - - fn abs(self) -> Self::Output { +impl Decimal { + pub fn abs(&self) -> Decimal { let mut result = Decimal::new(self.precision); result.data = self.data.abs(); result } } -// Implement Abs for a reference to Decimal -impl Abs for &Decimal { - type Output = Decimal; - - fn abs(self) -> Self::Output { - let mut result = Decimal::new(self.precision); - result.data = (&self.data).abs(); - result - } -} - impl Mul for Decimal { type Output = Self; @@ -288,9 +276,10 @@ impl<'b> AddAssign<&'b Decimal> for &mut Decimal { impl FixedPrecision for Decimal { fn new(precision: u64) -> Self { - let mut precision_multiplier = IBig::from(10); - precision_multiplier = precision_multiplier.pow(precision as usize); - let data = IBig::from(0); + let mut precision_multiplier = BigInt::from(10); + precision_multiplier = precision_multiplier + .pow(u32::try_from(precision).expect("precision too large for u32")); + let data = BigInt::zero(); Decimal { precision, precision_multiplier, @@ -307,7 +296,7 @@ impl FixedPrecision for Decimal { } let mut decimal = Decimal::new(precision); - decimal.data = IBig::from_str(s).unwrap(); + decimal.data = BigInt::from_str(s).unwrap(); Ok(decimal) } @@ -351,10 +340,10 @@ impl FixedPrecision for Decimal { fn round(&self) -> Self { let mut result = self.clone(); - let half = &self.precision_multiplier / IBig::from(2); + let half = &self.precision_multiplier / BigInt::from(2); let remainder = &self.data % &self.precision_multiplier; if (&remainder).abs() >= half { - if self.data.sign() == Sign::Negative { + if self.data.is_negative() { result.data -= &self.precision_multiplier + remainder; } else { result.data += &self.precision_multiplier - remainder; @@ -368,7 +357,7 @@ impl FixedPrecision for Decimal { fn floor(&self) -> Self { let mut result = self.clone(); let remainder = &self.data % &self.precision_multiplier; - if self.data.sign() == Sign::Negative && remainder != ZERO.value { + if self.data.is_negative() && !remainder.is_zero() { result.data -= &self.precision_multiplier; } result.data -= remainder; @@ -378,10 +367,13 @@ impl FixedPrecision for Decimal { fn ceil(&self) -> Self { let mut result = self.clone(); let remainder = &self.data % &self.precision_multiplier; - if self.data.sign() == Sign::Positive && remainder != ZERO.value { + if remainder.is_zero() { + return result; + } + result.data -= &remainder; + if self.data.is_positive() { result.data += &self.precision_multiplier; } - result.data -= remainder; result } @@ -392,7 +384,7 @@ impl FixedPrecision for Decimal { } } -fn print_fixedp(n: &IBig, precision: &IBig, width: usize) -> String { +fn print_fixedp(n: &BigInt, precision: &BigInt, width: usize) -> String { let (mut temp_q, mut temp_r) = n.div_rem(precision); let is_negative_q = temp_q < ZERO.value; @@ -422,11 +414,11 @@ fn print_fixedp(n: &IBig, precision: &IBig, width: usize) -> String { } struct Constant { - value: IBig, + value: BigInt, } impl Constant { - pub fn new(init: fn() -> IBig) -> Constant { + pub fn new(init: fn() -> BigInt) -> Constant { Constant { value: init() } } } @@ -435,25 +427,28 @@ unsafe impl Sync for Constant {} unsafe impl Send for Constant {} static DIGITS_REGEX: LazyLock = LazyLock::new(|| Regex::new(r"^-?\d+$").unwrap()); -static TEN: LazyLock = LazyLock::new(|| Constant::new(|| IBig::from(10))); +static TEN: LazyLock = LazyLock::new(|| Constant::new(|| BigInt::from(10))); static PRECISION: LazyLock = LazyLock::new(|| Constant::new(|| TEN.value.clone().pow(34))); static EPS: LazyLock = LazyLock::new(|| Constant::new(|| TEN.value.clone().pow(34 - 24))); static ONE: LazyLock = - LazyLock::new(|| Constant::new(|| IBig::from(1) * &PRECISION.value)); -static ZERO: LazyLock = LazyLock::new(|| Constant::new(|| IBig::from(0))); + LazyLock::new(|| Constant::new(|| BigInt::one() * &PRECISION.value)); +static ZERO: LazyLock = LazyLock::new(|| Constant::new(|| BigInt::from(0))); static E: LazyLock = LazyLock::new(|| { Constant::new(|| { - let mut e = IBig::from(0); + let mut e = BigInt::zero(); ref_exp(&mut e, &ONE.value); e }) }); -fn div_round_ceil(x: &IBig, y: &IBig) -> IBig { +fn div_round_ceil(x: &BigInt, y: &BigInt) -> BigInt { + if x.is_zero() { + return BigInt::zero(); + } let (q, r) = x.div_rem(y); - if q.sign() == Sign::Positive && r != IBig::ZERO { - q + IBig::ONE + if !r.is_zero() && x.is_positive() { + q + BigInt::one() } else { q } @@ -461,7 +456,7 @@ fn div_round_ceil(x: &IBig, y: &IBig) -> IBig { /// Entry point for 'exp' approximation. First does the scaling of 'x' to [0,1] /// and then calls the continued fraction approximation function. -fn ref_exp(rop: &mut IBig, x: &IBig) -> i32 { +fn ref_exp(rop: &mut BigInt, x: &BigInt) -> i32 { let mut iterations = 0; match x.cmp(&ZERO.value) { Ordering::Equal => { @@ -469,8 +464,8 @@ fn ref_exp(rop: &mut IBig, x: &IBig) -> i32 { rop.clone_from(&ONE.value); } Ordering::Less => { - let x_ = -x; - let mut temp = IBig::from(0); + let x_ = x.neg(); + let mut temp = BigInt::zero(); iterations = ref_exp(&mut temp, &x_); // rop = 1 / temp div(rop, &ONE.value, &temp); @@ -491,15 +486,15 @@ fn ref_exp(rop: &mut IBig, x: &IBig) -> i32 { /// Division with quotent and remainder #[inline] -fn div_qr(q: &mut IBig, r: &mut IBig, x: &IBig, y: &IBig) { +fn div_qr(q: &mut BigInt, r: &mut BigInt, x: &BigInt, y: &BigInt) { (*q, *r) = x.div_rem(y); } /// Division -pub fn div(rop: &mut IBig, x: &IBig, y: &IBig) { - let mut temp_q = IBig::from(0); - let mut temp_r = IBig::from(0); - let mut temp: IBig; +pub fn div(rop: &mut BigInt, x: &BigInt, y: &BigInt) { + let mut temp_q = BigInt::zero(); + let mut temp_r = BigInt::zero(); + let mut temp: BigInt; div_qr(&mut temp_q, &mut temp_r, x, y); temp = &temp_q * &PRECISION.value; @@ -512,7 +507,7 @@ pub fn div(rop: &mut IBig, x: &IBig, y: &IBig) { } /// Taylor / MacLaurin series approximation -fn mp_exp_taylor(rop: &mut IBig, max_n: i32, x: &IBig, epsilon: &IBig) -> i32 { +fn mp_exp_taylor(rop: &mut BigInt, max_n: i32, x: &BigInt, epsilon: &BigInt) -> i32 { let mut divisor = ONE.value.clone(); let mut last_x = ONE.value.clone(); rop.clone_from(&ONE.value); @@ -536,27 +531,27 @@ fn mp_exp_taylor(rop: &mut IBig, max_n: i32, x: &IBig, epsilon: &IBig) -> i32 { n } -pub(crate) fn scale(rop: &mut IBig) { - let mut temp = IBig::from(0); - let mut a = IBig::from(0); +pub(crate) fn scale(rop: &mut BigInt) { + let mut temp = BigInt::zero(); + let mut a = BigInt::zero(); div_qr(&mut a, &mut temp, rop, &PRECISION.value); if *rop < ZERO.value && temp != ZERO.value { - a -= IBig::ONE; + a -= BigInt::one(); } *rop = a; } /// Integer power internal function -fn ipow_(rop: &mut IBig, x: &IBig, n: i64) { +fn ipow_(rop: &mut BigInt, x: &BigInt, n: i64) { if n == 0 { rop.clone_from(&ONE.value); } else if n % 2 == 0 { - let mut res = IBig::from(0); + let mut res = BigInt::zero(); ipow_(&mut res, x, n / 2); *rop = &res * &res; scale(rop); } else { - let mut res = IBig::from(0); + let mut res = BigInt::zero(); ipow_(&mut res, x, n - 1); *rop = res * x; scale(rop); @@ -564,9 +559,9 @@ fn ipow_(rop: &mut IBig, x: &IBig, n: i64) { } /// Integer power -fn ipow(rop: &mut IBig, x: &IBig, n: i64) { +fn ipow(rop: &mut BigInt, x: &BigInt, n: i64) { if n < 0 { - let mut temp = IBig::from(0); + let mut temp = BigInt::zero(); ipow_(&mut temp, x, -n); div(rop, &ONE.value, &temp); } else { @@ -578,32 +573,32 @@ fn ipow(rop: &mut IBig, x: &IBig, n: i64) { /// maximum of 'maxN' iterations or until the absolute difference between two /// succeeding convergents is smaller than 'eps'. Assumes 'x' to be within /// [1,e). -fn mp_ln_n(rop: &mut IBig, max_n: i32, x: &IBig, epsilon: &IBig) { - let mut ba: IBig; - let mut aa: IBig; - let mut ab: IBig; - let mut bb: IBig; - let mut a_: IBig; - let mut b_: IBig; - let mut diff: IBig; - let mut convergent: IBig = IBig::from(0); - let mut last: IBig = IBig::from(0); +fn mp_ln_n(rop: &mut BigInt, max_n: i32, x: &BigInt, epsilon: &BigInt) { + let mut ba: BigInt; + let mut aa: BigInt; + let mut ab: BigInt; + let mut bb: BigInt; + let mut a_: BigInt; + let mut b_: BigInt; + let mut diff: BigInt; + let mut convergent: BigInt = BigInt::zero(); + let mut last: BigInt = BigInt::zero(); let mut first = true; let mut n = 1; - let mut a: IBig; + let mut a: BigInt; let mut b = ONE.value.clone(); let mut an_m2 = ONE.value.clone(); - let mut bn_m2 = IBig::from(0); - let mut an_m1 = IBig::from(0); + let mut bn_m2 = BigInt::zero(); + let mut an_m1 = BigInt::zero(); let mut bn_m1 = ONE.value.clone(); let mut curr_a = 1; while n <= max_n + 2 { let curr_a_2 = curr_a * curr_a; - a = x * IBig::from(curr_a_2); + a = x * BigInt::from(curr_a_2); if n > 1 && n % 2 == 1 { curr_a += 1; } @@ -645,9 +640,9 @@ fn mp_ln_n(rop: &mut IBig, max_n: i32, x: &IBig, epsilon: &IBig) { *rop = convergent; } -fn find_e(x: &IBig) -> i64 { - let mut x_: IBig = IBig::from(0); - let mut x__: IBig = E.value.clone(); +fn find_e(x: &BigInt) -> i64 { + let mut x_: BigInt = BigInt::zero(); + let mut x__: BigInt = E.value.clone(); div(&mut x_, &ONE.value, &E.value); @@ -680,16 +675,16 @@ fn find_e(x: &IBig) -> i64 { /// Entry point for 'ln' approximation. First does the necessary scaling, and /// then calls the continued fraction calculation. For any value outside the /// domain, i.e., 'x in (-inf,0]', the function returns '-INFINITY'. -fn ref_ln(rop: &mut IBig, x: &IBig) -> bool { - let mut factor = IBig::from(0); - let mut x_ = IBig::from(0); +fn ref_ln(rop: &mut BigInt, x: &BigInt) -> bool { + let mut factor = BigInt::zero(); + let mut x_ = BigInt::zero(); if x <= &ZERO.value { return false; } let n = find_e(x); - *rop = IBig::from(n); + *rop = BigInt::from(n); *rop = &*rop * &PRECISION.value; ref_exp(&mut factor, rop); @@ -704,11 +699,11 @@ fn ref_ln(rop: &mut IBig, x: &IBig) -> bool { true } -fn ref_pow(rop: &mut IBig, base: &IBig, exponent: &IBig) { +fn ref_pow(rop: &mut BigInt, base: &BigInt, exponent: &BigInt) { /* x^y = exp(y * ln x) */ - let mut tmp: IBig = IBig::from(0); + let mut tmp: BigInt = BigInt::zero(); - if exponent == &ZERO.value || base == &ONE.value { + if exponent.is_zero() || base == &ONE.value { // any base to the power of zero is one, or 1 to any power is 1 *rop = ONE.value.clone(); return; @@ -718,26 +713,26 @@ fn ref_pow(rop: &mut IBig, base: &IBig, exponent: &IBig) { *rop = base.clone(); return; } - if base == &ZERO.value && exponent > &ZERO.value { + if base.is_zero() && exponent.is_positive() { // zero to any positive power is zero - *rop = &ZERO.value * &PRECISION.value; + *rop = &BigInt::zero() * &PRECISION.value; return; } - if base == &ZERO.value && exponent < &ZERO.value { + if base.is_zero() && exponent.is_negative() { panic!("zero to a negative power is undefined"); } - if base < &ZERO.value { + if base.is_negative() { // negate the base and calculate the power let neg_base = base.neg(); let ref_ln = ref_ln(&mut tmp, &neg_base); debug_assert!(ref_ln); tmp *= exponent; scale(&mut tmp); - let mut tmp_rop = IBig::from(0); + let mut tmp_rop = BigInt::zero(); ref_exp(&mut tmp_rop, &tmp); - let (_, rem) = (exponent / &PRECISION.value).div_rem(&IBig::from(2)); + let (_, rem) = (exponent / &PRECISION.value).div_rem(&BigInt::from(2)); // check if rem is even - *rop = if rem == IBig::ZERO { tmp_rop } else { -tmp_rop }; + *rop = if rem.is_zero() { tmp_rop } else { -tmp_rop }; } else { // base is positive, ref_ln result is valid let ref_ln = ref_ln(&mut tmp, base); @@ -759,20 +754,20 @@ fn ref_pow(rop: &mut IBig, base: &IBig, exponent: &IBig) { /// Lagrange remainder require knowledge of the maximum value to compute the /// maximal error of the remainder. fn ref_exp_cmp( - rop: &mut IBig, + rop: &mut BigInt, max_n: u64, - x: &IBig, + x: &BigInt, bound_x: i64, - compare: &IBig, + compare: &BigInt, ) -> ExpCmpOrdering { rop.clone_from(&ONE.value); let mut n = 0u64; - let mut divisor: IBig; - let mut next_x: IBig; - let mut error: IBig; - let mut upper: IBig; - let mut lower: IBig; - let mut error_term: IBig; + let mut divisor: BigInt; + let mut next_x: BigInt; + let mut error: BigInt; + let mut upper: BigInt; + let mut lower: BigInt; + let mut error_term: BigInt; divisor = ONE.value.clone(); error = x.clone(); @@ -792,7 +787,7 @@ fn ref_exp_cmp( scale(&mut error); let e2 = error.clone(); div(&mut error, &e2, &divisor); - error_term = &error * IBig::from(bound_x); + error_term = &error * BigInt::from(bound_x); *rop = &*rop + &next_x; /* compare is guaranteed to be above overall result */