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 { abs_cmp } else { abs_cmp.reverse() }
77            })),
78        }
79    }
80}
81
82impl<'a> Ord for ComparableFloatRef<'a> {
83    /// Compares two [`ComparableFloatRef`]s.
84    ///
85    /// This implementation does not follow the IEEE 754 standard. This is how
86    /// [`ComparableFloatRef`]s are ordered, least to greatest:
87    ///   - $-\infty$
88    ///   - Negative nonzero finite floats
89    ///   - Negative zero
90    ///   - NaN
91    ///   - Positive zero
92    ///   - Positive nonzero finite floats
93    ///   - $\infty$
94    ///
95    /// For different comparison behavior that follows the IEEE 754 standard, consider just using
96    /// [`Float`].
97    ///
98    /// # Worst-case complexity
99    /// $T(n) = O(n)$
100    ///
101    /// $M(n) = O(1)$
102    ///
103    /// where $T$ is time, $M$ is additional memory, and $n$ is `max(self.significant_bits(),
104    /// other.significant_bits())`.
105    ///
106    /// # Examples
107    /// ```
108    /// use malachite_base::num::basic::traits::{
109    ///     Infinity, NaN, NegativeInfinity, NegativeOne, NegativeZero, One, OneHalf, Zero,
110    /// };
111    /// use malachite_float::{ComparableFloatRef, Float};
112    /// use std::cmp::Ordering::*;
113    ///
114    /// assert_eq!(
115    ///     ComparableFloatRef(&Float::NAN).partial_cmp(&ComparableFloatRef(&Float::NAN)),
116    ///     Some(Equal)
117    /// );
118    /// assert!(ComparableFloatRef(&Float::ZERO) > ComparableFloatRef(&Float::NEGATIVE_ZERO));
119    /// assert!(ComparableFloatRef(&Float::ONE) < ComparableFloatRef(&Float::one_prec(100)));
120    /// assert!(ComparableFloatRef(&Float::INFINITY) > ComparableFloatRef(&Float::ONE));
121    /// assert!(ComparableFloatRef(&Float::NEGATIVE_INFINITY) < ComparableFloatRef(&Float::ONE));
122    /// assert!(ComparableFloatRef(&Float::ONE_HALF) < ComparableFloatRef(&Float::ONE));
123    /// assert!(ComparableFloatRef(&Float::ONE_HALF) > ComparableFloatRef(&Float::NEGATIVE_ONE));
124    /// ```
125    fn cmp(&self, other: &ComparableFloatRef<'a>) -> Ordering {
126        match (&self.0, &other.0) {
127            (float_nan!(), float_nan!())
128            | (float_infinity!(), float_infinity!())
129            | (float_negative_infinity!(), float_negative_infinity!()) => Equal,
130            (Float(Zero { sign: s_x }), Float(Zero { sign: s_y })) => s_x.cmp(s_y),
131            (float_infinity!(), _) | (_, float_negative_infinity!()) => Greater,
132            (float_negative_infinity!(), _) | (_, float_infinity!()) => Less,
133            (Float(NaN | Zero { .. }), Float(Finite { sign, .. }))
134            | (Float(NaN), Float(Zero { sign })) => {
135                if *sign {
136                    Less
137                } else {
138                    Greater
139                }
140            }
141            (Float(Finite { sign, .. } | Zero { sign }), Float(NaN))
142            | (Float(Finite { sign, .. }), Float(Zero { .. })) => {
143                if *sign {
144                    Greater
145                } else {
146                    Less
147                }
148            }
149            (
150                Float(Finite {
151                    sign: s_x,
152                    exponent: e_x,
153                    precision: p_x,
154                    significand: x,
155                }),
156                Float(Finite {
157                    sign: s_y,
158                    exponent: e_y,
159                    precision: p_y,
160                    significand: y,
161                }),
162            ) => s_x.cmp(s_y).then_with(|| {
163                let abs_cmp = e_x
164                    .cmp(e_y)
165                    .then_with(|| x.cmp_normalized_no_shift(y))
166                    .then_with(|| p_x.cmp(p_y));
167                if *s_x { abs_cmp } else { abs_cmp.reverse() }
168            }),
169        }
170    }
171}
172
173impl PartialOrd for ComparableFloatRef<'_> {
174    /// Compares two [`ComparableFloatRef`]s.
175    ///
176    /// See the documentation for the [`Ord`] implementation.
177    #[inline]
178    fn partial_cmp(&self, other: &ComparableFloatRef) -> Option<Ordering> {
179        Some(self.cmp(other))
180    }
181}
182
183impl Ord for ComparableFloat {
184    /// Compares two [`ComparableFloat`]s.
185    ///
186    /// This implementation does not follow the IEEE 754 standard. This is how [`ComparableFloat`]s
187    /// are ordered, least to greatest:
188    ///   - $-\infty$
189    ///   - Negative nonzero finite floats
190    ///   - Negative zero
191    ///   - NaN
192    ///   - Positive zero
193    ///   - Positive nonzero finite floats
194    ///   - $\infty$
195    ///
196    /// For different comparison behavior that follows the IEEE 754 standard, consider just using
197    /// [`Float`].
198    ///
199    /// # Worst-case complexity
200    /// $T(n) = O(n)$
201    ///
202    /// $M(n) = O(1)$
203    ///
204    /// where $T$ is time, $M$ is additional memory, and $n$ is `max(self.significant_bits(),
205    /// other.significant_bits())`.
206    ///
207    /// # Examples
208    /// ```
209    /// use malachite_base::num::basic::traits::{
210    ///     Infinity, NaN, NegativeInfinity, NegativeOne, NegativeZero, One, OneHalf, Zero,
211    /// };
212    /// use malachite_float::{ComparableFloat, Float};
213    /// use std::cmp::Ordering::*;
214    ///
215    /// assert_eq!(
216    ///     ComparableFloat(Float::NAN).partial_cmp(&ComparableFloat(Float::NAN)),
217    ///     Some(Equal)
218    /// );
219    /// assert!(ComparableFloat(Float::ZERO) > ComparableFloat(Float::NEGATIVE_ZERO));
220    /// assert!(ComparableFloat(Float::ONE) < ComparableFloat(Float::one_prec(100)));
221    /// assert!(ComparableFloat(Float::INFINITY) > ComparableFloat(Float::ONE));
222    /// assert!(ComparableFloat(Float::NEGATIVE_INFINITY) < ComparableFloat(Float::ONE));
223    /// assert!(ComparableFloat(Float::ONE_HALF) < ComparableFloat(Float::ONE));
224    /// assert!(ComparableFloat(Float::ONE_HALF) > ComparableFloat(Float::NEGATIVE_ONE));
225    /// ```
226    #[inline]
227    fn cmp(&self, other: &ComparableFloat) -> Ordering {
228        self.as_ref().cmp(&other.as_ref())
229    }
230}
231
232impl PartialOrd for ComparableFloat {
233    /// Compares two [`ComparableFloat`]s.
234    ///
235    /// See the documentation for the [`Ord`] implementation.
236    #[inline]
237    fn partial_cmp(&self, other: &ComparableFloat) -> Option<Ordering> {
238        Some(self.as_ref().cmp(&other.as_ref()))
239    }
240}