malachite_nz/integer/conversion/
primitive_float_from_integer.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::integer::Integer;
10use core::cmp::Ordering;
11use malachite_base::num::conversion::traits::{ConvertibleFrom, RoundingFrom};
12use malachite_base::rounding_modes::RoundingMode;
13
14#[derive(Clone, Copy, Debug, Eq, PartialEq)]
15pub struct PrimitiveFloatFromIntegerError;
16
17macro_rules! float_impls {
18    ($f: ident) => {
19        impl<'a> RoundingFrom<&'a Integer> for $f {
20            /// Converts an [`Integer`] to a primitive float according to a specified
21            /// [`RoundingMode`]. An [`Ordering`] is also returned, indicating whether the returned
22            /// value is less than, equal to, or greater than the original value.
23            ///
24            /// - If the rounding mode is `Floor` the largest float less than or equal to the
25            ///   [`Integer`] is returned. If the [`Integer`] is greater than the maximum finite
26            ///   float, then the maximum finite float is returned. If it is smaller than the
27            ///   minimum finite float, then negative infinity is returned.
28            /// - If the rounding mode is `Ceiling`, the smallest float greater than or equal to the
29            ///   [`Integer`] is returned. If the [`Integer`] is greater than the maximum finite
30            ///   float, then positive infinity is returned. If it is smaller than the minimum
31            ///   finite float, then the minimum finite float is returned.
32            /// - If the rounding mode is `Down`, then the rounding proceeds as with `Floor` if the
33            ///   [`Integer`] is non-negative and as with `Ceiling` if the [`Integer`] is negative.
34            /// - If the rounding mode is `Up`, then the rounding proceeds as with `Ceiling` if the
35            ///   [`Integer`] is non-negative and as with `Floor` if the [`Integer`] is negative.
36            /// - If the rounding mode is `Nearest`, then the nearest float is returned. If the
37            ///   [`Integer`] is exactly between two floats, the float with the zero
38            ///   least-significant bit in its representation is selected. If the [`Integer`] is
39            ///   greater than the maximum finite float, then the maximum finite float is returned.
40            ///
41            /// # Worst-case complexity
42            /// $T(n) = O(n)$
43            ///
44            /// $M(n) = O(1)$
45            ///
46            /// where $T$ is time, $M$ is additional memory, and $n$ is `value.significant_bits()`.
47            ///
48            /// # Panics
49            /// Panics if the rounding mode is `Exact` and `value` cannot be represented exactly.
50            ///
51            /// # Examples
52            /// See [here](super::primitive_float_from_integer#rounding_from).
53            fn rounding_from(value: &'a Integer, rm: RoundingMode) -> ($f, Ordering) {
54                if value.sign {
55                    $f::rounding_from(&value.abs, rm)
56                } else {
57                    let (f, o) = $f::rounding_from(&value.abs, -rm);
58                    (-f, o.reverse())
59                }
60            }
61        }
62
63        impl<'a> TryFrom<&'a Integer> for $f {
64            type Error = PrimitiveFloatFromIntegerError;
65
66            /// Converts an [`Integer`] to a primitive float.
67            ///
68            /// If the input isn't exactly equal to some float, an error is returned.
69            ///
70            /// # Worst-case complexity
71            /// $T(n) = O(n)$
72            ///
73            /// $M(n) = O(1)$
74            ///
75            /// where $T$ is time, $M$ is additional memory, and $n$ is `value.significant_bits()`.
76            ///
77            /// # Examples
78            /// See [here](super::primitive_float_from_integer#try_from).
79            fn try_from(value: &'a Integer) -> Result<$f, Self::Error> {
80                $f::try_from(&value.abs)
81                    .map(|f| if value.sign { f } else { -f })
82                    .map_err(|_| PrimitiveFloatFromIntegerError)
83            }
84        }
85
86        impl<'a> ConvertibleFrom<&'a Integer> for $f {
87            /// Determines whether an [`Integer`] can be exactly converted to a primitive float.
88            ///
89            /// # Worst-case complexity
90            /// $T(n) = O(n)$
91            ///
92            /// $M(n) = O(1)$
93            ///
94            /// where $T$ is time, $M$ is additional memory, and $n$ is `value.significant_bits()`.
95            ///
96            /// # Examples
97            /// See [here](super::primitive_float_from_integer#convertible_from).
98            fn convertible_from(value: &'a Integer) -> bool {
99                $f::convertible_from(&value.abs)
100            }
101        }
102    };
103}
104apply_to_primitive_floats!(float_impls);