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