Skip to main content

flow_value/
decimal.rs

1//! `Decimal`: every number with a finite decimal expansion (`data.md`,
2//! *Decimal*).
3
4use std::cmp::Ordering;
5use std::fmt;
6
7use num_bigint::BigInt;
8use num_integer::Integer;
9use num_traits::{One, Pow, Signed, Zero};
10
11use crate::error::Fault;
12use crate::int::Int;
13
14/// How many significant digits a quotient with no finite expansion keeps.
15pub const DIVISION_DIGITS: u32 = 34;
16
17/// An exact decimal number.
18///
19/// A value is `coefficient × 10^exponent`, held **normalized**: a nonzero
20/// coefficient is not a multiple of ten, and zero is `0 × 10^0`. That makes
21/// the representation a function of the number, so `1.50` and `1.5` are one
22/// value with one text and the derived equality and hash are the number's.
23/// Zero has no sign, because a `BigInt` zero has none.
24///
25/// Addition, subtraction, multiplication and negation are exact. Division is
26/// exact when the quotient has a finite expansion and is otherwise rounded to
27/// [`DIVISION_DIGITS`] significant digits, half to even.
28///
29/// The exponent is a signed 64-bit integer. A result whose exponent would leave
30/// that range is reported as [`Fault::Limit`]: the number exists, but this host
31/// cannot represent its scale.
32#[derive(Clone, PartialEq, Eq, Hash)]
33pub struct Decimal {
34    coefficient: BigInt,
35    exponent: i64,
36}
37
38impl Decimal {
39    /// Returns the number `coefficient × 10^exponent`, normalized.
40    ///
41    /// Normalizing raises the exponent once per trailing zero stripped, and a
42    /// number whose normalized exponent would pass `i64::MAX` is
43    /// [`Fault::Limit`].
44    pub fn new(coefficient: BigInt, exponent: i64) -> Result<Self, Fault> {
45        if coefficient.is_zero() {
46            return Ok(Decimal {
47                coefficient,
48                exponent: 0,
49            });
50        }
51        let digits = coefficient.magnitude().to_string();
52        let zeros = digits.len() - digits.trim_end_matches('0').len();
53        let raised = i64::try_from(zeros)
54            .ok()
55            .and_then(|zeros| exponent.checked_add(zeros))
56            .ok_or(Fault::Limit)?;
57        // The power of ten divided out is no longer than the coefficient.
58        let zeros = u64::try_from(zeros).expect("a count of digits fits 64 bits");
59        Ok(Decimal {
60            coefficient: coefficient / pow10(zeros),
61            exponent: raised,
62        })
63    }
64
65    /// Returns the number a decoded literal spells: ASCII digits with an
66    /// optional leading `-`, then optionally `.` and at least one digit.
67    ///
68    /// This reads what `flow-ir` writes for a decimal literal; `+`, an
69    /// exponent, separators and a bare point are refused.
70    pub fn parse(spelling: &str) -> Option<Self> {
71        let (whole, fraction) = spelling.split_once('.').unwrap_or((spelling, "0"));
72        Int::parse(whole)?;
73        if fraction.is_empty() || !fraction.bytes().all(|byte| byte.is_ascii_digit()) {
74            return None;
75        }
76        let coefficient = Int::parse(&format!("{whole}{fraction}"))?.into_bigint();
77        let exponent = i64::try_from(fraction.len()).ok()?;
78        Decimal::new(coefficient, -exponent).ok()
79    }
80
81    /// Returns the coefficient of the normalized form.
82    pub fn coefficient(&self) -> &BigInt {
83        &self.coefficient
84    }
85
86    /// Returns the power of ten of the normalized form.
87    pub fn exponent(&self) -> i64 {
88        self.exponent
89    }
90
91    /// Returns whether this is zero.
92    pub fn is_zero(&self) -> bool {
93        self.coefficient.is_zero()
94    }
95
96    /// Returns `self + other`, exactly.
97    ///
98    /// The two are aligned to the lower exponent first, so the sum of numbers
99    /// whose scales are far apart is written out in full, as exactness
100    /// requires.
101    pub fn add(&self, other: &Decimal) -> Result<Decimal, Fault> {
102        // Zero is `0 × 10^0`, whatever the other number's scale: adding it
103        // aligns nothing.
104        if self.is_zero() {
105            return Ok(other.clone());
106        }
107        if other.is_zero() {
108            return Ok(self.clone());
109        }
110        let exponent = self.exponent.min(other.exponent);
111        let left = &self.coefficient * pow10(self.exponent.abs_diff(exponent));
112        let right = &other.coefficient * pow10(other.exponent.abs_diff(exponent));
113        Decimal::new(left + right, exponent)
114    }
115
116    /// Returns `self - other`, exactly.
117    pub fn sub(&self, other: &Decimal) -> Result<Decimal, Fault> {
118        self.add(&other.neg())
119    }
120
121    /// Returns `-self`.
122    #[must_use]
123    pub fn neg(&self) -> Decimal {
124        Decimal {
125            coefficient: -&self.coefficient,
126            exponent: self.exponent,
127        }
128    }
129
130    /// Returns `self * other`, exactly.
131    pub fn mul(&self, other: &Decimal) -> Result<Decimal, Fault> {
132        let exponent = self
133            .exponent
134            .checked_add(other.exponent)
135            .ok_or(Fault::Limit)?;
136        Decimal::new(&self.coefficient * &other.coefficient, exponent)
137    }
138
139    /// Returns `self / divisor`.
140    ///
141    /// A quotient with a finite decimal expansion is exact. Any other is
142    /// rounded to [`DIVISION_DIGITS`] significant digits, half to even. A
143    /// quotient with no finite expansion is never exactly halfway between two
144    /// such neighbours — a halfway point has a finite expansion — so rounding
145    /// to nearest decides every case and the tie rule never has to choose.
146    pub fn div(&self, divisor: &Decimal) -> Result<Decimal, Fault> {
147        if divisor.is_zero() {
148            return Err(Fault::DivisionByZero);
149        }
150        let negative = self.coefficient.is_negative() != divisor.coefficient.is_negative();
151        let shared = self.coefficient.gcd(&divisor.coefficient);
152        let numerator = self.coefficient.abs() / &shared;
153        let denominator = divisor.coefficient.abs() / &shared;
154        let exponent = self
155            .exponent
156            .checked_sub(divisor.exponent)
157            .ok_or(Fault::Limit)?;
158
159        let (twos, fives, rest) = twos_and_fives(&denominator);
160        let (magnitude, exponent) = if rest.is_one() {
161            // `denominator` is 2^twos * 5^fives, so 10^k / denominator is
162            // whole for k = max(twos, fives).
163            let k = twos.max(fives);
164            let factor = pow10(k) / &denominator;
165            let shifted = exponent
166                .checked_sub(i64::try_from(k).map_err(|_| Fault::Limit)?)
167                .ok_or(Fault::Limit)?;
168            (numerator * factor, shifted)
169        } else {
170            rounded_quotient(&numerator, &denominator, exponent)?
171        };
172        let signed = if negative { -magnitude } else { magnitude };
173        Decimal::new(signed, exponent)
174    }
175
176    /// Returns the greatest integer not above this number.
177    pub fn floor(&self) -> Int {
178        if self.adjusted_exponent() <= 0 {
179            // Every digit is after the point, so the magnitude is below one.
180            // Answering here also keeps a tiny number such as `0.1` raised to a
181            // high power from building a power of ten as long as its exponent.
182            return Int::from(if self.coefficient.is_negative() {
183                BigInt::from(-1)
184            } else {
185                BigInt::zero()
186            });
187        }
188        let up = pow10(self.exponent.max(0).unsigned_abs());
189        let down = pow10(self.exponent.min(0).unsigned_abs());
190        Int::from((&self.coefficient * up).div_floor(&down))
191    }
192
193    /// Returns [`Decimal::floor`] when its magnitude takes at most `max_bits`
194    /// bits, and `None` otherwise.
195    ///
196    /// A number with `d` digits before the point has a floor of at least
197    /// `10^(d-1)`, which takes more than `d - 1` bits, so a number too large
198    /// is refused before its floor is built: a huge exponent costs nothing.
199    pub fn floor_within(&self, max_bits: u64) -> Option<Int> {
200        if self.adjusted_exponent() > i128::from(max_bits) {
201            return None;
202        }
203        let floor = self.floor();
204        (floor.bits() <= max_bits).then_some(floor)
205    }
206
207    /// Returns how many bytes this number's text takes, without writing it:
208    /// a number with a vast exponent has a text far too long to build.
209    pub fn text_len(&self) -> u128 {
210        let digits = u128::from(digit_count(&self.coefficient));
211        let places = u128::from(self.exponent.unsigned_abs());
212        let plain = if self.exponent >= 0 {
213            digits + places
214        } else if digits > places {
215            // The digits with a point among them.
216            digits + 1
217        } else {
218            // `0.`, zeros, and the digits.
219            places + 2
220        };
221        plain + u128::from(self.coefficient.is_negative())
222    }
223
224    /// The power of ten of this number's leading digit.
225    fn adjusted_exponent(&self) -> i128 {
226        i128::from(self.exponent) + i128::from(digit_count(&self.coefficient))
227    }
228}
229
230impl From<&Int> for Decimal {
231    fn from(value: &Int) -> Self {
232        Decimal::new(value.as_bigint().clone(), 0)
233            .expect("an integer has fewer trailing zeros than an exponent can count")
234    }
235}
236
237/// Numbers by value (`data.md`).
238impl Ord for Decimal {
239    fn cmp(&self, other: &Self) -> Ordering {
240        let by_sign = self.coefficient.sign().cmp(&other.coefficient.sign());
241        if by_sign != Ordering::Equal {
242            return by_sign;
243        }
244        // Same sign. The leading digit's place decides unless it is shared;
245        // then the digits, read from the leading one, are aligned, and since
246        // neither coefficient ends in a zero, the one that is a proper prefix
247        // of the other is the smaller. No power of ten is built, however far
248        // apart the two exponents are.
249        let magnitude = self
250            .adjusted_exponent()
251            .cmp(&other.adjusted_exponent())
252            .then_with(|| {
253                let left = self.coefficient.magnitude().to_string();
254                left.cmp(&other.coefficient.magnitude().to_string())
255            });
256        if self.coefficient.is_negative() {
257            magnitude.reverse()
258        } else {
259            magnitude
260        }
261    }
262}
263
264impl PartialOrd for Decimal {
265    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
266        Some(self.cmp(other))
267    }
268}
269
270/// The text form: plain decimal notation with no exponent, no trailing zero
271/// after the point, no point when the number is whole, `-` before a negative
272/// number and `0` for zero (`data.md`, *Decimal*).
273impl fmt::Display for Decimal {
274    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
275        let sign = if self.coefficient.is_negative() {
276            "-"
277        } else {
278            ""
279        };
280        let digits = self.coefficient.magnitude().to_string();
281        let Ok(places) = usize::try_from(-self.exponent) else {
282            // A non-negative exponent: the number is whole.
283            let zeros = "0".repeat(usize::try_from(self.exponent).unwrap_or(usize::MAX));
284            return write!(f, "{sign}{digits}{zeros}");
285        };
286        if places >= digits.len() {
287            let zeros = "0".repeat(places - digits.len());
288            write!(f, "{sign}0.{zeros}{digits}")
289        } else {
290            let (whole, fraction) = digits.split_at(digits.len() - places);
291            if fraction.is_empty() {
292                write!(f, "{sign}{whole}")
293            } else {
294                write!(f, "{sign}{whole}.{fraction}")
295            }
296        }
297    }
298}
299
300impl fmt::Debug for Decimal {
301    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
302        fmt::Display::fmt(self, f)
303    }
304}
305
306/// Returns `10^places`.
307///
308/// Every caller asks for a power no longer than a number it already holds or
309/// the result it must produce, so building it costs no more than the answer.
310fn pow10(places: u64) -> BigInt {
311    Pow::pow(BigInt::from(10), places)
312}
313
314/// Returns how many decimal digits `value`'s magnitude has; zero has one.
315fn digit_count(value: &BigInt) -> u64 {
316    u64::try_from(value.magnitude().to_string().len()).unwrap_or(u64::MAX)
317}
318
319/// Splits a positive `value` into `2^twos × 5^fives × rest`.
320fn twos_and_fives(value: &BigInt) -> (u64, u64, BigInt) {
321    let mut rest = value.clone();
322    let twos = rest.trailing_zeros().unwrap_or(0);
323    rest >>= twos;
324    let five = BigInt::from(5);
325    let mut fives = 0;
326    // A number has fewer factors of five than bits, which bounds the search
327    // even for an argument it was never meant to see, such as zero.
328    for _ in 0..value.bits() {
329        let (quotient, remainder) = rest.div_rem(&five);
330        if !remainder.is_zero() {
331            break;
332        }
333        rest = quotient;
334        fives += 1;
335    }
336    (twos, fives, rest)
337}
338
339/// Returns `numerator / denominator × 10^exponent` rounded to
340/// [`DIVISION_DIGITS`] significant digits, as a magnitude and an exponent.
341///
342/// Both operands are positive, and the quotient has no finite expansion.
343fn rounded_quotient(
344    numerator: &BigInt,
345    denominator: &BigInt,
346    exponent: i64,
347) -> Result<(BigInt, i64), Fault> {
348    let digits = i64::from(DIVISION_DIGITS);
349    let low = pow10(u64::from(DIVISION_DIGITS));
350    // A shift `s` with 10^34 ≤ ⌊numerator × 10^s / denominator⌋ < 10^35,
351    // that is one guard digit past the 34 kept. The first guess lands within
352    // one place below it.
353    let mut shift = digits + digits_i64(denominator) - digits_i64(numerator);
354    let mut guarded = shifted_quotient(numerator, denominator, shift);
355    if guarded < low {
356        shift += 1;
357        guarded = shifted_quotient(numerator, denominator, shift);
358    }
359    // The guard digit rounds: five or more goes up. Exactly five with nothing
360    // after it would be a tie, which a quotient with no finite expansion never
361    // is, so nothing after it is ever zero.
362    let rounded = (guarded + 5) / 10;
363    let exponent = exponent.checked_sub(shift - 1).ok_or(Fault::Limit)?;
364    Ok((rounded, exponent))
365}
366
367/// Returns `⌊numerator × 10^shift / denominator⌋` for a shift of either sign.
368fn shifted_quotient(numerator: &BigInt, denominator: &BigInt, shift: i64) -> BigInt {
369    let places = shift.unsigned_abs();
370    if shift >= 0 {
371        (numerator * pow10(places)) / denominator
372    } else {
373        numerator / (denominator * pow10(places))
374    }
375}
376
377fn digits_i64(value: &BigInt) -> i64 {
378    i64::try_from(digit_count(value)).unwrap_or(i64::MAX)
379}