malachite_q/conversion/
from_primitive_float.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::Rational;
10use malachite_base::num::basic::traits::Zero;
11use malachite_base::num::conversion::traits::{ConvertibleFrom, IntegerMantissaAndExponent};
12
13#[derive(Clone, Copy, Debug, Eq, PartialEq)]
14pub struct RationalFromPrimitiveFloatError;
15
16macro_rules! float_impls {
17    ($f: ident) => {
18        impl TryFrom<$f> for Rational {
19            type Error = RationalFromPrimitiveFloatError;
20
21            /// Converts a primitive float to the equivalent [`Rational`]. If the floating point
22            /// value is `NaN` or infinite, an error is returned.
23            ///
24            /// This conversion is literal. For example, `Rational::try_from(0.1f32)` evaluates to
25            /// Some($13421773/134217728$). If you want $1/10$ instead, use
26            /// [`try_from_float_simplest`](Rational::try_from_float_simplest); that function
27            /// returns the simplest [`Rational`] that rounds to the specified float.
28            ///
29            /// # Worst-case complexity
30            /// $T(n) = O(n)$
31            ///
32            /// $M(n) = O(n)$
33            ///
34            /// where $T$ is time, $M$ is additional memory, and $n$ is
35            /// `value.sci_exponent().abs()`.
36            ///
37            /// # Examples
38            /// See [here](super::from_primitive_float#try_from).
39            fn try_from(value: $f) -> Result<Rational, Self::Error> {
40                if !value.is_finite() {
41                    Err(RationalFromPrimitiveFloatError)
42                } else if value == 0.0 {
43                    Ok(Rational::ZERO)
44                } else {
45                    let (mantissa, exponent) = value.integer_mantissa_and_exponent();
46                    let x = Rational::from(mantissa) << exponent;
47                    Ok(if value > 0.0 { x } else { -x })
48                }
49            }
50        }
51
52        impl ConvertibleFrom<$f> for Rational {
53            /// Determines whether a primitive float can be converted to a [`Rational`]. (It can if
54            /// it is finite.)
55            ///
56            /// # Worst-case complexity
57            /// Constant time and additional memory.
58            ///
59            /// # Examples
60            /// See [here](super::from_primitive_float#convertible_from).
61            fn convertible_from(x: $f) -> bool {
62                x.is_finite()
63            }
64        }
65    };
66}
67apply_to_primitive_floats!(float_impls);