malachite_float/comparison/
cmp.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::{ComparableFloat, ComparableFloatRef, Float};
11use core::cmp::Ordering::{self, *};
12
13impl PartialOrd for Float {
14    /// Compares two [`Float`]s.
15    ///
16    /// This implementation follows the IEEE 754 standard. `NaN` is not comparable to anything, not
17    /// even itself. Positive zero is equal to negative zero. [`Float`]s with different precisions
18    /// are equal if they represent the same numeric value.
19    ///
20    /// For different comparison behavior that provides a total order, consider using
21    /// [`ComparableFloat`] or [`ComparableFloatRef`].
22    ///
23    /// # Worst-case complexity
24    /// $T(n) = O(n)$
25    ///
26    /// $M(n) = O(1)$
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::{
34    ///     Infinity, NaN, NegativeInfinity, NegativeOne, NegativeZero, One, OneHalf, Zero,
35    /// };
36    /// use malachite_float::Float;
37    /// use std::cmp::Ordering::*;
38    ///
39    /// assert_eq!(Float::NAN.partial_cmp(&Float::NAN), None);
40    /// assert_eq!(Float::ZERO.partial_cmp(&Float::NEGATIVE_ZERO), Some(Equal));
41    /// assert_eq!(Float::ONE.partial_cmp(&Float::one_prec(100)), Some(Equal));
42    /// assert!(Float::INFINITY > Float::ONE);
43    /// assert!(Float::NEGATIVE_INFINITY < Float::ONE);
44    /// assert!(Float::ONE_HALF < Float::ONE);
45    /// assert!(Float::ONE_HALF > Float::NEGATIVE_ONE);
46    /// ```
47    fn partial_cmp(&self, other: &Float) -> Option<Ordering> {
48        match (self, other) {
49            (float_nan!(), _) | (_, float_nan!()) => None,
50            (float_infinity!(), float_infinity!())
51            | (float_negative_infinity!(), float_negative_infinity!())
52            | (float_either_zero!(), float_either_zero!()) => Some(Equal),
53            (float_infinity!(), _) | (_, float_negative_infinity!()) => Some(Greater),
54            (float_negative_infinity!(), _) | (_, float_infinity!()) => Some(Less),
55            (Float(Finite { sign, .. }), float_either_zero!()) => {
56                Some(if *sign { Greater } else { Less })
57            }
58            (float_either_zero!(), Float(Finite { sign, .. })) => {
59                Some(if *sign { Less } else { Greater })
60            }
61            (
62                Float(Finite {
63                    sign: s_x,
64                    exponent: e_x,
65                    significand: x,
66                    ..
67                }),
68                Float(Finite {
69                    sign: s_y,
70                    exponent: e_y,
71                    significand: y,
72                    ..
73                }),
74            ) => Some(s_x.cmp(s_y).then_with(|| {
75                let abs_cmp = e_x.cmp(e_y).then_with(|| x.cmp_normalized_no_shift(y));
76                if *s_x {
77                    abs_cmp
78                } else {
79                    abs_cmp.reverse()
80                }
81            })),
82        }
83    }
84}
85
86impl<'a> Ord for ComparableFloatRef<'a> {
87    /// Compares two [`ComparableFloatRef`]s.
88    ///
89    /// This implementation does not follow the IEEE 754 standard. This is how
90    /// [`ComparableFloatRef`]s are ordered, least to greatest:
91    ///   - $-\infty$
92    ///   - Negative nonzero finite floats
93    ///   - Negative zero
94    ///   - NaN
95    ///   - Positive zero
96    ///   - Positive nonzero finite floats
97    ///   - $\infty$
98    ///
99    /// For different comparison behavior that follows the IEEE 754 standard, consider just using
100    /// [`Float`].
101    ///
102    /// # Worst-case complexity
103    /// $T(n) = O(n)$
104    ///
105    /// $M(n) = O(1)$
106    ///
107    /// where $T$ is time, $M$ is additional memory, and $n$ is `max(self.significant_bits(),
108    /// other.significant_bits())`.
109    ///
110    /// # Examples
111    /// ```
112    /// use malachite_base::num::basic::traits::{
113    ///     Infinity, NaN, NegativeInfinity, NegativeOne, NegativeZero, One, OneHalf, Zero,
114    /// };
115    /// use malachite_float::{ComparableFloatRef, Float};
116    /// use std::cmp::Ordering::*;
117    ///
118    /// assert_eq!(
119    ///     ComparableFloatRef(&Float::NAN).partial_cmp(&ComparableFloatRef(&Float::NAN)),
120    ///     Some(Equal)
121    /// );
122    /// assert!(ComparableFloatRef(&Float::ZERO) > ComparableFloatRef(&Float::NEGATIVE_ZERO));
123    /// assert!(ComparableFloatRef(&Float::ONE) < ComparableFloatRef(&Float::one_prec(100)));
124    /// assert!(ComparableFloatRef(&Float::INFINITY) > ComparableFloatRef(&Float::ONE));
125    /// assert!(ComparableFloatRef(&Float::NEGATIVE_INFINITY) < ComparableFloatRef(&Float::ONE));
126    /// assert!(ComparableFloatRef(&Float::ONE_HALF) < ComparableFloatRef(&Float::ONE));
127    /// assert!(ComparableFloatRef(&Float::ONE_HALF) > ComparableFloatRef(&Float::NEGATIVE_ONE));
128    /// ```
129    fn cmp(&self, other: &ComparableFloatRef<'a>) -> Ordering {
130        match (&self.0, &other.0) {
131            (float_nan!(), float_nan!())
132            | (float_infinity!(), float_infinity!())
133            | (float_negative_infinity!(), float_negative_infinity!()) => Equal,
134            (Float(Zero { sign: s_x }), Float(Zero { sign: s_y })) => s_x.cmp(s_y),
135            (float_infinity!(), _) | (_, float_negative_infinity!()) => Greater,
136            (float_negative_infinity!(), _) | (_, float_infinity!()) => Less,
137            (Float(NaN | Zero { .. }), Float(Finite { sign, .. }))
138            | (Float(NaN), Float(Zero { sign })) => {
139                if *sign {
140                    Less
141                } else {
142                    Greater
143                }
144            }
145            (Float(Finite { sign, .. } | Zero { sign }), Float(NaN))
146            | (Float(Finite { sign, .. }), Float(Zero { .. })) => {
147                if *sign {
148                    Greater
149                } else {
150                    Less
151                }
152            }
153            (
154                Float(Finite {
155                    sign: s_x,
156                    exponent: e_x,
157                    precision: p_x,
158                    significand: x,
159                }),
160                Float(Finite {
161                    sign: s_y,
162                    exponent: e_y,
163                    precision: p_y,
164                    significand: y,
165                }),
166            ) => s_x.cmp(s_y).then_with(|| {
167                let abs_cmp = e_x
168                    .cmp(e_y)
169                    .then_with(|| x.cmp_normalized_no_shift(y))
170                    .then_with(|| p_x.cmp(p_y));
171                if *s_x {
172                    abs_cmp
173                } else {
174                    abs_cmp.reverse()
175                }
176            }),
177        }
178    }
179}
180
181impl PartialOrd for ComparableFloatRef<'_> {
182    /// Compares two [`ComparableFloatRef`]s.
183    ///
184    /// See the documentation for the [`Ord`] implementation.
185    #[inline]
186    fn partial_cmp(&self, other: &ComparableFloatRef) -> Option<Ordering> {
187        Some(self.cmp(other))
188    }
189}
190
191impl Ord for ComparableFloat {
192    /// Compares two [`ComparableFloat`]s.
193    ///
194    /// This implementation does not follow the IEEE 754 standard. This is how [`ComparableFloat`]s
195    /// are ordered, least to greatest:
196    ///   - $-\infty$
197    ///   - Negative nonzero finite floats
198    ///   - Negative zero
199    ///   - NaN
200    ///   - Positive zero
201    ///   - Positive nonzero finite floats
202    ///   - $\infty$
203    ///
204    /// For different comparison behavior that follows the IEEE 754 standard, consider just using
205    /// [`Float`].
206    ///
207    /// # Worst-case complexity
208    /// $T(n) = O(n)$
209    ///
210    /// $M(n) = O(1)$
211    ///
212    /// where $T$ is time, $M$ is additional memory, and $n$ is `max(self.significant_bits(),
213    /// other.significant_bits())`.
214    ///
215    /// # Examples
216    /// ```
217    /// use malachite_base::num::basic::traits::{
218    ///     Infinity, NaN, NegativeInfinity, NegativeOne, NegativeZero, One, OneHalf, Zero,
219    /// };
220    /// use malachite_float::{ComparableFloat, Float};
221    /// use std::cmp::Ordering::*;
222    ///
223    /// assert_eq!(
224    ///     ComparableFloat(Float::NAN).partial_cmp(&ComparableFloat(Float::NAN)),
225    ///     Some(Equal)
226    /// );
227    /// assert!(ComparableFloat(Float::ZERO) > ComparableFloat(Float::NEGATIVE_ZERO));
228    /// assert!(ComparableFloat(Float::ONE) < ComparableFloat(Float::one_prec(100)));
229    /// assert!(ComparableFloat(Float::INFINITY) > ComparableFloat(Float::ONE));
230    /// assert!(ComparableFloat(Float::NEGATIVE_INFINITY) < ComparableFloat(Float::ONE));
231    /// assert!(ComparableFloat(Float::ONE_HALF) < ComparableFloat(Float::ONE));
232    /// assert!(ComparableFloat(Float::ONE_HALF) > ComparableFloat(Float::NEGATIVE_ONE));
233    /// ```
234    #[inline]
235    fn cmp(&self, other: &ComparableFloat) -> Ordering {
236        self.as_ref().cmp(&other.as_ref())
237    }
238}
239
240impl PartialOrd for ComparableFloat {
241    /// Compares two [`ComparableFloat`]s.
242    ///
243    /// See the documentation for the [`Ord`] implementation.
244    #[inline]
245    fn partial_cmp(&self, other: &ComparableFloat) -> Option<Ordering> {
246        Some(self.as_ref().cmp(&other.as_ref()))
247    }
248}