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