Skip to main content

malachite_nz/natural/comparison/
partial_eq_primitive_float.rs

1// Copyright © 2026 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::natural::Natural;
10use core::cmp::Ordering::*;
11use malachite_base::num::conversion::traits::IntegerMantissaAndExponent;
12use malachite_base::num::logic::traits::SignificantBits;
13
14macro_rules! impl_float {
15    ($t: ident) => {
16        impl PartialEq<$t> for Natural {
17            /// Determines whether a [`Natural`] is equal to a primitive float.
18            ///
19            /// # Worst-case complexity
20            /// $T(n) = O(n)$
21            ///
22            /// $M(n) = O(1)$
23            ///
24            /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
25            ///
26            /// # Examples
27            /// See [here](super::partial_eq_primitive_float#partial_eq).
28            fn eq(&self, other: &$t) -> bool {
29                if !other.is_finite() {
30                    false
31                } else if *other == 0.0 {
32                    *self == 0u32
33                } else if *other < 1.0 || *self == 0u32 {
34                    false
35                } else {
36                    let (m, e) = other.integer_mantissa_and_exponent();
37                    if let Ok(e) = u64::try_from(e) {
38                        self.significant_bits() == m.significant_bits() + e
39                            && self.cmp_normalized(&Natural::from(m)) == Equal
40                    } else {
41                        false
42                    }
43                }
44            }
45        }
46
47        impl PartialEq<Natural> for $t {
48            /// Determines whether a primitive float is equal to a [`Natural`].
49            ///
50            /// # Worst-case complexity
51            /// $T(n) = O(n)$
52            ///
53            /// $M(n) = O(1)$
54            ///
55            /// where $T$ is time, $M$ is additional memory, and $n$ is `other.significant_bits()`.
56            ///
57            /// # Examples
58            /// See [here](super::partial_eq_primitive_float#partial_eq).
59            #[inline]
60            fn eq(&self, other: &Natural) -> bool {
61                other == self
62            }
63        }
64    };
65}
66apply_to_primitive_floats!(impl_float);