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::{Float, significand_bits};
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                Self(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 { Greater } else { Less }
59            } else {
60                let s_cmp = s_x.cmp(&(*y > 0));
61                if s_cmp != Equal {
62                    return Some(s_cmp);
63                }
64                let e_x = i64::from(*e_x);
65                let exp_cmp = (e_x - 1).cmp(&other.floor_log_base_2_abs());
66                if exp_cmp != Equal {
67                    return Some(if *s_x { exp_cmp } else { exp_cmp.reverse() });
68                }
69                let shift = e_x - i64::exact_from(significand_bits(significand_x));
70                let abs_shift = shift.unsigned_abs();
71                let prod_cmp = match shift.sign() {
72                    Equal => (significand_x * other.denominator_ref()).cmp(other.numerator_ref()),
73                    Greater => ((significand_x * other.denominator_ref()) << abs_shift)
74                        .cmp(other.numerator_ref()),
75                    Less => {
76                        let n_trailing_zeros = significand_x.trailing_zeros().unwrap();
77                        if abs_shift <= n_trailing_zeros {
78                            ((significand_x >> abs_shift) * other.denominator_ref())
79                                .cmp(other.numerator_ref())
80                        } else {
81                            ((significand_x >> n_trailing_zeros) * other.denominator_ref())
82                                .cmp(&(other.numerator_ref() << (abs_shift - n_trailing_zeros)))
83                        }
84                    }
85                };
86                if *s_x { prod_cmp } else { prod_cmp.reverse() }
87            }),
88        }
89    }
90}
91
92impl PartialOrd<Float> for Rational {
93    /// Compares an [`Rational`] to a [`Float`].
94    ///
95    /// No [`Rational`] is comparable to NaN. Every [`Rational`] is smaller than $\infty$ and
96    /// greater than $-\infty$. The [`Rational`] zero is equal to both the [`Float`] zero and the
97    /// [`Float`] negative zero.
98    ///
99    /// # Worst-case complexity
100    /// $T(n) = O(n \log n \log\log n)$
101    ///
102    /// $M(n) = O(n \log n)$
103    ///
104    /// where $T$ is time, $M$ is additional memory, and $n$ is `max(self.significant_bits(),
105    /// other.significant_bits())`.
106    ///
107    /// # Examples
108    /// ```
109    /// use malachite_base::num::basic::traits::{Infinity, NegativeInfinity};
110    /// use malachite_float::Float;
111    /// use malachite_q::Rational;
112    ///
113    /// assert!(Rational::from(100) > Float::from(80));
114    /// assert!(Rational::from(-100) < Float::from(-80));
115    /// assert!(Rational::from(100) < Float::INFINITY);
116    /// assert!(Rational::from(-100) > Float::NEGATIVE_INFINITY);
117    /// assert!(Rational::from_unsigneds(1u8, 3) > Float::from(1.0f64 / 3.0));
118    /// ```
119    #[inline]
120    fn partial_cmp(&self, other: &Float) -> Option<Ordering> {
121        other.partial_cmp(self).map(Ordering::reverse)
122    }
123}