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