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 $-\infty$ 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 $\infty$ is returned. If it is smaller than the minimum finite float,
31            ///   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 $\infty$ is returned. If the
40            ///   [`Integer`] is smaller than the minimum finite float, then $-\infty$ is returned.
41            ///
42            /// # Worst-case complexity
43            /// $T(n) = O(n)$
44            ///
45            /// $M(n) = O(1)$
46            ///
47            /// where $T$ is time, $M$ is additional memory, and $n$ is `value.significant_bits()`.
48            ///
49            /// # Panics
50            /// Panics if the rounding mode is `Exact` and `value` cannot be represented exactly.
51            ///
52            /// # Examples
53            /// See [here](super::primitive_float_from_integer#rounding_from).
54            fn rounding_from(value: &'a Integer, rm: RoundingMode) -> ($f, Ordering) {
55                if value.sign {
56                    $f::rounding_from(&value.abs, rm)
57                } else {
58                    let (f, o) = $f::rounding_from(&value.abs, -rm);
59                    (-f, o.reverse())
60                }
61            }
62        }
63
64        impl<'a> TryFrom<&'a Integer> for $f {
65            type Error = PrimitiveFloatFromIntegerError;
66
67            /// Converts an [`Integer`] to a primitive float.
68            ///
69            /// If the input isn't exactly equal to some float, an error is returned.
70            ///
71            /// # Worst-case complexity
72            /// $T(n) = O(n)$
73            ///
74            /// $M(n) = O(1)$
75            ///
76            /// where $T$ is time, $M$ is additional memory, and $n$ is `value.significant_bits()`.
77            ///
78            /// # Examples
79            /// See [here](super::primitive_float_from_integer#try_from).
80            fn try_from(value: &'a Integer) -> Result<$f, Self::Error> {
81                $f::try_from(&value.abs)
82                    .map(|f| if value.sign { f } else { -f })
83                    .map_err(|_| PrimitiveFloatFromIntegerError)
84            }
85        }
86
87        impl<'a> ConvertibleFrom<&'a Integer> for $f {
88            /// Determines whether an [`Integer`] can be exactly converted to a primitive float.
89            ///
90            /// # Worst-case complexity
91            /// $T(n) = O(n)$
92            ///
93            /// $M(n) = O(1)$
94            ///
95            /// where $T$ is time, $M$ is additional memory, and $n$ is `value.significant_bits()`.
96            ///
97            /// # Examples
98            /// See [here](super::primitive_float_from_integer#convertible_from).
99            fn convertible_from(value: &'a Integer) -> bool {
100                $f::convertible_from(&value.abs)
101            }
102        }
103    };
104}
105apply_to_primitive_floats!(float_impls);