malachite_float/comparison/
partial_cmp_rational.rs

1// Copyright © 2025 Mikhail Hogrefe
2//
3// This file is part of Malachite.
4//
5// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
6// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
7// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
8
9use crate::InnerFloat::{Finite, Infinity, NaN, Zero};
10use crate::{significand_bits, Float};
11use core::cmp::Ordering::{self, *};
12use malachite_base::num::arithmetic::traits::Sign;
13use malachite_base::num::conversion::traits::ExactFrom;
14use malachite_q::Rational;
15
16impl PartialOrd<Rational> for Float {
17    /// Compares a [`Float`] to a [`Rational`].
18    ///
19    /// NaN is not comparable to any [`Rational`]. $\infty$ is greater than any [`Rational`], and
20    /// $-\infty$ is less. Both the [`Float`] zero and the [`Float`] negative zero are equal to the
21    /// [`Rational`] zero.
22    ///
23    /// # Worst-case complexity
24    /// $T(n) = O(n \log n \log\log n)$
25    ///
26    /// $M(n) = O(n \log n)$
27    ///
28    /// where $T$ is time, $M$ is additional memory, and $n$ is `max(self.significant_bits(),
29    /// other.significant_bits())`.
30    ///
31    /// # Examples
32    /// ```
33    /// use malachite_base::num::basic::traits::{Infinity, NegativeInfinity};
34    /// use malachite_float::Float;
35    /// use malachite_q::Rational;
36    ///
37    /// assert!(Float::from(80) < Rational::from(100));
38    /// assert!(Float::from(-80) > Rational::from(-100));
39    /// assert!(Float::INFINITY > Rational::from(100));
40    /// assert!(Float::NEGATIVE_INFINITY < Rational::from(-100));
41    /// assert!(Float::from(1.0f64 / 3.0) < Rational::from_unsigneds(1u8, 3));
42    /// ```
43    fn partial_cmp(&self, other: &Rational) -> Option<Ordering> {
44        match (self, other) {
45            (float_nan!(), _) => None,
46            (float_infinity!(), _) => Some(Greater),
47            (float_negative_infinity!(), _) => Some(Less),
48            (float_either_zero!(), y) => 0u32.partial_cmp(y),
49            (
50                Float(Finite {
51                    sign: s_x,
52                    exponent: e_x,
53                    significand: significand_x,
54                    ..
55                }),
56                y,
57            ) => Some(if *y == 0u32 {
58                if *s_x {
59                    Greater
60                } else {
61                    Less
62                }
63            } else {
64                let s_cmp = s_x.cmp(&(*y > 0));
65                if s_cmp != Equal {
66                    return Some(s_cmp);
67                }
68                let e_x = i64::from(*e_x);
69                let exp_cmp = (e_x - 1).cmp(&other.floor_log_base_2_abs());
70                if exp_cmp != Equal {
71                    return Some(if *s_x { exp_cmp } else { exp_cmp.reverse() });
72                }
73                let shift = e_x - i64::exact_from(significand_bits(significand_x));
74                let abs_shift = shift.unsigned_abs();
75                let prod_cmp = match shift.sign() {
76                    Equal => (significand_x * other.denominator_ref()).cmp(other.numerator_ref()),
77                    Greater => ((significand_x * other.denominator_ref()) << abs_shift)
78                        .cmp(other.numerator_ref()),
79                    Less => {
80                        let n_trailing_zeros = significand_x.trailing_zeros().unwrap();
81                        if abs_shift <= n_trailing_zeros {
82                            ((significand_x >> abs_shift) * other.denominator_ref())
83                                .cmp(other.numerator_ref())
84                        } else {
85                            ((significand_x >> n_trailing_zeros) * other.denominator_ref())
86                                .cmp(&(other.numerator_ref() << (abs_shift - n_trailing_zeros)))
87                        }
88                    }
89                };
90                if *s_x {
91                    prod_cmp
92                } else {
93                    prod_cmp.reverse()
94                }
95            }),
96        }
97    }
98}
99
100impl PartialOrd<Float> for Rational {
101    /// Compares an [`Rational`] to a [`Float`].
102    ///
103    /// No [`Rational`] is comparable to NaN. Every [`Rational`] is smaller than $\infty$ and
104    /// greater than $-\infty$. The [`Rational`] zero is equal to both the [`Float`] zero and the
105    /// [`Float`] negative zero.
106    ///
107    /// # Worst-case complexity
108    /// $T(n) = O(n \log n \log\log n)$
109    ///
110    /// $M(n) = O(n \log n)$
111    ///
112    /// where $T$ is time, $M$ is additional memory, and $n$ is `max(self.significant_bits(),
113    /// other.significant_bits())`.
114    ///
115    /// # Examples
116    /// ```
117    /// use malachite_base::num::basic::traits::{Infinity, NegativeInfinity};
118    /// use malachite_float::Float;
119    /// use malachite_q::Rational;
120    ///
121    /// assert!(Rational::from(100) > Float::from(80));
122    /// assert!(Rational::from(-100) < Float::from(-80));
123    /// assert!(Rational::from(100) < Float::INFINITY);
124    /// assert!(Rational::from(-100) > Float::NEGATIVE_INFINITY);
125    /// assert!(Rational::from_unsigneds(1u8, 3) > Float::from(1.0f64 / 3.0));
126    /// ```
127    #[inline]
128    fn partial_cmp(&self, other: &Float) -> Option<Ordering> {
129        other.partial_cmp(self).map(Ordering::reverse)
130    }
131}