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