Skip to main content

malachite_float/float/arithmetic/
round_to_integer.rs

1// Copyright © 2026 Mikhail Hogrefe
2//
3// Uses code adopted from the GNU MPFR Library.
4//
5//      Copyright © 1999-2025 Free Software Foundation, Inc.
6//
7// This file is part of Malachite.
8//
9// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
10// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
11// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
12use crate::emulate_float_to_float_fn;
13use malachite_base::num::basic::floats::PrimitiveFloat;
14
15use crate::Float;
16use crate::InnerFloat::{Finite, Infinity, Zero};
17use core::cmp::Ordering::{self, *};
18use malachite_base::num::arithmetic::traits::{IsPowerOf2, NegModPowerOf2, PowerOf2};
19use malachite_base::num::basic::integers::PrimitiveInt;
20use malachite_base::num::conversion::traits::{ExactFrom, IsInteger};
21use malachite_base::num::logic::traits::{LowMask, SignificantBits};
22use malachite_base::rounding_modes::RoundingMode::{self, *};
23use malachite_nz::natural::Natural;
24use malachite_nz::natural::arithmetic::float::round::{
25    limbs_float_round_to_integer, with_float_significand_limbs,
26};
27use malachite_nz::platform::Limb;
28
29// One with the given sign, at the given precision.
30fn signed_one(sign: bool, prec: u64) -> Float {
31    Float(Finite {
32        sign,
33        exponent: 1,
34        precision: prec,
35        significand: Natural::power_of_2(prec.neg_mod_power_of_2(Limb::LOG_WIDTH) + prec - 1),
36    })
37}
38
39impl Float {
40    // This is mpfr_rint from rint.c, MPFR 4.2.2, with the result's precision passed explicitly and
41    // with MPFR_RNDNA (round to nearest, ties away from zero) selected by the `ties_away` flag
42    // alongside `Nearest` rather than by a distinct rounding mode. Returns the rounded value, an
43    // `Ordering` comparing it to the exact input, and whether the input was an integer; the pair is
44    // a bijection with MPFR's refined ternary. The rounding is a single rounding to an integer
45    // representable at `prec`: no double rounding is performed.
46
47    // The maximum finite value with the given sign at the given precision, for overflow in the
48    // directed modes that cannot produce an infinity.
49    fn max_finite(sign: bool, prec: u64) -> Self {
50        Self(Finite {
51            sign,
52            exponent: Self::MAX_EXPONENT,
53            precision: prec,
54            significand: Natural::low_mask(prec) << prec.neg_mod_power_of_2(Limb::LOG_WIDTH),
55        })
56    }
57
58    fn round_to_integer_then_helper(
59        &self,
60        irm: RoundingMode,
61        ties_away: bool,
62        prec: u64,
63        rm: RoundingMode,
64    ) -> (Self, Ordering) {
65        if !matches!(self, Self(Finite { .. })) || self.is_integer() {
66            return Self::from_float_prec_round_ref(self, prec, rm);
67        }
68        // Rounding to an integer at self's own precision is exact, unless the carry at the maximum
69        // exponent overflows.
70        let t = self
71            .round_to_integer_helper(self.significant_bits(), irm, ties_away)
72            .0;
73        if let Self(Infinity { sign }) = t {
74            // The integer exceeds the exponent range; apply the final rounding mode's overflow
75            // behavior, as mpfr_overflow does.
76            let away = match rm {
77                Floor => !sign,
78                Ceiling => sign,
79                Down => false,
80                Up | Nearest => true,
81                Exact => panic!("overflow in round_to_integer_then with the Exact mode"),
82            };
83            return if away {
84                (t, if sign { Greater } else { Less })
85            } else {
86                (
87                    Self::max_finite(sign, prec),
88                    if sign { Less } else { Greater },
89                )
90            };
91        }
92        Self::from_float_prec_round(t, prec, rm)
93    }
94
95    /// Rounds a [`Float`] to an integer, representable at the specified precision, in the direction
96    /// given by the specified rounding mode. An [`Ordering`] comparing the result to the exact
97    /// input is also returned, along with a `bool` indicating whether the input was an integer. The
98    /// [`Float`] is taken by value.
99    ///
100    /// The result is produced by a single rounding to an integer representable at the target
101    /// precision: if the input's integer part needs more bits than the precision provides, no
102    /// intermediate integer is formed. For example, $10.5$ rounded to the nearest integer at a
103    /// precision of 2 bits is $12$: not first $10$, and then $10$ rounded again. The rounding mode
104    /// gives the integer-rounding direction: `Floor` and `Ceiling` are the floor and ceiling
105    /// functions, `Down` is truncation, `Up` rounds away from zero, and `Nearest` rounds to the
106    /// nearest integer with ties to even. `Exact` is not allowed.
107    ///
108    /// The pair of the [`Ordering`] and the `bool` carries the same information as `mpfr_rint`'s
109    /// ternary value: `(Equal, true)` means the input was an integer representable at the target
110    /// precision, returned unchanged; `(Less, true)` and `(Greater, true)` mean the input was an
111    /// integer that required rounding to fit the precision; `(Less, false)` and `(Greater, false)`
112    /// mean the input was not an integer. `(Equal, false)` cannot occur.
113    ///
114    /// `NaN`s, infinities, and zeros are returned unchanged with `Equal`; of these, only zeros are
115    /// considered integers.
116    ///
117    /// If rounding away from zero at the maximum exponent produces an integer too large to
118    /// represent, the result is $\pm\infty$.
119    ///
120    /// # Worst-case complexity
121    /// $T(n) = O(n)$
122    ///
123    /// $M(n) = O(n)$
124    ///
125    /// where $T$ is time, $M$ is additional memory, and $n$ is `max(prec,
126    /// self.significant_bits())`.
127    ///
128    /// # Panics
129    /// Panics if `prec` is zero or if `rm` is `Exact`.
130    ///
131    /// # Examples
132    /// ```
133    /// use core::cmp::Ordering::*;
134    /// use malachite_base::num::basic::traits::Two;
135    /// use malachite_base::rounding_modes::RoundingMode::*;
136    /// use malachite_float::Float;
137    ///
138    /// let x = Float::from(2.5f64);
139    /// assert_eq!(
140    ///     x.round_to_integer_prec_round_ref(4, Floor),
141    ///     (Float::TWO, Less, false)
142    /// );
143    /// assert_eq!(
144    ///     x.round_to_integer_prec_round_ref(4, Ceiling),
145    ///     (Float::from(3u32), Greater, false)
146    /// );
147    /// assert_eq!(
148    ///     x.round_to_integer_prec_round_ref(4, Nearest),
149    ///     (Float::TWO, Less, false)
150    /// );
151    ///
152    /// // A single rounding: the nearest integer to 10.5 representable at 2 bits is 12.
153    /// let x = Float::from(10.5f64);
154    /// assert_eq!(
155    ///     x.round_to_integer_prec_round_ref(2, Nearest),
156    ///     (Float::from(12u32), Greater, false)
157    /// );
158    ///
159    /// // 7 is an integer, but needs rounding to fit 2 bits.
160    /// let x = Float::from(7u32);
161    /// assert_eq!(
162    ///     x.round_to_integer_prec_round_ref(2, Nearest),
163    ///     (Float::from(8u32), Greater, true)
164    /// );
165    /// ```
166    #[inline]
167    pub fn round_to_integer_prec_round(
168        self,
169        prec: u64,
170        rm: RoundingMode,
171    ) -> (Self, Ordering, bool) {
172        self.round_to_integer_helper(prec, rm, false)
173    }
174
175    /// Rounds a [`Float`] to an integer, representable at the specified precision, in the direction
176    /// given by the specified rounding mode. An [`Ordering`] comparing the result to the exact
177    /// input is also returned, along with a `bool` indicating whether the input was an integer. The
178    /// [`Float`] is taken by reference.
179    ///
180    /// The result is produced by a single rounding to an integer representable at the target
181    /// precision: if the input's integer part needs more bits than the precision provides, no
182    /// intermediate integer is formed. For example, $10.5$ rounded to the nearest integer at a
183    /// precision of 2 bits is $12$: not first $10$, and then $10$ rounded again. The rounding mode
184    /// gives the integer-rounding direction: `Floor` and `Ceiling` are the floor and ceiling
185    /// functions, `Down` is truncation, `Up` rounds away from zero, and `Nearest` rounds to the
186    /// nearest integer with ties to even. `Exact` is not allowed.
187    ///
188    /// The pair of the [`Ordering`] and the `bool` carries the same information as `mpfr_rint`'s
189    /// ternary value: `(Equal, true)` means the input was an integer representable at the target
190    /// precision, returned unchanged; `(Less, true)` and `(Greater, true)` mean the input was an
191    /// integer that required rounding to fit the precision; `(Less, false)` and `(Greater, false)`
192    /// mean the input was not an integer. `(Equal, false)` cannot occur.
193    ///
194    /// `NaN`s, infinities, and zeros are returned unchanged with `Equal`; of these, only zeros are
195    /// considered integers.
196    ///
197    /// If rounding away from zero at the maximum exponent produces an integer too large to
198    /// represent, the result is $\pm\infty$.
199    ///
200    /// # Worst-case complexity
201    /// $T(n) = O(n)$
202    ///
203    /// $M(n) = O(n)$
204    ///
205    /// where $T$ is time, $M$ is additional memory, and $n$ is `max(prec,
206    /// self.significant_bits())`.
207    ///
208    /// # Panics
209    /// Panics if `prec` is zero or if `rm` is `Exact`.
210    ///
211    /// # Examples
212    /// ```
213    /// use core::cmp::Ordering::*;
214    /// use malachite_base::num::basic::traits::Two;
215    /// use malachite_base::rounding_modes::RoundingMode::*;
216    /// use malachite_float::Float;
217    ///
218    /// let x = Float::from(2.5f64);
219    /// assert_eq!(
220    ///     x.round_to_integer_prec_round_ref(4, Floor),
221    ///     (Float::TWO, Less, false)
222    /// );
223    /// assert_eq!(
224    ///     x.round_to_integer_prec_round_ref(4, Ceiling),
225    ///     (Float::from(3u32), Greater, false)
226    /// );
227    /// assert_eq!(
228    ///     x.round_to_integer_prec_round_ref(4, Nearest),
229    ///     (Float::TWO, Less, false)
230    /// );
231    ///
232    /// // A single rounding: the nearest integer to 10.5 representable at 2 bits is 12.
233    /// let x = Float::from(10.5f64);
234    /// assert_eq!(
235    ///     x.round_to_integer_prec_round_ref(2, Nearest),
236    ///     (Float::from(12u32), Greater, false)
237    /// );
238    ///
239    /// // 7 is an integer, but needs rounding to fit 2 bits.
240    /// let x = Float::from(7u32);
241    /// assert_eq!(
242    ///     x.round_to_integer_prec_round_ref(2, Nearest),
243    ///     (Float::from(8u32), Greater, true)
244    /// );
245    /// ```
246    #[inline]
247    pub fn round_to_integer_prec_round_ref(
248        &self,
249        prec: u64,
250        rm: RoundingMode,
251    ) -> (Self, Ordering, bool) {
252        self.round_to_integer_helper(prec, rm, false)
253    }
254
255    /// Rounds a [`Float`] to the nearest integer representable at the specified precision, with
256    /// ties going to even. An [`Ordering`] comparing the result to the exact input is also
257    /// returned, along with a `bool` indicating whether the input was an integer. The [`Float`] is
258    /// taken by value.
259    ///
260    /// The result is produced by a single rounding to an integer representable at the target
261    /// precision: if the input's integer part needs more bits than the precision provides, no
262    /// intermediate integer is formed. For example, $10.5$ rounded to the nearest integer at a
263    /// precision of 2 bits is $12$: not first $10$, and then $10$ rounded again.
264    ///
265    /// The pair of the [`Ordering`] and the `bool` carries the same information as `mpfr_rint`'s
266    /// ternary value: `(Equal, true)` means the input was an integer representable at the target
267    /// precision, returned unchanged; `(Less, true)` and `(Greater, true)` mean the input was an
268    /// integer that required rounding to fit the precision; `(Less, false)` and `(Greater, false)`
269    /// mean the input was not an integer. `(Equal, false)` cannot occur.
270    ///
271    /// `NaN`s, infinities, and zeros are returned unchanged with `Equal`; of these, only zeros are
272    /// considered integers.
273    ///
274    /// If rounding away from zero at the maximum exponent produces an integer too large to
275    /// represent, the result is $\pm\infty$.
276    ///
277    /// # Worst-case complexity
278    /// $T(n) = O(n)$
279    ///
280    /// $M(n) = O(n)$
281    ///
282    /// where $T$ is time, $M$ is additional memory, and $n$ is `max(prec,
283    /// self.significant_bits())`.
284    ///
285    /// # Panics
286    /// Panics if `prec` is zero.
287    ///
288    /// # Examples
289    /// ```
290    /// use core::cmp::Ordering::*;
291    /// use malachite_base::num::basic::traits::Two;
292    /// use malachite_float::Float;
293    ///
294    /// let x = Float::from(2.5f64);
295    /// assert_eq!(x.round_to_integer_prec_ref(4), (Float::TWO, Less, false));
296    /// assert_eq!(
297    ///     Float::from(4u32).round_to_integer_prec(2),
298    ///     (Float::from(4u32), Equal, true)
299    /// );
300    /// ```
301    #[inline]
302    pub fn round_to_integer_prec(self, prec: u64) -> (Self, Ordering, bool) {
303        self.round_to_integer_helper(prec, Nearest, false)
304    }
305
306    /// Rounds a [`Float`] to the nearest integer representable at the specified precision, with
307    /// ties going to even. An [`Ordering`] comparing the result to the exact input is also
308    /// returned, along with a `bool` indicating whether the input was an integer. The [`Float`] is
309    /// taken by reference.
310    ///
311    /// The result is produced by a single rounding to an integer representable at the target
312    /// precision: if the input's integer part needs more bits than the precision provides, no
313    /// intermediate integer is formed. For example, $10.5$ rounded to the nearest integer at a
314    /// precision of 2 bits is $12$: not first $10$, and then $10$ rounded again.
315    ///
316    /// The pair of the [`Ordering`] and the `bool` carries the same information as `mpfr_rint`'s
317    /// ternary value: `(Equal, true)` means the input was an integer representable at the target
318    /// precision, returned unchanged; `(Less, true)` and `(Greater, true)` mean the input was an
319    /// integer that required rounding to fit the precision; `(Less, false)` and `(Greater, false)`
320    /// mean the input was not an integer. `(Equal, false)` cannot occur.
321    ///
322    /// `NaN`s, infinities, and zeros are returned unchanged with `Equal`; of these, only zeros are
323    /// considered integers.
324    ///
325    /// If rounding away from zero at the maximum exponent produces an integer too large to
326    /// represent, the result is $\pm\infty$.
327    ///
328    /// # Worst-case complexity
329    /// $T(n) = O(n)$
330    ///
331    /// $M(n) = O(n)$
332    ///
333    /// where $T$ is time, $M$ is additional memory, and $n$ is `max(prec,
334    /// self.significant_bits())`.
335    ///
336    /// # Panics
337    /// Panics if `prec` is zero.
338    ///
339    /// # Examples
340    /// ```
341    /// use core::cmp::Ordering::*;
342    /// use malachite_base::num::basic::traits::Two;
343    /// use malachite_float::Float;
344    ///
345    /// let x = Float::from(2.5f64);
346    /// assert_eq!(x.round_to_integer_prec_ref(4), (Float::TWO, Less, false));
347    /// assert_eq!(
348    ///     Float::from(4u32).round_to_integer_prec(2),
349    ///     (Float::from(4u32), Equal, true)
350    /// );
351    /// ```
352    #[inline]
353    pub fn round_to_integer_prec_ref(&self, prec: u64) -> (Self, Ordering, bool) {
354        self.round_to_integer_helper(prec, Nearest, false)
355    }
356
357    /// Rounds a [`Float`] to an integer, representable at the input's own precision, in the
358    /// direction given by the specified rounding mode. An [`Ordering`] comparing the result to the
359    /// exact input is also returned, along with a `bool` indicating whether the input was an
360    /// integer. The [`Float`] is taken by value.
361    ///
362    /// The rounding mode gives the integer-rounding direction: `Floor` and `Ceiling` are the floor
363    /// and ceiling functions, `Down` is truncation, `Up` rounds away from zero, and `Nearest`
364    /// rounds to the nearest integer with ties to even. `Exact` is not allowed.
365    ///
366    /// The pair of the [`Ordering`] and the `bool` carries the same information as `mpfr_rint`'s
367    /// ternary value: `(Equal, true)` means the input was an integer representable at the target
368    /// precision, returned unchanged; `(Less, true)` and `(Greater, true)` mean the input was an
369    /// integer that required rounding to fit the precision; `(Less, false)` and `(Greater, false)`
370    /// mean the input was not an integer. `(Equal, false)` cannot occur.
371    ///
372    /// `NaN`s, infinities, and zeros are returned unchanged with `Equal`; of these, only zeros are
373    /// considered integers.
374    ///
375    /// If rounding away from zero at the maximum exponent produces an integer too large to
376    /// represent, the result is $\pm\infty$.
377    ///
378    /// # Worst-case complexity
379    /// $T(n) = O(n)$
380    ///
381    /// $M(n) = O(n)$
382    ///
383    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
384    ///
385    /// # Panics
386    /// Panics if `rm` is `Exact`.
387    ///
388    /// # Examples
389    /// ```
390    /// use core::cmp::Ordering::*;
391    /// use malachite_base::num::basic::traits::Two;
392    /// use malachite_base::rounding_modes::RoundingMode::*;
393    /// use malachite_float::Float;
394    ///
395    /// let x = Float::from(2.5f64);
396    /// assert_eq!(
397    ///     x.round_to_integer_round_ref(Ceiling),
398    ///     (Float::from(3u32), Greater, false)
399    /// );
400    /// assert_eq!(
401    ///     x.round_to_integer_round_ref(Floor),
402    ///     (Float::TWO, Less, false)
403    /// );
404    /// ```
405    #[inline]
406    pub fn round_to_integer_round(self, rm: RoundingMode) -> (Self, Ordering, bool) {
407        self.round_to_integer_helper(self.significant_bits(), rm, false)
408    }
409
410    /// Rounds a [`Float`] to an integer, representable at the input's own precision, in the
411    /// direction given by the specified rounding mode. An [`Ordering`] comparing the result to the
412    /// exact input is also returned, along with a `bool` indicating whether the input was an
413    /// integer. The [`Float`] is taken by reference.
414    ///
415    /// The rounding mode gives the integer-rounding direction: `Floor` and `Ceiling` are the floor
416    /// and ceiling functions, `Down` is truncation, `Up` rounds away from zero, and `Nearest`
417    /// rounds to the nearest integer with ties to even. `Exact` is not allowed.
418    ///
419    /// The pair of the [`Ordering`] and the `bool` carries the same information as `mpfr_rint`'s
420    /// ternary value: `(Equal, true)` means the input was an integer representable at the target
421    /// precision, returned unchanged; `(Less, true)` and `(Greater, true)` mean the input was an
422    /// integer that required rounding to fit the precision; `(Less, false)` and `(Greater, false)`
423    /// mean the input was not an integer. `(Equal, false)` cannot occur.
424    ///
425    /// `NaN`s, infinities, and zeros are returned unchanged with `Equal`; of these, only zeros are
426    /// considered integers.
427    ///
428    /// If rounding away from zero at the maximum exponent produces an integer too large to
429    /// represent, the result is $\pm\infty$.
430    ///
431    /// # Worst-case complexity
432    /// $T(n) = O(n)$
433    ///
434    /// $M(n) = O(n)$
435    ///
436    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
437    ///
438    /// # Panics
439    /// Panics if `rm` is `Exact`.
440    ///
441    /// # Examples
442    /// ```
443    /// use core::cmp::Ordering::*;
444    /// use malachite_base::num::basic::traits::Two;
445    /// use malachite_base::rounding_modes::RoundingMode::*;
446    /// use malachite_float::Float;
447    ///
448    /// let x = Float::from(2.5f64);
449    /// assert_eq!(
450    ///     x.round_to_integer_round_ref(Ceiling),
451    ///     (Float::from(3u32), Greater, false)
452    /// );
453    /// assert_eq!(
454    ///     x.round_to_integer_round_ref(Floor),
455    ///     (Float::TWO, Less, false)
456    /// );
457    /// ```
458    #[inline]
459    pub fn round_to_integer_round_ref(&self, rm: RoundingMode) -> (Self, Ordering, bool) {
460        self.round_to_integer_helper(self.significant_bits(), rm, false)
461    }
462
463    /// Rounds a [`Float`] to the nearest integer representable at the input's own precision, with
464    /// ties going to even. An [`Ordering`] comparing the result to the exact input is also
465    /// returned, along with a `bool` indicating whether the input was an integer. The [`Float`] is
466    /// taken by value.
467    ///
468    /// The pair of the [`Ordering`] and the `bool` carries the same information as `mpfr_rint`'s
469    /// ternary value: `(Equal, true)` means the input was an integer representable at the target
470    /// precision, returned unchanged; `(Less, true)` and `(Greater, true)` mean the input was an
471    /// integer that required rounding to fit the precision; `(Less, false)` and `(Greater, false)`
472    /// mean the input was not an integer. `(Equal, false)` cannot occur.
473    ///
474    /// `NaN`s, infinities, and zeros are returned unchanged with `Equal`; of these, only zeros are
475    /// considered integers.
476    ///
477    /// If rounding away from zero at the maximum exponent produces an integer too large to
478    /// represent, the result is $\pm\infty$.
479    ///
480    /// # Worst-case complexity
481    /// $T(n) = O(n)$
482    ///
483    /// $M(n) = O(n)$
484    ///
485    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
486    ///
487    /// # Panics
488    /// Never panics.
489    ///
490    /// # Examples
491    /// ```
492    /// use core::cmp::Ordering::*;
493    /// use malachite_base::num::basic::traits::Two;
494    /// use malachite_float::Float;
495    ///
496    /// // ties to even
497    /// let x = Float::from(2.5f64);
498    /// assert_eq!(x.round_to_integer_ref(), (Float::TWO, Less, false));
499    /// ```
500    #[inline]
501    pub fn round_to_integer(self) -> (Self, Ordering, bool) {
502        self.round_to_integer_helper(self.significant_bits(), Nearest, false)
503    }
504
505    /// Rounds a [`Float`] to the nearest integer representable at the input's own precision, with
506    /// ties going to even. An [`Ordering`] comparing the result to the exact input is also
507    /// returned, along with a `bool` indicating whether the input was an integer. The [`Float`] is
508    /// taken by reference.
509    ///
510    /// The pair of the [`Ordering`] and the `bool` carries the same information as `mpfr_rint`'s
511    /// ternary value: `(Equal, true)` means the input was an integer representable at the target
512    /// precision, returned unchanged; `(Less, true)` and `(Greater, true)` mean the input was an
513    /// integer that required rounding to fit the precision; `(Less, false)` and `(Greater, false)`
514    /// mean the input was not an integer. `(Equal, false)` cannot occur.
515    ///
516    /// `NaN`s, infinities, and zeros are returned unchanged with `Equal`; of these, only zeros are
517    /// considered integers.
518    ///
519    /// If rounding away from zero at the maximum exponent produces an integer too large to
520    /// represent, the result is $\pm\infty$.
521    ///
522    /// # Worst-case complexity
523    /// $T(n) = O(n)$
524    ///
525    /// $M(n) = O(n)$
526    ///
527    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
528    ///
529    /// # Panics
530    /// Never panics.
531    ///
532    /// # Examples
533    /// ```
534    /// use core::cmp::Ordering::*;
535    /// use malachite_base::num::basic::traits::Two;
536    /// use malachite_float::Float;
537    ///
538    /// // ties to even
539    /// let x = Float::from(2.5f64);
540    /// assert_eq!(x.round_to_integer_ref(), (Float::TWO, Less, false));
541    /// ```
542    #[inline]
543    pub fn round_to_integer_ref(&self) -> (Self, Ordering, bool) {
544        self.round_to_integer_helper(self.significant_bits(), Nearest, false)
545    }
546
547    /// Rounds a [`Float`] to the nearest integer representable at the specified precision, with
548    /// ties going away from zero. An [`Ordering`] comparing the result to the exact input is also
549    /// returned, along with a `bool` indicating whether the input was an integer. The [`Float`] is
550    /// taken by value.
551    ///
552    /// The result is produced by a single rounding to an integer representable at the target
553    /// precision: if the input's integer part needs more bits than the precision provides, no
554    /// intermediate integer is formed. For example, $10.5$ rounded to the nearest integer at a
555    /// precision of 2 bits is $12$: not first $10$, and then $10$ rounded again. Ties round away
556    /// from zero, as in IEEE 754's roundTiesToAway and MPFR's `mpfr_round`; the other
557    /// integer-rounding directions are available through [`Float::round_to_integer_prec_round`].
558    ///
559    /// The pair of the [`Ordering`] and the `bool` carries the same information as `mpfr_rint`'s
560    /// ternary value: `(Equal, true)` means the input was an integer representable at the target
561    /// precision, returned unchanged; `(Less, true)` and `(Greater, true)` mean the input was an
562    /// integer that required rounding to fit the precision; `(Less, false)` and `(Greater, false)`
563    /// mean the input was not an integer. `(Equal, false)` cannot occur.
564    ///
565    /// `NaN`s, infinities, and zeros are returned unchanged with `Equal`; of these, only zeros are
566    /// considered integers.
567    ///
568    /// If rounding away from zero at the maximum exponent produces an integer too large to
569    /// represent, the result is $\pm\infty$.
570    ///
571    /// # Worst-case complexity
572    /// $T(n) = O(n)$
573    ///
574    /// $M(n) = O(n)$
575    ///
576    /// where $T$ is time, $M$ is additional memory, and $n$ is `max(prec,
577    /// self.significant_bits())`.
578    ///
579    /// # Panics
580    /// Panics if `prec` is zero.
581    ///
582    /// # Examples
583    /// ```
584    /// use core::cmp::Ordering::*;
585    /// use malachite_float::Float;
586    ///
587    /// // ties away from zero
588    /// let x = Float::from(2.5f64);
589    /// assert_eq!(
590    ///     x.round_to_integer_ties_away_prec_ref(4),
591    ///     (Float::from(3u32), Greater, false)
592    /// );
593    /// ```
594    #[inline]
595    pub fn round_to_integer_ties_away_prec(self, prec: u64) -> (Self, Ordering, bool) {
596        self.round_to_integer_helper(prec, Nearest, true)
597    }
598
599    /// Rounds a [`Float`] to the nearest integer representable at the specified precision, with
600    /// ties going away from zero. An [`Ordering`] comparing the result to the exact input is also
601    /// returned, along with a `bool` indicating whether the input was an integer. The [`Float`] is
602    /// taken by reference.
603    ///
604    /// The result is produced by a single rounding to an integer representable at the target
605    /// precision: if the input's integer part needs more bits than the precision provides, no
606    /// intermediate integer is formed. For example, $10.5$ rounded to the nearest integer at a
607    /// precision of 2 bits is $12$: not first $10$, and then $10$ rounded again. Ties round away
608    /// from zero, as in IEEE 754's roundTiesToAway and MPFR's `mpfr_round`; the other
609    /// integer-rounding directions are available through [`Float::round_to_integer_prec_round`].
610    ///
611    /// The pair of the [`Ordering`] and the `bool` carries the same information as `mpfr_rint`'s
612    /// ternary value: `(Equal, true)` means the input was an integer representable at the target
613    /// precision, returned unchanged; `(Less, true)` and `(Greater, true)` mean the input was an
614    /// integer that required rounding to fit the precision; `(Less, false)` and `(Greater, false)`
615    /// mean the input was not an integer. `(Equal, false)` cannot occur.
616    ///
617    /// `NaN`s, infinities, and zeros are returned unchanged with `Equal`; of these, only zeros are
618    /// considered integers.
619    ///
620    /// If rounding away from zero at the maximum exponent produces an integer too large to
621    /// represent, the result is $\pm\infty$.
622    ///
623    /// # Worst-case complexity
624    /// $T(n) = O(n)$
625    ///
626    /// $M(n) = O(n)$
627    ///
628    /// where $T$ is time, $M$ is additional memory, and $n$ is `max(prec,
629    /// self.significant_bits())`.
630    ///
631    /// # Panics
632    /// Panics if `prec` is zero.
633    ///
634    /// # Examples
635    /// ```
636    /// use core::cmp::Ordering::*;
637    /// use malachite_float::Float;
638    ///
639    /// // ties away from zero
640    /// let x = Float::from(2.5f64);
641    /// assert_eq!(
642    ///     x.round_to_integer_ties_away_prec_ref(4),
643    ///     (Float::from(3u32), Greater, false)
644    /// );
645    /// ```
646    #[inline]
647    pub fn round_to_integer_ties_away_prec_ref(&self, prec: u64) -> (Self, Ordering, bool) {
648        self.round_to_integer_helper(prec, Nearest, true)
649    }
650
651    /// Rounds a [`Float`] to the nearest integer representable at the input's own precision, with
652    /// ties going away from zero. An [`Ordering`] comparing the result to the exact input is also
653    /// returned, along with a `bool` indicating whether the input was an integer. The [`Float`] is
654    /// taken by value.
655    ///
656    /// Ties round away from zero, as in IEEE 754's roundTiesToAway and MPFR's `mpfr_round`; the
657    /// other integer-rounding directions are available through
658    /// [`Float::round_to_integer_prec_round`].
659    ///
660    /// The pair of the [`Ordering`] and the `bool` carries the same information as `mpfr_rint`'s
661    /// ternary value: `(Equal, true)` means the input was an integer representable at the target
662    /// precision, returned unchanged; `(Less, true)` and `(Greater, true)` mean the input was an
663    /// integer that required rounding to fit the precision; `(Less, false)` and `(Greater, false)`
664    /// mean the input was not an integer. `(Equal, false)` cannot occur.
665    ///
666    /// `NaN`s, infinities, and zeros are returned unchanged with `Equal`; of these, only zeros are
667    /// considered integers.
668    ///
669    /// If rounding away from zero at the maximum exponent produces an integer too large to
670    /// represent, the result is $\pm\infty$.
671    ///
672    /// # Worst-case complexity
673    /// $T(n) = O(n)$
674    ///
675    /// $M(n) = O(n)$
676    ///
677    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
678    ///
679    /// # Panics
680    /// Never panics.
681    ///
682    /// # Examples
683    /// ```
684    /// use core::cmp::Ordering::*;
685    /// use malachite_float::Float;
686    ///
687    /// // ties away from zero
688    /// let x = Float::from(2.5f64);
689    /// assert_eq!(
690    ///     x.round_to_integer_ties_away_ref(),
691    ///     (Float::from(3u32), Greater, false)
692    /// );
693    /// ```
694    #[inline]
695    pub fn round_to_integer_ties_away(self) -> (Self, Ordering, bool) {
696        self.round_to_integer_helper(self.significant_bits(), Nearest, true)
697    }
698
699    /// Rounds a [`Float`] to the nearest integer representable at the input's own precision, with
700    /// ties going away from zero. An [`Ordering`] comparing the result to the exact input is also
701    /// returned, along with a `bool` indicating whether the input was an integer. The [`Float`] is
702    /// taken by reference.
703    ///
704    /// Ties round away from zero, as in IEEE 754's roundTiesToAway and MPFR's `mpfr_round`; the
705    /// other integer-rounding directions are available through
706    /// [`Float::round_to_integer_prec_round`].
707    ///
708    /// The pair of the [`Ordering`] and the `bool` carries the same information as `mpfr_rint`'s
709    /// ternary value: `(Equal, true)` means the input was an integer representable at the target
710    /// precision, returned unchanged; `(Less, true)` and `(Greater, true)` mean the input was an
711    /// integer that required rounding to fit the precision; `(Less, false)` and `(Greater, false)`
712    /// mean the input was not an integer. `(Equal, false)` cannot occur.
713    ///
714    /// `NaN`s, infinities, and zeros are returned unchanged with `Equal`; of these, only zeros are
715    /// considered integers.
716    ///
717    /// If rounding away from zero at the maximum exponent produces an integer too large to
718    /// represent, the result is $\pm\infty$.
719    ///
720    /// # Worst-case complexity
721    /// $T(n) = O(n)$
722    ///
723    /// $M(n) = O(n)$
724    ///
725    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
726    ///
727    /// # Panics
728    /// Never panics.
729    ///
730    /// # Examples
731    /// ```
732    /// use core::cmp::Ordering::*;
733    /// use malachite_float::Float;
734    ///
735    /// // ties away from zero
736    /// let x = Float::from(2.5f64);
737    /// assert_eq!(
738    ///     x.round_to_integer_ties_away_ref(),
739    ///     (Float::from(3u32), Greater, false)
740    /// );
741    /// ```
742    #[inline]
743    pub fn round_to_integer_ties_away_ref(&self) -> (Self, Ordering, bool) {
744        self.round_to_integer_helper(self.significant_bits(), Nearest, true)
745    }
746
747    /// Rounds a [`Float`] to an integer in the direction `irm`, and then correctly rounds that
748    /// exact integer to the specified precision with `rm`. An [`Ordering`] comparing the result to
749    /// the exact integer is also returned. The [`Float`] is taken by value.
750    ///
751    /// Unlike [`Float::round_to_integer_prec_round`], which rounds once, this function is the
752    /// composition of two roundings, matching MPFR's `mpfr_rint_`-prefixed functions: the exact
753    /// integer is formed first, then rounded to the target precision. The two can differ: under
754    /// this function with both modes `Nearest`, $10.5$ becomes $10$, which then rounds to $8$ at a
755    /// precision of 2 bits, while the single-rounding form gives $12$.
756    ///
757    /// `NaN`s, infinities, and non-integer-producing specials pass through the final rounding only.
758    /// If the integer overflows the exponent range, the result follows `rm`: $\pm\infty$ for the
759    /// modes rounding away from zero, and the maximum finite value at the target precision for the
760    /// modes rounding toward zero.
761    ///
762    /// # Worst-case complexity
763    /// $T(n) = O(n)$
764    ///
765    /// $M(n) = O(n)$
766    ///
767    /// where $T$ is time, $M$ is additional memory, and $n$ is `max(prec,
768    /// self.significant_bits())`.
769    ///
770    /// # Panics
771    /// Panics if `prec` is zero, if `irm` is `Exact`, or if `rm` is `Exact` and the integer is not
772    /// exactly representable at the target precision.
773    ///
774    /// # Examples
775    /// ```
776    /// use core::cmp::Ordering::*;
777    /// use malachite_base::rounding_modes::RoundingMode::*;
778    /// use malachite_float::Float;
779    ///
780    /// let x = Float::from(10.5f64);
781    /// assert_eq!(
782    ///     x.round_to_integer_then_prec_round_ref(Nearest, 2, Nearest),
783    ///     (Float::from(8u32), Less)
784    /// );
785    /// assert_eq!(
786    ///     Float::from(2.5f64).round_to_integer_then_prec_round_ref(Ceiling, 10, Nearest),
787    ///     (Float::from(3u32), Equal)
788    /// );
789    /// ```
790    #[inline]
791    pub fn round_to_integer_then_prec_round(
792        self,
793        irm: RoundingMode,
794        prec: u64,
795        rm: RoundingMode,
796    ) -> (Self, Ordering) {
797        assert_ne!(irm, Exact);
798        self.round_to_integer_then_helper(irm, false, prec, rm)
799    }
800
801    /// Rounds a [`Float`] to an integer in the direction `irm`, and then correctly rounds that
802    /// exact integer to the specified precision with `rm`. An [`Ordering`] comparing the result to
803    /// the exact integer is also returned. The [`Float`] is taken by reference.
804    ///
805    /// Unlike [`Float::round_to_integer_prec_round`], which rounds once, this function is the
806    /// composition of two roundings, matching MPFR's `mpfr_rint_`-prefixed functions: the exact
807    /// integer is formed first, then rounded to the target precision. The two can differ: under
808    /// this function with both modes `Nearest`, $10.5$ becomes $10$, which then rounds to $8$ at a
809    /// precision of 2 bits, while the single-rounding form gives $12$.
810    ///
811    /// `NaN`s, infinities, and non-integer-producing specials pass through the final rounding only.
812    /// If the integer overflows the exponent range, the result follows `rm`: $\pm\infty$ for the
813    /// modes rounding away from zero, and the maximum finite value at the target precision for the
814    /// modes rounding toward zero.
815    ///
816    /// # Worst-case complexity
817    /// $T(n) = O(n)$
818    ///
819    /// $M(n) = O(n)$
820    ///
821    /// where $T$ is time, $M$ is additional memory, and $n$ is `max(prec,
822    /// self.significant_bits())`.
823    ///
824    /// # Panics
825    /// Panics if `prec` is zero, if `irm` is `Exact`, or if `rm` is `Exact` and the integer is not
826    /// exactly representable at the target precision.
827    ///
828    /// # Examples
829    /// ```
830    /// use core::cmp::Ordering::*;
831    /// use malachite_base::rounding_modes::RoundingMode::*;
832    /// use malachite_float::Float;
833    ///
834    /// let x = Float::from(10.5f64);
835    /// assert_eq!(
836    ///     x.round_to_integer_then_prec_round_ref(Nearest, 2, Nearest),
837    ///     (Float::from(8u32), Less)
838    /// );
839    /// assert_eq!(
840    ///     Float::from(2.5f64).round_to_integer_then_prec_round_ref(Ceiling, 10, Nearest),
841    ///     (Float::from(3u32), Equal)
842    /// );
843    /// ```
844    #[inline]
845    pub fn round_to_integer_then_prec_round_ref(
846        &self,
847        irm: RoundingMode,
848        prec: u64,
849        rm: RoundingMode,
850    ) -> (Self, Ordering) {
851        assert_ne!(irm, Exact);
852        self.round_to_integer_then_helper(irm, false, prec, rm)
853    }
854
855    /// Rounds a [`Float`] to the nearest integer with ties going away from zero, and then correctly
856    /// rounds that exact integer to the specified precision with `rm`. An [`Ordering`] comparing
857    /// the result to the exact integer is also returned. The [`Float`] is taken by value.
858    ///
859    /// Unlike [`Float::round_to_integer_prec_round`], which rounds once, this function is the
860    /// composition of two roundings, matching MPFR's `mpfr_rint_`-prefixed functions: the exact
861    /// integer is formed first, then rounded to the target precision. The two can differ: under
862    /// this function with both modes `Nearest`, $10.5$ becomes $10$, which then rounds to $8$ at a
863    /// precision of 2 bits, while the single-rounding form gives $12$.
864    ///
865    /// `NaN`s, infinities, and non-integer-producing specials pass through the final rounding only.
866    /// If the integer overflows the exponent range, the result follows `rm`: $\pm\infty$ for the
867    /// modes rounding away from zero, and the maximum finite value at the target precision for the
868    /// modes rounding toward zero.
869    ///
870    /// # Worst-case complexity
871    /// $T(n) = O(n)$
872    ///
873    /// $M(n) = O(n)$
874    ///
875    /// where $T$ is time, $M$ is additional memory, and $n$ is `max(prec,
876    /// self.significant_bits())`.
877    ///
878    /// # Panics
879    /// Panics if `prec` is zero, or if `rm` is `Exact` and the integer is not exactly representable
880    /// at the target precision.
881    ///
882    /// # Examples
883    /// ```
884    /// use core::cmp::Ordering::*;
885    /// use malachite_base::rounding_modes::RoundingMode::*;
886    /// use malachite_float::Float;
887    ///
888    /// let x = Float::from(10.5f64);
889    /// assert_eq!(
890    ///     x.round_to_integer_ties_away_then_prec_round_ref(2, Nearest),
891    ///     (Float::from(12u32), Greater)
892    /// );
893    /// ```
894    #[inline]
895    pub fn round_to_integer_ties_away_then_prec_round(
896        self,
897        prec: u64,
898        rm: RoundingMode,
899    ) -> (Self, Ordering) {
900        self.round_to_integer_then_helper(Nearest, true, prec, rm)
901    }
902
903    /// Rounds a [`Float`] to the nearest integer with ties going away from zero, and then correctly
904    /// rounds that exact integer to the specified precision with `rm`. An [`Ordering`] comparing
905    /// the result to the exact integer is also returned. The [`Float`] is taken by reference.
906    ///
907    /// Unlike [`Float::round_to_integer_prec_round`], which rounds once, this function is the
908    /// composition of two roundings, matching MPFR's `mpfr_rint_`-prefixed functions: the exact
909    /// integer is formed first, then rounded to the target precision. The two can differ: under
910    /// this function with both modes `Nearest`, $10.5$ becomes $10$, which then rounds to $8$ at a
911    /// precision of 2 bits, while the single-rounding form gives $12$.
912    ///
913    /// `NaN`s, infinities, and non-integer-producing specials pass through the final rounding only.
914    /// If the integer overflows the exponent range, the result follows `rm`: $\pm\infty$ for the
915    /// modes rounding away from zero, and the maximum finite value at the target precision for the
916    /// modes rounding toward zero.
917    ///
918    /// # Worst-case complexity
919    /// $T(n) = O(n)$
920    ///
921    /// $M(n) = O(n)$
922    ///
923    /// where $T$ is time, $M$ is additional memory, and $n$ is `max(prec,
924    /// self.significant_bits())`.
925    ///
926    /// # Panics
927    /// Panics if `prec` is zero, or if `rm` is `Exact` and the integer is not exactly representable
928    /// at the target precision.
929    ///
930    /// # Examples
931    /// ```
932    /// use core::cmp::Ordering::*;
933    /// use malachite_base::rounding_modes::RoundingMode::*;
934    /// use malachite_float::Float;
935    ///
936    /// let x = Float::from(10.5f64);
937    /// assert_eq!(
938    ///     x.round_to_integer_ties_away_then_prec_round_ref(2, Nearest),
939    ///     (Float::from(12u32), Greater)
940    /// );
941    /// ```
942    #[inline]
943    pub fn round_to_integer_ties_away_then_prec_round_ref(
944        &self,
945        prec: u64,
946        rm: RoundingMode,
947    ) -> (Self, Ordering) {
948        self.round_to_integer_then_helper(Nearest, true, prec, rm)
949    }
950
951    pub(crate) fn round_to_integer_helper(
952        &self,
953        prec: u64,
954        rm: RoundingMode,
955        ties_away: bool,
956    ) -> (Self, Ordering, bool) {
957        assert_ne!(prec, 0);
958        let Self(Finite {
959            sign,
960            exponent,
961            significand,
962            ..
963        }) = self
964        else {
965            // NaN, infinities, and zeros are returned unchanged and are exact; among them, only
966            // zeros are integers.
967            return (self.clone(), Equal, matches!(self, Self(Zero { .. })));
968        };
969        let sign = *sign;
970        let neg = !sign;
971        let exp = *exponent;
972        // The rounding direction in terms of magnitude: away from zero, toward zero, or (for the
973        // nearest modes) not yet decided.
974        let rnd_away = match rm {
975            Floor => Some(neg),
976            Ceiling => Some(sign),
977            Down => Some(false),
978            Up => Some(true),
979            Nearest => None,
980            Exact => panic!("round_to_integer with the Exact rounding mode"),
981        };
982        if exp <= 0 {
983            // 0 < |u| < 1, so the result is 0 or +/-1, and the input is never an integer. In the
984            // Nearest mode, 1/2 rounds to 0 by the even rule, but to +/-1 when ties go away from
985            // zero.
986            let away = match rnd_away {
987                Some(away) => away,
988                None => exp == 0 && (ties_away || !significand.is_power_of_2()),
989            };
990            return if away {
991                (
992                    signed_one(sign, prec),
993                    if sign { Greater } else { Less },
994                    false,
995                )
996            } else {
997                (
998                    Self(Zero { sign }),
999                    if sign { Less } else { Greater },
1000                    false,
1001                )
1002            };
1003        }
1004        // Now exp > 0, so |u| >= 1.
1005        let (rp, exp_increment, uflags, rnd_away) =
1006            with_float_significand_limbs(significand, |up| {
1007                limbs_float_round_to_integer(up, u64::exact_from(exp), prec, rnd_away, ties_away)
1008            });
1009        if uflags == 0 {
1010            return (
1011                Self(Finite {
1012                    sign,
1013                    exponent: exp,
1014                    precision: prec,
1015                    significand: Natural::from_owned_limbs_asc(rp),
1016                }),
1017                Equal,
1018                true,
1019            );
1020        }
1021        if exp_increment && exp == Self::MAX_EXPONENT {
1022            // The rounded integer would exceed the maximum exponent; since the rounding was away
1023            // from zero, the result overflows to infinity.
1024            return (
1025                Self(Infinity { sign }),
1026                if sign { Greater } else { Less },
1027                uflags == 1,
1028            );
1029        }
1030        let o = if rnd_away == sign { Greater } else { Less };
1031        (
1032            Self(Finite {
1033                sign,
1034                exponent: if exp_increment { exp + 1 } else { exp },
1035                precision: prec,
1036                significand: Natural::from_owned_limbs_asc(rp),
1037            }),
1038            o,
1039            uflags == 1,
1040        )
1041    }
1042}
1043
1044/// Rounds a primitive float to an integer using the given rounding mode, using emulated [`Float`]
1045/// arithmetic.
1046///
1047/// The result is always exactly representable. With `Floor`, `Ceiling`, `Down`, `Up`, and `Nearest`
1048/// this matches the standard library's `floor`, `ceil`, `trunc` (with `Down`; `Up` rounds away from
1049/// zero, which has no standard equivalent), and `round_ties_even`; it serves as a reference
1050/// implementation. NaN, infinities, and zeros are unchanged.
1051///
1052/// # Worst-case complexity
1053/// Constant time and additional memory.
1054///
1055/// # Panics
1056/// Panics if `rm` is `Exact` and the input is not an integer.
1057///
1058/// # Examples
1059/// ```
1060/// use malachite_base::num::float::NiceFloat;
1061/// use malachite_base::rounding_modes::RoundingMode::*;
1062/// use malachite_float::float::arithmetic::round_to_integer::primitive_float_round_to_integer;
1063///
1064/// assert_eq!(
1065///     NiceFloat(primitive_float_round_to_integer(2.5, Floor)),
1066///     NiceFloat(2.0)
1067/// );
1068/// assert_eq!(
1069///     NiceFloat(primitive_float_round_to_integer(2.5, Nearest)),
1070///     NiceFloat(2.0)
1071/// );
1072/// ```
1073#[allow(clippy::type_repetition_in_bounds)]
1074#[inline]
1075pub fn primitive_float_round_to_integer<T: PrimitiveFloat>(x: T, rm: RoundingMode) -> T
1076where
1077    Float: From<T> + PartialOrd<T>,
1078    for<'a> T: ExactFrom<&'a Float>,
1079{
1080    emulate_float_to_float_fn(
1081        |x, prec| {
1082            let (r, o, _) = x.round_to_integer_prec_round(prec, rm);
1083            (r, o)
1084        },
1085        x,
1086    )
1087}
1088
1089/// Rounds a primitive float to the nearest integer, with ties away from zero, using emulated
1090/// [`Float`] arithmetic.
1091///
1092/// This is IEEE 754's roundTiesToAway, matching the standard library's `round`; it serves as a
1093/// reference implementation. NaN, infinities, and zeros are unchanged.
1094///
1095/// # Worst-case complexity
1096/// Constant time and additional memory.
1097///
1098/// # Examples
1099/// ```
1100/// use malachite_base::num::float::NiceFloat;
1101/// use malachite_float::float::arithmetic::round_to_integer::*;
1102///
1103/// assert_eq!(
1104///     NiceFloat(primitive_float_round_to_integer_ties_away(2.5)),
1105///     NiceFloat(3.0)
1106/// );
1107/// ```
1108#[allow(clippy::type_repetition_in_bounds)]
1109#[inline]
1110pub fn primitive_float_round_to_integer_ties_away<T: PrimitiveFloat>(x: T) -> T
1111where
1112    Float: From<T> + PartialOrd<T>,
1113    for<'a> T: ExactFrom<&'a Float>,
1114{
1115    emulate_float_to_float_fn(
1116        |x, prec| {
1117            let (r, o, _) = x.round_to_integer_ties_away_prec(prec);
1118            (r, o)
1119        },
1120        x,
1121    )
1122}