Skip to main content

malachite_base/num/basic/
floats.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::comparison::traits::{Max, Min};
10use crate::named::Named;
11use crate::num::arithmetic::traits::{
12    Abs, AbsAssign, AddMul, AddMulAssign, Ceiling, CeilingAssign, CeilingLogBase2,
13    CeilingLogBasePowerOf2, CheckedLogBase2, CheckedLogBasePowerOf2, Floor, FloorAssign,
14    FloorLogBase2, FloorLogBasePowerOf2, IsPowerOf2, NegAssign, NextPowerOf2, NextPowerOf2Assign,
15    Pow, PowAssign, PowerOf2, Reciprocal, ReciprocalAssign, Sign, Sqrt, SqrtAssign, Square,
16    SquareAssign, SubMul, SubMulAssign,
17};
18use crate::num::basic::traits::{
19    GaussConstant, GelfondSchneiderConstant, GelfondsConstant, Infinity, LemniscateConstant, Ln2,
20    Ln10, Log2E, Log10E, Log102, Log210, NaN, NegativeInfinity, NegativeOne, NegativeZero, One,
21    OneHalf, OneOverPi, OneOverSqrtPi, OneOverSqrtTau, Phi, Pi, PiOver2, PiOver3, PiOver4, PiOver6,
22    PiOver8, PrimeConstant, ProuhetThueMorseConstant, RamanujansConstant, Sqrt2, Sqrt2Over2, Sqrt3,
23    Sqrt3Over3, Sqrt5, Sqrt5Over5, SqrtPi, Tau, Two, TwoOverPi, TwoOverSqrtPi, Zero,
24};
25use crate::num::comparison::traits::{EqAbs, PartialOrdAbs};
26use crate::num::conversion::traits::{
27    ConvertibleFrom, ExactInto, IntegerMantissaAndExponent, IsInteger, RawMantissaAndExponent,
28    RoundingFrom, RoundingInto, SciMantissaAndExponent, WrappingFrom,
29};
30use crate::num::float::FmtRyuString;
31use crate::num::logic::traits::{BitAccess, LowMask, SignificantBits, TrailingZeros};
32use core::cmp::Ordering::*;
33use core::fmt::{Debug, Display, LowerExp, UpperExp};
34use core::iter::{Product, Sum};
35use core::num::FpCategory;
36use core::ops::{
37    Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, RemAssign, Sub, SubAssign,
38};
39use core::panic::RefUnwindSafe;
40use core::str::FromStr;
41
42/// This trait defines functions on primitive float types: [`f32`] and [`f64`].
43///
44/// Many of the functions here concern exponents and mantissas. We define three ways to express a
45/// float, each with its own exponent and mantissa. In the following, let $x$ be an arbitrary
46/// positive, finite, non-zero, non-NaN float. Let $M$ and $E$ be the mantissa width and exponent
47/// width of the floating point type; for [`f32`]s, this is 23 and 8, and for [`f64`]s it's 52 and
48/// 11.
49///
50/// In the following we assume that $x$ is positive, but you can easily extend these definitions to
51/// negative floats by first taking their absolute value.
52///
53/// # raw form
54/// The raw exponent and raw mantissa are the actual bit patterns used to represent the components
55/// of $x$. The raw exponent $e_r$ is an integer in $[0, 2^E-2]$ and the raw mantissa $m_r$ is an
56/// integer in $[0, 2^M-1]$. Since we are dealing with a nonzero $x$, we forbid $e_r$ and $m_r$ from
57/// both being zero. We have
58/// $$
59/// x = \\begin{cases}
60///     2^{2-2^{E-1}-M}m_r & \text{if} \quad e_r = 0, \\\\
61///     2^{e_r-2^{E-1}+1}(2^{-M}m_r+1) & \textrm{otherwise},
62/// \\end{cases}
63/// $$
64/// $$
65/// e_r = \\begin{cases}
66///     0 & \text{if} \quad x < 2^{2-2^{E-1}}, \\\\
67///     \lfloor \log_2 x \rfloor + 2^{E-1} - 1 & \textrm{otherwise},
68/// \\end{cases}
69/// $$
70/// $$
71/// m_r = \\begin{cases}
72///     2^{M+2^{E-1}-2}x & \text{if} \quad x < 2^{2-2^{E-1}}, \\\\
73///     2^M \left ( \frac{x}{2^{\lfloor \log_2 x \rfloor}}-1\right ) & \textrm{otherwise}.
74/// \\end{cases}
75/// $$
76///
77/// # scientific form
78/// We can write $x = 2^{e_s}m_s$, where $e_s$ is an integer and $m_s$ is a rational number with $1
79/// \leq m_s < 2$. If $x$ is a valid float, the scientific mantissa $m_s$ is always exactly
80/// representable as a float of the same type. We have
81/// $$
82/// x = 2^{e_s}m_s,
83/// $$
84/// $$
85/// e_s = \lfloor \log_2 x \rfloor,
86/// $$
87/// $$
88/// m_s = \frac{x}{2^{\lfloor \log_2 x \rfloor}}.
89/// $$
90///
91/// # integer form
92/// We can also write $x = 2^{e_i}m_i$, where $e_i$ is an integer and $m_i$ is an odd integer. We
93/// have
94/// $$
95/// x = 2^{e_i}m_i,
96/// $$
97/// $e_i$ is the unique integer such that $x/2^{e_i}$is an odd integer, and
98/// $$
99/// m_i = \frac{x}{2^{e_i}}.
100/// $$
101pub trait PrimitiveFloat:
102    'static
103    + Abs<Output = Self>
104    + AbsAssign
105    + Add<Output = Self>
106    + AddAssign<Self>
107    + AddMul<Output = Self>
108    + AddMulAssign<Self, Self>
109    + Ceiling<Output = Self>
110    + CeilingAssign
111    + CeilingLogBase2<Output = i64>
112    + CeilingLogBasePowerOf2<u64, Output = i64>
113    + CheckedLogBase2<Output = i64>
114    + CheckedLogBasePowerOf2<u64, Output = i64>
115    + ConvertibleFrom<u8>
116    + ConvertibleFrom<u16>
117    + ConvertibleFrom<u32>
118    + ConvertibleFrom<u64>
119    + ConvertibleFrom<u128>
120    + ConvertibleFrom<usize>
121    + ConvertibleFrom<i8>
122    + ConvertibleFrom<i16>
123    + ConvertibleFrom<i32>
124    + ConvertibleFrom<i64>
125    + ConvertibleFrom<i128>
126    + ConvertibleFrom<isize>
127    + Copy
128    + Debug
129    + Default
130    + Display
131    + Div<Output = Self>
132    + DivAssign
133    + EqAbs<Self>
134    + Floor<Output = Self>
135    + FloorAssign
136    + FloorLogBase2<Output = i64>
137    + FloorLogBasePowerOf2<u64, Output = i64>
138    + FmtRyuString
139    + From<f32>
140    + FromStr
141    + GaussConstant
142    + GelfondSchneiderConstant
143    + GelfondsConstant
144    + Infinity
145    + IntegerMantissaAndExponent<u64, i64>
146    + Into<f64>
147    + IsInteger
148    + IsPowerOf2
149    + LemniscateConstant
150    + Log2E
151    + Log10E
152    + Log210
153    + Log102
154    + Ln2
155    + Ln10
156    + LowerExp
157    + Min
158    + Max
159    + Mul<Output = Self>
160    + MulAssign<Self>
161    + Named
162    + NaN
163    + NegativeInfinity
164    + NegativeZero
165    + Neg<Output = Self>
166    + NegAssign
167    + NegativeOne
168    + NextPowerOf2<Output = Self>
169    + NextPowerOf2Assign
170    + One
171    + OneHalf
172    + OneOverPi
173    + OneOverSqrtPi
174    + OneOverSqrtTau
175    + PartialEq<Self>
176    + PartialOrd<Self>
177    + PartialOrdAbs<Self>
178    + Phi
179    + Pi
180    + PiOver2
181    + PiOver3
182    + PiOver4
183    + PiOver6
184    + PiOver8
185    + Pow<i64, Output = Self>
186    + Pow<Self, Output = Self>
187    + PowAssign<i64>
188    + PowAssign<Self>
189    + PowerOf2<i64>
190    + PowerOf2<u64>
191    + PrimeConstant
192    + Product
193    + RamanujansConstant
194    + RawMantissaAndExponent<u64, u64>
195    + Reciprocal<Output = Self>
196    + ReciprocalAssign
197    + RefUnwindSafe
198    + Rem<Output = Self>
199    + RemAssign<Self>
200    + RoundingFrom<u8>
201    + RoundingFrom<u16>
202    + RoundingFrom<u32>
203    + RoundingFrom<u64>
204    + RoundingFrom<u128>
205    + RoundingFrom<usize>
206    + RoundingFrom<i8>
207    + RoundingFrom<i16>
208    + RoundingFrom<i32>
209    + RoundingFrom<i64>
210    + RoundingFrom<i128>
211    + RoundingFrom<isize>
212    + RoundingInto<u8>
213    + RoundingInto<u16>
214    + RoundingInto<u32>
215    + RoundingInto<u64>
216    + RoundingInto<u128>
217    + RoundingInto<usize>
218    + RoundingInto<i8>
219    + RoundingInto<i16>
220    + RoundingInto<i32>
221    + RoundingInto<i64>
222    + RoundingInto<i128>
223    + RoundingInto<isize>
224    + SciMantissaAndExponent<Self, i64>
225    + Sign
226    + Sized
227    + Sqrt<Output = Self>
228    + SqrtAssign
229    + Sqrt2
230    + Sqrt2Over2
231    + Sqrt3
232    + Sqrt3Over3
233    + Sqrt5
234    + Sqrt5Over5
235    + SqrtPi
236    + Square<Output = Self>
237    + SquareAssign
238    + Sub<Output = Self>
239    + SubAssign<Self>
240    + SubMul<Output = Self>
241    + SubMulAssign<Self, Self>
242    + Sum<Self>
243    + ProuhetThueMorseConstant
244    + Tau
245    + Two
246    + TwoOverPi
247    + TwoOverSqrtPi
248    + UpperExp
249    + Zero
250{
251    /// The number of bits taken up by the type.
252    ///
253    /// This is $M+E+1$. The three terms in the sum correspond to the width of the mantissa, the
254    /// width of the exponent, and the sign bit.
255    /// - For [`f32`]s, this is 32.
256    /// - For [`f64`]s, this is 64.
257    const WIDTH: u64;
258    /// The number of bits taken up by the exponent.
259    /// - For [`f32`]s, this is 8.
260    /// - For [`f64`]s, this is 11.
261    const EXPONENT_WIDTH: u64 = Self::WIDTH - Self::MANTISSA_WIDTH - 1;
262    /// The number of bits taken up by the mantissa.
263    /// - For [`f32`]s, this is 23.
264    /// - For [`f64`]s, this is 52.
265    const MANTISSA_WIDTH: u64;
266    /// The smallest possible exponent of a float in the normal range. Any floats with smaller
267    /// exponents are subnormal and thus have reduced precision. This is $2-2^{E-1}$.
268    /// - For [`f32`]s, this is -126.
269    /// - For [`f64`]s, this is -1022.
270    const MIN_NORMAL_EXPONENT: i64 = -(1 << (Self::EXPONENT_WIDTH - 1)) + 2;
271    /// The smallest possible exponent of a float. This is $2-2^{E-1}-M$.
272    /// - For [`f32`]s, this is -149.
273    /// - For [`f64`]s, this is -1074.
274    const MIN_EXPONENT: i64 = Self::MIN_NORMAL_EXPONENT - (Self::MANTISSA_WIDTH as i64);
275    /// The largest possible exponent of a float. This is $2^{E-1}-1$.
276    /// - For [`f32`]s, this is 127.
277    /// - For [`f64`]s, this is 1023.
278    const MAX_EXPONENT: i64 = (1 << (Self::EXPONENT_WIDTH - 1)) - 1;
279    /// The smallest positive float. This is $2^{2-2^{E-1}-M}$.
280    /// - For [`f32`]s, this is $2^{-149}$, or `1.0e-45`.
281    /// - For [`f64`]s, this is $2^{-1074}$, or `5.0e-324`.
282    const MIN_POSITIVE_SUBNORMAL: Self;
283    /// The largest float in the subnormal range. This is $2^{2-2^{E-1}-M}(2^M-1)$.
284    /// - For [`f32`]s, this is $2^{-149}(2^{23}-1)$, or `1.1754942e-38`.
285    /// - For [`f64`]s, this is $2^{-1074}(2^{52}-1)$, or `2.225073858507201e-308`.
286    const MAX_SUBNORMAL: Self;
287    /// The smallest positive normal float. This is $2^{2-2^{E-1}}$.
288    /// - For [`f32`]s, this is $2^{-126}$, or `1.1754944e-38`.
289    /// - For [`f64`]s, this is $2^{-1022}$, or `2.2250738585072014e-308`.
290    const MIN_POSITIVE_NORMAL: Self;
291    /// The largest finite float. This is $2^{2^{E-1}-1}(2-2^{-M})$.
292    /// - For [`f32`]s, this is $2^{127}(2-2^{-23})$, or `3.4028235e38`.
293    /// - For [`f64`]s, this is $2^{1023}(2-2^{-52})$, or `1.7976931348623157e308`.
294    const MAX_FINITE: Self;
295    /// The smallest positive integer that cannot be represented as a float. This is $2^{M+1}+1$.
296    /// - For [`f32`]s, this is $2^{24}+1$, or 16777217.
297    /// - For [`f64`]s, this is $2^{53}+1$, or 9007199254740993.
298    const SMALLEST_UNREPRESENTABLE_UINT: u64;
299    /// If you list all floats in increasing order, excluding NaN and giving negative and positive
300    /// zero separate adjacent spots, this will be index of the last element, positive infinity. It
301    /// is $2^{M+1}(2^E-1)+1$.
302    /// - For [`f32`]s, this is $2^{32}-2^{24}+1$, or 4278190081.
303    /// - For [`f64`]s, this is $2^{64}-2^{53}+1$, or 18437736874454810625.
304    const LARGEST_ORDERED_REPRESENTATION: u64;
305
306    fn is_nan(self) -> bool;
307
308    fn is_infinite(self) -> bool;
309
310    fn is_finite(self) -> bool;
311
312    fn is_normal(self) -> bool;
313
314    fn is_sign_positive(self) -> bool;
315
316    fn is_sign_negative(self) -> bool;
317
318    fn classify(self) -> FpCategory;
319
320    fn to_bits(self) -> u64;
321
322    fn from_bits(v: u64) -> Self;
323
324    /// Tests whether `self` is negative zero.
325    ///
326    /// # Worst-case complexity
327    /// Constant time and additional memory.
328    ///
329    /// # Examples
330    /// ```
331    /// use malachite_base::num::basic::floats::PrimitiveFloat;
332    ///
333    /// assert!((-0.0).is_negative_zero());
334    /// assert!(!0.0.is_negative_zero());
335    /// assert!(!1.0.is_negative_zero());
336    /// assert!(!f32::NAN.is_negative_zero());
337    /// assert!(!f32::INFINITY.is_negative_zero());
338    /// ```
339    #[inline]
340    fn is_negative_zero(self) -> bool {
341        self.sign() == Less && self == Self::ZERO
342    }
343
344    /// If `self` is negative zero, returns positive zero; otherwise, returns `self`.
345    ///
346    /// # Worst-case complexity
347    /// Constant time and additional memory.
348    ///
349    /// # Examples
350    /// ```
351    /// use malachite_base::num::basic::floats::PrimitiveFloat;
352    /// use malachite_base::num::float::NiceFloat;
353    ///
354    /// assert_eq!(NiceFloat((-0.0).abs_negative_zero()), NiceFloat(0.0));
355    /// assert_eq!(NiceFloat(0.0.abs_negative_zero()), NiceFloat(0.0));
356    /// assert_eq!(NiceFloat(1.0.abs_negative_zero()), NiceFloat(1.0));
357    /// assert_eq!(NiceFloat((-1.0).abs_negative_zero()), NiceFloat(-1.0));
358    /// assert_eq!(NiceFloat(f32::NAN.abs_negative_zero()), NiceFloat(f32::NAN));
359    /// ```
360    #[inline]
361    fn abs_negative_zero(self) -> Self {
362        if self == Self::ZERO { Self::ZERO } else { self }
363    }
364
365    /// If `self` is negative zero, replaces it with positive zero; otherwise, leaves `self`
366    /// unchanged.
367    ///
368    /// # Worst-case complexity
369    /// Constant time and additional memory.
370    ///
371    /// # Examples
372    /// ```
373    /// use malachite_base::num::basic::floats::PrimitiveFloat;
374    /// use malachite_base::num::float::NiceFloat;
375    ///
376    /// let mut f = -0.0;
377    /// f.abs_negative_zero_assign();
378    /// assert_eq!(NiceFloat(f), NiceFloat(0.0));
379    ///
380    /// let mut f = 0.0;
381    /// f.abs_negative_zero_assign();
382    /// assert_eq!(NiceFloat(f), NiceFloat(0.0));
383    ///
384    /// let mut f = 1.0;
385    /// f.abs_negative_zero_assign();
386    /// assert_eq!(NiceFloat(f), NiceFloat(1.0));
387    ///
388    /// let mut f = -1.0;
389    /// f.abs_negative_zero_assign();
390    /// assert_eq!(NiceFloat(f), NiceFloat(-1.0));
391    ///
392    /// let mut f = f32::NAN;
393    /// f.abs_negative_zero_assign();
394    /// assert_eq!(NiceFloat(f), NiceFloat(f32::NAN));
395    /// ```
396    #[inline]
397    fn abs_negative_zero_assign(&mut self) {
398        if *self == Self::ZERO {
399            *self = Self::ZERO;
400        }
401    }
402
403    /// Returns the smallest float larger than `self`.
404    ///
405    /// Passing `-0.0` returns `0.0`; passing `NaN` or positive infinity panics.
406    ///
407    /// # Worst-case complexity
408    /// Constant time and additional memory.
409    ///
410    /// # Panics
411    /// Panics if `self` is `NaN` or positive infinity.
412    ///
413    /// # Examples
414    /// ```
415    /// use malachite_base::num::basic::floats::PrimitiveFloat;
416    /// use malachite_base::num::float::NiceFloat;
417    ///
418    /// assert_eq!(NiceFloat((-0.0f32).next_higher()), NiceFloat(0.0));
419    /// assert_eq!(NiceFloat(0.0f32.next_higher()), NiceFloat(1.0e-45));
420    /// assert_eq!(NiceFloat(1.0f32.next_higher()), NiceFloat(1.0000001));
421    /// assert_eq!(NiceFloat((-1.0f32).next_higher()), NiceFloat(-0.99999994));
422    /// ```
423    fn next_higher(self) -> Self {
424        assert!(!self.is_nan());
425        if self.sign() == Greater {
426            assert_ne!(self, Self::INFINITY);
427            Self::from_bits(self.to_bits() + 1)
428        } else if self == Self::ZERO {
429            // negative zero -> positive zero
430            Self::ZERO
431        } else {
432            Self::from_bits(self.to_bits() - 1)
433        }
434    }
435
436    /// Returns the largest float smaller than `self`.
437    ///
438    /// Passing `0.0` returns `-0.0`; passing `NaN` or negative infinity panics.
439    ///
440    /// # Worst-case complexity
441    /// Constant time and additional memory.
442    ///
443    /// # Panics
444    /// Panics if `self` is `NaN` or negative infinity.
445    ///
446    /// # Examples
447    /// ```
448    /// use malachite_base::num::basic::floats::PrimitiveFloat;
449    /// use malachite_base::num::float::NiceFloat;
450    ///
451    /// assert_eq!(NiceFloat(0.0f32.next_lower()), NiceFloat(-0.0));
452    /// assert_eq!(NiceFloat((-0.0f32).next_lower()), NiceFloat(-1.0e-45));
453    /// assert_eq!(NiceFloat(1.0f32.next_lower()), NiceFloat(0.99999994));
454    /// assert_eq!(NiceFloat((-1.0f32).next_lower()), NiceFloat(-1.0000001));
455    /// ```
456    fn next_lower(self) -> Self {
457        assert!(!self.is_nan());
458        if self.sign() == Less {
459            assert_ne!(self, Self::NEGATIVE_INFINITY);
460            Self::from_bits(self.to_bits() + 1)
461        } else if self == Self::ZERO {
462            // positive zero -> negative zero
463            Self::NEGATIVE_ZERO
464        } else {
465            Self::from_bits(self.to_bits() - 1)
466        }
467    }
468
469    /// Maps `self` to an integer. The map preserves ordering, and adjacent floats are mapped to
470    /// adjacent integers.
471    ///
472    /// Negative infinity is mapped to 0, and positive infinity is mapped to the largest value,
473    /// [`LARGEST_ORDERED_REPRESENTATION`](PrimitiveFloat::LARGEST_ORDERED_REPRESENTATION). Negative
474    /// and positive zero are mapped to distinct adjacent values. Passing in `NaN` panics.
475    ///
476    /// The inverse operation is
477    /// [`from_ordered_representation`](PrimitiveFloat::from_ordered_representation).
478    ///
479    /// # Worst-case complexity
480    /// Constant time and additional memory.
481    ///
482    /// # Panics
483    /// Panics if `self` is `NaN`.
484    ///
485    /// # Examples
486    /// ```
487    /// use malachite_base::num::basic::floats::PrimitiveFloat;
488    /// use malachite_base::num::basic::traits::NegativeInfinity;
489    ///
490    /// assert_eq!(f32::NEGATIVE_INFINITY.to_ordered_representation(), 0);
491    /// assert_eq!((-0.0f32).to_ordered_representation(), 2139095040);
492    /// assert_eq!(0.0f32.to_ordered_representation(), 2139095041);
493    /// assert_eq!(1.0f32.to_ordered_representation(), 3204448257);
494    /// assert_eq!(f32::INFINITY.to_ordered_representation(), 4278190081);
495    /// ```
496    fn to_ordered_representation(self) -> u64 {
497        assert!(!self.is_nan());
498        let bits = self.to_bits();
499        if self.sign() == Greater {
500            (u64::low_mask(Self::EXPONENT_WIDTH) << Self::MANTISSA_WIDTH) + bits + 1
501        } else {
502            (u64::low_mask(Self::EXPONENT_WIDTH + 1) << Self::MANTISSA_WIDTH) - bits
503        }
504    }
505
506    /// Maps a non-negative integer, less than or equal to
507    /// [`LARGEST_ORDERED_REPRESENTATION`](PrimitiveFloat::LARGEST_ORDERED_REPRESENTATION), to a
508    /// float. The map preserves ordering, and adjacent integers are mapped to adjacent floats.
509    ///
510    /// Zero is mapped to negative infinity, and
511    /// [`LARGEST_ORDERED_REPRESENTATION`](PrimitiveFloat::LARGEST_ORDERED_REPRESENTATION) is mapped
512    /// to positive infinity. Negative and positive zero are produced by two distinct adjacent
513    /// integers. `NaN` is never produced.
514    ///
515    /// The inverse operation is
516    /// [`to_ordered_representation`](PrimitiveFloat::to_ordered_representation).
517    ///
518    /// # Worst-case complexity
519    /// Constant time and additional memory.
520    ///
521    /// # Panics
522    /// Panics if `self` is greater than
523    /// [`LARGEST_ORDERED_REPRESENTATION`](PrimitiveFloat::LARGEST_ORDERED_REPRESENTATION).
524    ///
525    /// # Examples
526    /// ```
527    /// use malachite_base::num::basic::floats::PrimitiveFloat;
528    /// use malachite_base::num::basic::traits::NegativeInfinity;
529    ///
530    /// assert_eq!(f32::from_ordered_representation(0), f32::NEGATIVE_INFINITY);
531    /// assert_eq!(f32::from_ordered_representation(2139095040), -0.0f32);
532    /// assert_eq!(f32::from_ordered_representation(2139095041), 0.0f32);
533    /// assert_eq!(f32::from_ordered_representation(3204448257), 1.0f32);
534    /// assert_eq!(f32::from_ordered_representation(4278190081), f32::INFINITY);
535    /// ```
536    fn from_ordered_representation(n: u64) -> Self {
537        let zero_exp = u64::low_mask(Self::EXPONENT_WIDTH) << Self::MANTISSA_WIDTH;
538        let f = if n <= zero_exp {
539            Self::from_bits((u64::low_mask(Self::EXPONENT_WIDTH + 1) << Self::MANTISSA_WIDTH) - n)
540        } else {
541            let f = Self::from_bits(n - zero_exp - 1);
542            assert_eq!(f.sign(), Greater);
543            f
544        };
545        assert!(!f.is_nan());
546        f
547    }
548
549    /// Returns the precision of a nonzero finite floating-point number.
550    ///
551    /// The precision is the number of significant bits of the integer mantissa. For example, the
552    /// positive floats with precision 1 are the powers of 2, those with precision 2 are 3 times a
553    /// power of 2, those with precision 3 are 5 or 7 times a power of 2, and so on.
554    ///
555    /// # Worst-case complexity
556    /// Constant time and additional memory.
557    ///
558    /// # Panics
559    /// Panics if `self` is zero, infinite, or `NaN`.
560    ///
561    /// # Examples
562    /// ```
563    /// use malachite_base::num::basic::floats::PrimitiveFloat;
564    ///
565    /// assert_eq!(1.0.precision(), 1);
566    /// assert_eq!(2.0.precision(), 1);
567    /// assert_eq!(3.0.precision(), 2);
568    /// assert_eq!(1.5.precision(), 2);
569    /// assert_eq!(1.234f32.precision(), 23);
570    /// ```
571    fn precision(self) -> u64 {
572        assert!(self.is_finite());
573        assert!(self != Self::ZERO);
574        let (mut mantissa, exponent) = self.raw_mantissa_and_exponent();
575        if exponent == 0 {
576            mantissa.significant_bits() - TrailingZeros::trailing_zeros(mantissa)
577        } else {
578            mantissa.set_bit(Self::MANTISSA_WIDTH);
579            Self::MANTISSA_WIDTH + 1 - TrailingZeros::trailing_zeros(mantissa)
580        }
581    }
582
583    /// Given a scientific exponent, returns the largest possible precision for a float with that
584    /// exponent.
585    ///
586    /// See the documentation of the [`precision`](PrimitiveFloat::precision) function for a
587    /// definition of precision.
588    ///
589    /// For exponents greater than or equal to
590    /// [`MIN_NORMAL_EXPONENT`](PrimitiveFloat::MIN_NORMAL_EXPONENT), the maximum precision is one
591    /// more than the mantissa width. For smaller exponents (corresponding to the subnormal range),
592    /// the precision is lower.
593    ///
594    /// # Worst-case complexity
595    /// Constant time and additional memory.
596    ///
597    /// # Panics
598    /// Panics if `exponent` is less than [`MIN_EXPONENT`](PrimitiveFloat::MIN_EXPONENT) or greater
599    /// than [`MAX_EXPONENT`](PrimitiveFloat::MAX_EXPONENT).
600    ///
601    /// # Examples
602    /// ```
603    /// use malachite_base::num::basic::floats::PrimitiveFloat;
604    ///
605    /// assert_eq!(f32::max_precision_for_sci_exponent(0), 24);
606    /// assert_eq!(f32::max_precision_for_sci_exponent(127), 24);
607    /// assert_eq!(f32::max_precision_for_sci_exponent(-149), 1);
608    /// assert_eq!(f32::max_precision_for_sci_exponent(-148), 2);
609    /// assert_eq!(f32::max_precision_for_sci_exponent(-147), 3);
610    /// ```
611    fn max_precision_for_sci_exponent(exponent: i64) -> u64 {
612        assert!(exponent >= Self::MIN_EXPONENT);
613        assert!(exponent <= Self::MAX_EXPONENT);
614        if exponent >= Self::MIN_NORMAL_EXPONENT {
615            Self::MANTISSA_WIDTH + 1
616        } else {
617            u64::wrapping_from(exponent - Self::MIN_EXPONENT) + 1
618        }
619    }
620}
621
622/// Defines basic trait implementations for floating-point types.
623macro_rules! impl_basic_traits_primitive_float {
624    (
625        $t: ident,
626        $width: expr,
627        $min_positive_subnormal: expr,
628        $max_subnormal: expr,
629        $min_positive_normal: expr,
630        $prouhet_thue_morse_constant: expr,
631        $prime_constant: expr,
632        $sqrt_3: expr,
633        $sqrt_5: expr,
634        $sqrt_3_over_3: expr,
635        $sqrt_5_over_5: expr,
636        $phi: expr,
637        $sqrt_pi: expr,
638        $one_over_sqrt_pi: expr,
639        $one_over_sqrt_tau: expr,
640        $gauss_constant: expr,
641        $gelfonds_constant: expr,
642        $gelfond_schneider_constant: expr,
643        $lemniscate_constant: expr,
644        $ramanujans_constant: expr
645    ) => {
646        impl PrimitiveFloat for $t {
647            const WIDTH: u64 = $width;
648            const MANTISSA_WIDTH: u64 = ($t::MANTISSA_DIGITS as u64) - 1;
649
650            const MAX_FINITE: Self = $t::MAX;
651            const MIN_POSITIVE_SUBNORMAL: Self = $min_positive_subnormal;
652            const MAX_SUBNORMAL: Self = $max_subnormal;
653            const MIN_POSITIVE_NORMAL: Self = $min_positive_normal;
654            const SMALLEST_UNREPRESENTABLE_UINT: u64 = (1 << (Self::MANTISSA_WIDTH + 1)) + 1;
655            // We can't shift by $width when $width is 64, so we shift by $width - 1 and then by 1
656            const LARGEST_ORDERED_REPRESENTATION: u64 = (1u64 << ($width - 1) << 1)
657                .wrapping_sub(((1 << Self::MANTISSA_WIDTH) - 1) << 1)
658                - 1;
659
660            #[inline]
661            fn is_nan(self) -> bool {
662                $t::is_nan(self)
663            }
664
665            #[inline]
666            fn is_infinite(self) -> bool {
667                $t::is_infinite(self)
668            }
669
670            #[inline]
671            fn is_finite(self) -> bool {
672                $t::is_finite(self)
673            }
674
675            #[inline]
676            fn is_normal(self) -> bool {
677                $t::is_normal(self)
678            }
679
680            #[inline]
681            fn is_sign_positive(self) -> bool {
682                $t::is_sign_positive(self)
683            }
684
685            #[inline]
686            fn is_sign_negative(self) -> bool {
687                $t::is_sign_negative(self)
688            }
689
690            #[inline]
691            fn classify(self) -> FpCategory {
692                $t::classify(self)
693            }
694
695            #[inline]
696            fn to_bits(self) -> u64 {
697                u64::wrapping_from($t::to_bits(self))
698            }
699
700            #[inline]
701            fn from_bits(v: u64) -> $t {
702                $t::from_bits(v.exact_into())
703            }
704        }
705
706        impl_named!($t);
707
708        /// The constant 0.
709        impl Zero for $t {
710            const ZERO: $t = 0.0;
711        }
712
713        /// The constant 1.
714        impl One for $t {
715            const ONE: $t = 1.0;
716        }
717
718        /// The constant 2.
719        impl Two for $t {
720            const TWO: $t = 2.0;
721        }
722
723        /// The constant 1/2.
724        impl OneHalf for $t {
725            const ONE_HALF: $t = 0.5;
726        }
727
728        /// The constant -1.0 for primitive floating-point types.
729        impl NegativeOne for $t {
730            const NEGATIVE_ONE: $t = -1.0;
731        }
732
733        /// The constant -0.0 for primitive floating-point types.
734        impl NegativeZero for $t {
735            const NEGATIVE_ZERO: $t = -0.0;
736        }
737
738        /// The constant Infinity for primitive floating-point types.
739        impl Infinity for $t {
740            const INFINITY: $t = $t::INFINITY;
741        }
742
743        /// The constant -Infinity for primitive floating-point types.
744        impl NegativeInfinity for $t {
745            const NEGATIVE_INFINITY: $t = $t::NEG_INFINITY;
746        }
747
748        /// The constant NaN for primitive floating-point types.
749        impl NaN for $t {
750            const NAN: $t = $t::NAN;
751        }
752
753        /// The lowest value representable by this type, negative infinity.
754        impl Min for $t {
755            const MIN: $t = $t::NEGATIVE_INFINITY;
756        }
757
758        /// The highest value representable by this type, positive infinity.
759        impl Max for $t {
760            const MAX: $t = $t::INFINITY;
761        }
762
763        /// The Prouhet-Thue-Morse constant.
764        impl ProuhetThueMorseConstant for $t {
765            const PROUHET_THUE_MORSE_CONSTANT: $t = $prouhet_thue_morse_constant;
766        }
767
768        /// The prime constant.
769        impl PrimeConstant for $t {
770            const PRIME_CONSTANT: $t = $prime_constant;
771        }
772
773        /// $\ln 2$.
774        impl Ln2 for $t {
775            const LN_2: $t = core::$t::consts::LN_2;
776        }
777
778        /// $\ln 10$.
779        impl Ln10 for $t {
780            const LN_10: $t = core::$t::consts::LN_10;
781        }
782
783        /// $\log_2 e$.
784        impl Log2E for $t {
785            const LOG_2_E: $t = core::$t::consts::LOG2_E;
786        }
787
788        /// $\log_{10} e$.
789        impl Log10E for $t {
790            const LOG_10_E: $t = core::$t::consts::LOG10_E;
791        }
792
793        /// $\log_2 10$.
794        impl Log210 for $t {
795            const LOG_2_10: $t = core::$t::consts::LOG2_10;
796        }
797
798        /// $\log_{10} 2$.
799        impl Log102 for $t {
800            const LOG_10_2: $t = core::$t::consts::LOG10_2;
801        }
802
803        /// $\sqrt{2}$.
804        impl Sqrt2 for $t {
805            const SQRT_2: $t = core::$t::consts::SQRT_2;
806        }
807
808        /// $\sqrt{3}$.
809        impl Sqrt3 for $t {
810            const SQRT_3: $t = $sqrt_3;
811        }
812
813        /// $\sqrt{5}$.
814        impl Sqrt5 for $t {
815            const SQRT_5: $t = $sqrt_5;
816        }
817
818        /// $\sqrt{2}/2=\sqrt{1/2}=1/\sqrt{2}$.
819        impl Sqrt2Over2 for $t {
820            const SQRT_2_OVER_2: $t = core::$t::consts::FRAC_1_SQRT_2;
821        }
822
823        /// $\sqrt{3}/3=\sqrt{1/3}=1/\sqrt{3}$.
824        impl Sqrt3Over3 for $t {
825            const SQRT_3_OVER_3: $t = $sqrt_3_over_3;
826        }
827
828        /// $\sqrt{5}/5=\sqrt{1/5}=1/\sqrt{5}$.
829        impl Sqrt5Over5 for $t {
830            const SQRT_5_OVER_5: $t = $sqrt_5_over_5;
831        }
832
833        /// $\varphi$, the golden ratio.
834        impl Phi for $t {
835            const PHI: $t = $phi;
836        }
837
838        /// $\pi$.
839        impl Pi for $t {
840            const PI: $t = core::$t::consts::PI;
841        }
842
843        /// $\tau=2\pi$.
844        impl Tau for $t {
845            const TAU: $t = core::$t::consts::TAU;
846        }
847
848        /// $\pi/2$.
849        impl PiOver2 for $t {
850            const PI_OVER_2: $t = core::$t::consts::FRAC_PI_2;
851        }
852
853        /// $\pi/3$.
854        impl PiOver3 for $t {
855            const PI_OVER_3: $t = core::$t::consts::FRAC_PI_3;
856        }
857
858        /// $\pi/4$.
859        impl PiOver4 for $t {
860            const PI_OVER_4: $t = core::$t::consts::FRAC_PI_4;
861        }
862
863        /// $\pi/6$.
864        impl PiOver6 for $t {
865            const PI_OVER_6: $t = core::$t::consts::FRAC_PI_6;
866        }
867
868        /// $\pi/8$.
869        impl PiOver8 for $t {
870            const PI_OVER_8: $t = core::$t::consts::FRAC_PI_8;
871        }
872
873        /// $1/\pi$.
874        impl OneOverPi for $t {
875            const ONE_OVER_PI: $t = core::$t::consts::FRAC_1_PI;
876        }
877
878        /// $\sqrt{\pi}$.
879        impl SqrtPi for $t {
880            const SQRT_PI: $t = $sqrt_pi;
881        }
882
883        /// $1/\sqrt{\pi}$.
884        impl OneOverSqrtPi for $t {
885            const ONE_OVER_SQRT_PI: $t = $one_over_sqrt_pi;
886        }
887
888        /// $1/\sqrt{\tau}$.
889        impl OneOverSqrtTau for $t {
890            const ONE_OVER_SQRT_TAU: $t = $one_over_sqrt_tau;
891        }
892
893        /// $2/\pi$.
894        impl TwoOverPi for $t {
895            const TWO_OVER_PI: $t = core::$t::consts::FRAC_2_PI;
896        }
897
898        /// $2/\sqrt{\pi}$.
899        impl TwoOverSqrtPi for $t {
900            const TWO_OVER_SQRT_PI: $t = core::$t::consts::FRAC_2_SQRT_PI;
901        }
902
903        /// $G=1/\mathrm{AGM}(1,\sqrt{2})$.
904        impl GaussConstant for $t {
905            const GAUSS_CONSTANT: $t = $gauss_constant;
906        }
907
908        /// $e^\pi$.
909        impl GelfondsConstant for $t {
910            const GELFONDS_CONSTANT: $t = $gelfonds_constant;
911        }
912
913        /// $2^{\sqrt 2}$.
914        impl GelfondSchneiderConstant for $t {
915            const GELFOND_SCHNEIDER_CONSTANT: $t = $gelfond_schneider_constant;
916        }
917
918        /// $\varpi=\pi G$.
919        impl LemniscateConstant for $t {
920            const LEMNISCATE_CONSTANT: $t = $lemniscate_constant;
921        }
922
923        /// $e^{\pi\sqrt{163}}$.
924        impl RamanujansConstant for $t {
925            const RAMANUJANS_CONSTANT: $t = $ramanujans_constant;
926        }
927    };
928}
929impl_basic_traits_primitive_float!(
930    f32,
931    32,
932    1.0e-45,
933    1.1754942e-38,
934    1.1754944e-38,
935    0.41245404,
936    0.4146825,
937    1.7320508,
938    2.236068,
939    0.57735026,
940    0.4472136,
941    1.618034,
942    1.7724539,
943    0.5641896,
944    0.3989423,
945    0.83462685,
946    23.140692,
947    2.6651442,
948    2.6220574,
949    2.6253742e17
950);
951impl_basic_traits_primitive_float!(
952    f64,
953    64,
954    5.0e-324,
955    2.225073858507201e-308,
956    2.2250738585072014e-308,
957    0.4124540336401076,
958    0.41468250985111166,
959    1.7320508075688772,
960    2.23606797749979,
961    0.5773502691896257,
962    0.4472135954999579,
963    1.618033988749895,
964    1.772453850905516,
965    0.5641895835477563,
966    0.3989422804014327,
967    0.8346268416740732,
968    23.14069263277927,
969    2.665144142690225,
970    2.6220575542921196,
971    2.6253741264076874e17
972);