core/num/
f128.rs

1//! Constants for the `f128` quadruple-precision floating point type.
2//!
3//! *[See also the `f128` primitive type][f128].*
4//!
5//! Mathematically significant numbers are provided in the `consts` sub-module.
6//!
7//! For the constants defined directly in this module
8//! (as distinct from those defined in the `consts` sub-module),
9//! new code should instead use the associated constants
10//! defined directly on the `f128` type.
11
12#![unstable(feature = "f128", issue = "116909")]
13
14use crate::convert::FloatToInt;
15use crate::num::FpCategory;
16use crate::panic::const_assert;
17use crate::{intrinsics, mem};
18
19/// Basic mathematical constants.
20#[unstable(feature = "f128", issue = "116909")]
21pub mod consts {
22    // FIXME: replace with mathematical constants from cmath.
23
24    /// Archimedes' constant (π)
25    #[unstable(feature = "f128", issue = "116909")]
26    pub const PI: f128 = 3.14159265358979323846264338327950288419716939937510582097494_f128;
27
28    /// The full circle constant (τ)
29    ///
30    /// Equal to 2π.
31    #[unstable(feature = "f128", issue = "116909")]
32    pub const TAU: f128 = 6.28318530717958647692528676655900576839433879875021164194989_f128;
33
34    /// The golden ratio (φ)
35    #[unstable(feature = "f128", issue = "116909")]
36    // Also, #[unstable(feature = "more_float_constants", issue = "103883")]
37    pub const PHI: f128 = 1.61803398874989484820458683436563811772030917980576286213545_f128;
38
39    /// The Euler-Mascheroni constant (γ)
40    #[unstable(feature = "f128", issue = "116909")]
41    // Also, #[unstable(feature = "more_float_constants", issue = "103883")]
42    pub const EGAMMA: f128 = 0.577215664901532860606512090082402431042159335939923598805767_f128;
43
44    /// π/2
45    #[unstable(feature = "f128", issue = "116909")]
46    pub const FRAC_PI_2: f128 = 1.57079632679489661923132169163975144209858469968755291048747_f128;
47
48    /// π/3
49    #[unstable(feature = "f128", issue = "116909")]
50    pub const FRAC_PI_3: f128 = 1.04719755119659774615421446109316762806572313312503527365831_f128;
51
52    /// π/4
53    #[unstable(feature = "f128", issue = "116909")]
54    pub const FRAC_PI_4: f128 = 0.785398163397448309615660845819875721049292349843776455243736_f128;
55
56    /// π/6
57    #[unstable(feature = "f128", issue = "116909")]
58    pub const FRAC_PI_6: f128 = 0.523598775598298873077107230546583814032861566562517636829157_f128;
59
60    /// π/8
61    #[unstable(feature = "f128", issue = "116909")]
62    pub const FRAC_PI_8: f128 = 0.392699081698724154807830422909937860524646174921888227621868_f128;
63
64    /// 1/π
65    #[unstable(feature = "f128", issue = "116909")]
66    pub const FRAC_1_PI: f128 = 0.318309886183790671537767526745028724068919291480912897495335_f128;
67
68    /// 1/sqrt(π)
69    #[unstable(feature = "f128", issue = "116909")]
70    // Also, #[unstable(feature = "more_float_constants", issue = "103883")]
71    pub const FRAC_1_SQRT_PI: f128 =
72        0.564189583547756286948079451560772585844050629328998856844086_f128;
73
74    /// 1/sqrt(2π)
75    #[doc(alias = "FRAC_1_SQRT_TAU")]
76    #[unstable(feature = "f128", issue = "116909")]
77    // Also, #[unstable(feature = "more_float_constants", issue = "103883")]
78    pub const FRAC_1_SQRT_2PI: f128 =
79        0.398942280401432677939946059934381868475858631164934657665926_f128;
80
81    /// 2/π
82    #[unstable(feature = "f128", issue = "116909")]
83    pub const FRAC_2_PI: f128 = 0.636619772367581343075535053490057448137838582961825794990669_f128;
84
85    /// 2/sqrt(π)
86    #[unstable(feature = "f128", issue = "116909")]
87    pub const FRAC_2_SQRT_PI: f128 =
88        1.12837916709551257389615890312154517168810125865799771368817_f128;
89
90    /// sqrt(2)
91    #[unstable(feature = "f128", issue = "116909")]
92    pub const SQRT_2: f128 = 1.41421356237309504880168872420969807856967187537694807317668_f128;
93
94    /// 1/sqrt(2)
95    #[unstable(feature = "f128", issue = "116909")]
96    pub const FRAC_1_SQRT_2: f128 =
97        0.707106781186547524400844362104849039284835937688474036588340_f128;
98
99    /// sqrt(3)
100    #[unstable(feature = "f128", issue = "116909")]
101    // Also, #[unstable(feature = "more_float_constants", issue = "103883")]
102    pub const SQRT_3: f128 = 1.73205080756887729352744634150587236694280525381038062805581_f128;
103
104    /// 1/sqrt(3)
105    #[unstable(feature = "f128", issue = "116909")]
106    // Also, #[unstable(feature = "more_float_constants", issue = "103883")]
107    pub const FRAC_1_SQRT_3: f128 =
108        0.577350269189625764509148780501957455647601751270126876018602_f128;
109
110    /// Euler's number (e)
111    #[unstable(feature = "f128", issue = "116909")]
112    pub const E: f128 = 2.71828182845904523536028747135266249775724709369995957496697_f128;
113
114    /// log<sub>2</sub>(10)
115    #[unstable(feature = "f128", issue = "116909")]
116    pub const LOG2_10: f128 = 3.32192809488736234787031942948939017586483139302458061205476_f128;
117
118    /// log<sub>2</sub>(e)
119    #[unstable(feature = "f128", issue = "116909")]
120    pub const LOG2_E: f128 = 1.44269504088896340735992468100189213742664595415298593413545_f128;
121
122    /// log<sub>10</sub>(2)
123    #[unstable(feature = "f128", issue = "116909")]
124    pub const LOG10_2: f128 = 0.301029995663981195213738894724493026768189881462108541310427_f128;
125
126    /// log<sub>10</sub>(e)
127    #[unstable(feature = "f128", issue = "116909")]
128    pub const LOG10_E: f128 = 0.434294481903251827651128918916605082294397005803666566114454_f128;
129
130    /// ln(2)
131    #[unstable(feature = "f128", issue = "116909")]
132    pub const LN_2: f128 = 0.693147180559945309417232121458176568075500134360255254120680_f128;
133
134    /// ln(10)
135    #[unstable(feature = "f128", issue = "116909")]
136    pub const LN_10: f128 = 2.30258509299404568401799145468436420760110148862877297603333_f128;
137}
138
139impl f128 {
140    // FIXME(f16_f128): almost all methods in this `impl` are missing examples and a const
141    // implementation. Add these once we can run code on all platforms and have f16/f128 in CTFE.
142
143    /// The radix or base of the internal representation of `f128`.
144    #[unstable(feature = "f128", issue = "116909")]
145    pub const RADIX: u32 = 2;
146
147    /// Number of significant digits in base 2.
148    #[unstable(feature = "f128", issue = "116909")]
149    pub const MANTISSA_DIGITS: u32 = 113;
150
151    /// Approximate number of significant digits in base 10.
152    ///
153    /// This is the maximum <i>x</i> such that any decimal number with <i>x</i>
154    /// significant digits can be converted to `f128` and back without loss.
155    ///
156    /// Equal to floor(log<sub>10</sub>&nbsp;2<sup>[`MANTISSA_DIGITS`]&nbsp;&minus;&nbsp;1</sup>).
157    ///
158    /// [`MANTISSA_DIGITS`]: f128::MANTISSA_DIGITS
159    #[unstable(feature = "f128", issue = "116909")]
160    pub const DIGITS: u32 = 33;
161
162    /// [Machine epsilon] value for `f128`.
163    ///
164    /// This is the difference between `1.0` and the next larger representable number.
165    ///
166    /// Equal to 2<sup>1&nbsp;&minus;&nbsp;[`MANTISSA_DIGITS`]</sup>.
167    ///
168    /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
169    /// [`MANTISSA_DIGITS`]: f128::MANTISSA_DIGITS
170    #[unstable(feature = "f128", issue = "116909")]
171    pub const EPSILON: f128 = 1.92592994438723585305597794258492732e-34_f128;
172
173    /// Smallest finite `f128` value.
174    ///
175    /// Equal to &minus;[`MAX`].
176    ///
177    /// [`MAX`]: f128::MAX
178    #[unstable(feature = "f128", issue = "116909")]
179    pub const MIN: f128 = -1.18973149535723176508575932662800702e+4932_f128;
180    /// Smallest positive normal `f128` value.
181    ///
182    /// Equal to 2<sup>[`MIN_EXP`]&nbsp;&minus;&nbsp;1</sup>.
183    ///
184    /// [`MIN_EXP`]: f128::MIN_EXP
185    #[unstable(feature = "f128", issue = "116909")]
186    pub const MIN_POSITIVE: f128 = 3.36210314311209350626267781732175260e-4932_f128;
187    /// Largest finite `f128` value.
188    ///
189    /// Equal to
190    /// (1&nbsp;&minus;&nbsp;2<sup>&minus;[`MANTISSA_DIGITS`]</sup>)&nbsp;2<sup>[`MAX_EXP`]</sup>.
191    ///
192    /// [`MANTISSA_DIGITS`]: f128::MANTISSA_DIGITS
193    /// [`MAX_EXP`]: f128::MAX_EXP
194    #[unstable(feature = "f128", issue = "116909")]
195    pub const MAX: f128 = 1.18973149535723176508575932662800702e+4932_f128;
196
197    /// One greater than the minimum possible normal power of 2 exponent.
198    ///
199    /// If <i>x</i>&nbsp;=&nbsp;`MIN_EXP`, then normal numbers
200    /// ≥&nbsp;0.5&nbsp;×&nbsp;2<sup><i>x</i></sup>.
201    #[unstable(feature = "f128", issue = "116909")]
202    pub const MIN_EXP: i32 = -16_381;
203    /// Maximum possible power of 2 exponent.
204    ///
205    /// If <i>x</i>&nbsp;=&nbsp;`MAX_EXP`, then normal numbers
206    /// &lt;&nbsp;1&nbsp;×&nbsp;2<sup><i>x</i></sup>.
207    #[unstable(feature = "f128", issue = "116909")]
208    pub const MAX_EXP: i32 = 16_384;
209
210    /// Minimum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
211    ///
212    /// Equal to ceil(log<sub>10</sub>&nbsp;[`MIN_POSITIVE`]).
213    ///
214    /// [`MIN_POSITIVE`]: f128::MIN_POSITIVE
215    #[unstable(feature = "f128", issue = "116909")]
216    pub const MIN_10_EXP: i32 = -4_931;
217    /// Maximum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
218    ///
219    /// Equal to floor(log<sub>10</sub>&nbsp;[`MAX`]).
220    ///
221    /// [`MAX`]: f128::MAX
222    #[unstable(feature = "f128", issue = "116909")]
223    pub const MAX_10_EXP: i32 = 4_932;
224
225    /// Not a Number (NaN).
226    ///
227    /// Note that IEEE 754 doesn't define just a single NaN value;
228    /// a plethora of bit patterns are considered to be NaN.
229    /// Furthermore, the standard makes a difference
230    /// between a "signaling" and a "quiet" NaN,
231    /// and allows inspecting its "payload" (the unspecified bits in the bit pattern).
232    /// This constant isn't guaranteed to equal to any specific NaN bitpattern,
233    /// and the stability of its representation over Rust versions
234    /// and target platforms isn't guaranteed.
235    #[allow(clippy::eq_op)]
236    #[rustc_diagnostic_item = "f128_nan"]
237    #[unstable(feature = "f128", issue = "116909")]
238    pub const NAN: f128 = 0.0_f128 / 0.0_f128;
239
240    /// Infinity (∞).
241    #[unstable(feature = "f128", issue = "116909")]
242    pub const INFINITY: f128 = 1.0_f128 / 0.0_f128;
243
244    /// Negative infinity (−∞).
245    #[unstable(feature = "f128", issue = "116909")]
246    pub const NEG_INFINITY: f128 = -1.0_f128 / 0.0_f128;
247
248    /// Sign bit
249    pub(crate) const SIGN_MASK: u128 = 0x8000_0000_0000_0000_0000_0000_0000_0000;
250
251    /// Exponent mask
252    pub(crate) const EXP_MASK: u128 = 0x7fff_0000_0000_0000_0000_0000_0000_0000;
253
254    /// Mantissa mask
255    pub(crate) const MAN_MASK: u128 = 0x0000_ffff_ffff_ffff_ffff_ffff_ffff_ffff;
256
257    /// Minimum representable positive value (min subnormal)
258    const TINY_BITS: u128 = 0x1;
259
260    /// Minimum representable negative value (min negative subnormal)
261    const NEG_TINY_BITS: u128 = Self::TINY_BITS | Self::SIGN_MASK;
262
263    /// Returns `true` if this value is NaN.
264    ///
265    /// ```
266    /// #![feature(f128)]
267    /// # // FIXME(f16_f128): remove when `unordtf2` is available
268    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
269    ///
270    /// let nan = f128::NAN;
271    /// let f = 7.0_f128;
272    ///
273    /// assert!(nan.is_nan());
274    /// assert!(!f.is_nan());
275    /// # }
276    /// ```
277    #[inline]
278    #[must_use]
279    #[unstable(feature = "f128", issue = "116909")]
280    #[allow(clippy::eq_op)] // > if you intended to check if the operand is NaN, use `.is_nan()` instead :)
281    pub const fn is_nan(self) -> bool {
282        self != self
283    }
284
285    /// Returns `true` if this value is positive infinity or negative infinity, and
286    /// `false` otherwise.
287    ///
288    /// ```
289    /// #![feature(f128)]
290    /// # // FIXME(f16_f128): remove when `eqtf2` is available
291    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
292    ///
293    /// let f = 7.0f128;
294    /// let inf = f128::INFINITY;
295    /// let neg_inf = f128::NEG_INFINITY;
296    /// let nan = f128::NAN;
297    ///
298    /// assert!(!f.is_infinite());
299    /// assert!(!nan.is_infinite());
300    ///
301    /// assert!(inf.is_infinite());
302    /// assert!(neg_inf.is_infinite());
303    /// # }
304    /// ```
305    #[inline]
306    #[must_use]
307    #[unstable(feature = "f128", issue = "116909")]
308    pub const fn is_infinite(self) -> bool {
309        (self == f128::INFINITY) | (self == f128::NEG_INFINITY)
310    }
311
312    /// Returns `true` if this number is neither infinite nor NaN.
313    ///
314    /// ```
315    /// #![feature(f128)]
316    /// # // FIXME(f16_f128): remove when `lttf2` is available
317    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
318    ///
319    /// let f = 7.0f128;
320    /// let inf: f128 = f128::INFINITY;
321    /// let neg_inf: f128 = f128::NEG_INFINITY;
322    /// let nan: f128 = f128::NAN;
323    ///
324    /// assert!(f.is_finite());
325    ///
326    /// assert!(!nan.is_finite());
327    /// assert!(!inf.is_finite());
328    /// assert!(!neg_inf.is_finite());
329    /// # }
330    /// ```
331    #[inline]
332    #[must_use]
333    #[unstable(feature = "f128", issue = "116909")]
334    #[rustc_const_unstable(feature = "f128", issue = "116909")]
335    pub const fn is_finite(self) -> bool {
336        // There's no need to handle NaN separately: if self is NaN,
337        // the comparison is not true, exactly as desired.
338        self.abs() < Self::INFINITY
339    }
340
341    /// Returns `true` if the number is [subnormal].
342    ///
343    /// ```
344    /// #![feature(f128)]
345    /// # // FIXME(f16_f128): remove when `eqtf2` is available
346    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
347    ///
348    /// let min = f128::MIN_POSITIVE; // 3.362103143e-4932f128
349    /// let max = f128::MAX;
350    /// let lower_than_min = 1.0e-4960_f128;
351    /// let zero = 0.0_f128;
352    ///
353    /// assert!(!min.is_subnormal());
354    /// assert!(!max.is_subnormal());
355    ///
356    /// assert!(!zero.is_subnormal());
357    /// assert!(!f128::NAN.is_subnormal());
358    /// assert!(!f128::INFINITY.is_subnormal());
359    /// // Values between `0` and `min` are Subnormal.
360    /// assert!(lower_than_min.is_subnormal());
361    /// # }
362    /// ```
363    ///
364    /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
365    #[inline]
366    #[must_use]
367    #[unstable(feature = "f128", issue = "116909")]
368    pub const fn is_subnormal(self) -> bool {
369        matches!(self.classify(), FpCategory::Subnormal)
370    }
371
372    /// Returns `true` if the number is neither zero, infinite, [subnormal], or NaN.
373    ///
374    /// ```
375    /// #![feature(f128)]
376    /// # // FIXME(f16_f128): remove when `eqtf2` is available
377    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
378    ///
379    /// let min = f128::MIN_POSITIVE; // 3.362103143e-4932f128
380    /// let max = f128::MAX;
381    /// let lower_than_min = 1.0e-4960_f128;
382    /// let zero = 0.0_f128;
383    ///
384    /// assert!(min.is_normal());
385    /// assert!(max.is_normal());
386    ///
387    /// assert!(!zero.is_normal());
388    /// assert!(!f128::NAN.is_normal());
389    /// assert!(!f128::INFINITY.is_normal());
390    /// // Values between `0` and `min` are Subnormal.
391    /// assert!(!lower_than_min.is_normal());
392    /// # }
393    /// ```
394    ///
395    /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
396    #[inline]
397    #[must_use]
398    #[unstable(feature = "f128", issue = "116909")]
399    pub const fn is_normal(self) -> bool {
400        matches!(self.classify(), FpCategory::Normal)
401    }
402
403    /// Returns the floating point category of the number. If only one property
404    /// is going to be tested, it is generally faster to use the specific
405    /// predicate instead.
406    ///
407    /// ```
408    /// #![feature(f128)]
409    /// # // FIXME(f16_f128): remove when `eqtf2` is available
410    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
411    ///
412    /// use std::num::FpCategory;
413    ///
414    /// let num = 12.4_f128;
415    /// let inf = f128::INFINITY;
416    ///
417    /// assert_eq!(num.classify(), FpCategory::Normal);
418    /// assert_eq!(inf.classify(), FpCategory::Infinite);
419    /// # }
420    /// ```
421    #[inline]
422    #[unstable(feature = "f128", issue = "116909")]
423    pub const fn classify(self) -> FpCategory {
424        let bits = self.to_bits();
425        match (bits & Self::MAN_MASK, bits & Self::EXP_MASK) {
426            (0, Self::EXP_MASK) => FpCategory::Infinite,
427            (_, Self::EXP_MASK) => FpCategory::Nan,
428            (0, 0) => FpCategory::Zero,
429            (_, 0) => FpCategory::Subnormal,
430            _ => FpCategory::Normal,
431        }
432    }
433
434    /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with
435    /// positive sign bit and positive infinity.
436    ///
437    /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
438    /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
439    /// conserved over arithmetic operations, the result of `is_sign_positive` on
440    /// a NaN might produce an unexpected or non-portable result. See the [specification
441    /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == 1.0`
442    /// if you need fully portable behavior (will return `false` for all NaNs).
443    ///
444    /// ```
445    /// #![feature(f128)]
446    ///
447    /// let f = 7.0_f128;
448    /// let g = -7.0_f128;
449    ///
450    /// assert!(f.is_sign_positive());
451    /// assert!(!g.is_sign_positive());
452    /// ```
453    #[inline]
454    #[must_use]
455    #[unstable(feature = "f128", issue = "116909")]
456    pub const fn is_sign_positive(self) -> bool {
457        !self.is_sign_negative()
458    }
459
460    /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with
461    /// negative sign bit and negative infinity.
462    ///
463    /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
464    /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
465    /// conserved over arithmetic operations, the result of `is_sign_negative` on
466    /// a NaN might produce an unexpected or non-portable result. See the [specification
467    /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == -1.0`
468    /// if you need fully portable behavior (will return `false` for all NaNs).
469    ///
470    /// ```
471    /// #![feature(f128)]
472    ///
473    /// let f = 7.0_f128;
474    /// let g = -7.0_f128;
475    ///
476    /// assert!(!f.is_sign_negative());
477    /// assert!(g.is_sign_negative());
478    /// ```
479    #[inline]
480    #[must_use]
481    #[unstable(feature = "f128", issue = "116909")]
482    pub const fn is_sign_negative(self) -> bool {
483        // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
484        // applies to zeros and NaNs as well.
485        // SAFETY: This is just transmuting to get the sign bit, it's fine.
486        (self.to_bits() & (1 << 127)) != 0
487    }
488
489    /// Returns the least number greater than `self`.
490    ///
491    /// Let `TINY` be the smallest representable positive `f128`. Then,
492    ///  - if `self.is_nan()`, this returns `self`;
493    ///  - if `self` is [`NEG_INFINITY`], this returns [`MIN`];
494    ///  - if `self` is `-TINY`, this returns -0.0;
495    ///  - if `self` is -0.0 or +0.0, this returns `TINY`;
496    ///  - if `self` is [`MAX`] or [`INFINITY`], this returns [`INFINITY`];
497    ///  - otherwise the unique least value greater than `self` is returned.
498    ///
499    /// The identity `x.next_up() == -(-x).next_down()` holds for all non-NaN `x`. When `x`
500    /// is finite `x == x.next_up().next_down()` also holds.
501    ///
502    /// ```rust
503    /// #![feature(f128)]
504    /// # // FIXME(f16_f128): remove when `eqtf2` is available
505    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
506    ///
507    /// // f128::EPSILON is the difference between 1.0 and the next number up.
508    /// assert_eq!(1.0f128.next_up(), 1.0 + f128::EPSILON);
509    /// // But not for most numbers.
510    /// assert!(0.1f128.next_up() < 0.1 + f128::EPSILON);
511    /// assert_eq!(4611686018427387904f128.next_up(), 4611686018427387904.000000000000001);
512    /// # }
513    /// ```
514    ///
515    /// This operation corresponds to IEEE-754 `nextUp`.
516    ///
517    /// [`NEG_INFINITY`]: Self::NEG_INFINITY
518    /// [`INFINITY`]: Self::INFINITY
519    /// [`MIN`]: Self::MIN
520    /// [`MAX`]: Self::MAX
521    #[inline]
522    #[doc(alias = "nextUp")]
523    #[unstable(feature = "f128", issue = "116909")]
524    pub const fn next_up(self) -> Self {
525        // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
526        // denormals to zero. This is in general unsound and unsupported, but here
527        // we do our best to still produce the correct result on such targets.
528        let bits = self.to_bits();
529        if self.is_nan() || bits == Self::INFINITY.to_bits() {
530            return self;
531        }
532
533        let abs = bits & !Self::SIGN_MASK;
534        let next_bits = if abs == 0 {
535            Self::TINY_BITS
536        } else if bits == abs {
537            bits + 1
538        } else {
539            bits - 1
540        };
541        Self::from_bits(next_bits)
542    }
543
544    /// Returns the greatest number less than `self`.
545    ///
546    /// Let `TINY` be the smallest representable positive `f128`. Then,
547    ///  - if `self.is_nan()`, this returns `self`;
548    ///  - if `self` is [`INFINITY`], this returns [`MAX`];
549    ///  - if `self` is `TINY`, this returns 0.0;
550    ///  - if `self` is -0.0 or +0.0, this returns `-TINY`;
551    ///  - if `self` is [`MIN`] or [`NEG_INFINITY`], this returns [`NEG_INFINITY`];
552    ///  - otherwise the unique greatest value less than `self` is returned.
553    ///
554    /// The identity `x.next_down() == -(-x).next_up()` holds for all non-NaN `x`. When `x`
555    /// is finite `x == x.next_down().next_up()` also holds.
556    ///
557    /// ```rust
558    /// #![feature(f128)]
559    /// # // FIXME(f16_f128): remove when `eqtf2` is available
560    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
561    ///
562    /// let x = 1.0f128;
563    /// // Clamp value into range [0, 1).
564    /// let clamped = x.clamp(0.0, 1.0f128.next_down());
565    /// assert!(clamped < 1.0);
566    /// assert_eq!(clamped.next_up(), 1.0);
567    /// # }
568    /// ```
569    ///
570    /// This operation corresponds to IEEE-754 `nextDown`.
571    ///
572    /// [`NEG_INFINITY`]: Self::NEG_INFINITY
573    /// [`INFINITY`]: Self::INFINITY
574    /// [`MIN`]: Self::MIN
575    /// [`MAX`]: Self::MAX
576    #[inline]
577    #[doc(alias = "nextDown")]
578    #[unstable(feature = "f128", issue = "116909")]
579    pub const fn next_down(self) -> Self {
580        // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
581        // denormals to zero. This is in general unsound and unsupported, but here
582        // we do our best to still produce the correct result on such targets.
583        let bits = self.to_bits();
584        if self.is_nan() || bits == Self::NEG_INFINITY.to_bits() {
585            return self;
586        }
587
588        let abs = bits & !Self::SIGN_MASK;
589        let next_bits = if abs == 0 {
590            Self::NEG_TINY_BITS
591        } else if bits == abs {
592            bits - 1
593        } else {
594            bits + 1
595        };
596        Self::from_bits(next_bits)
597    }
598
599    /// Takes the reciprocal (inverse) of a number, `1/x`.
600    ///
601    /// ```
602    /// #![feature(f128)]
603    /// # // FIXME(f16_f128): remove when `eqtf2` is available
604    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
605    ///
606    /// let x = 2.0_f128;
607    /// let abs_difference = (x.recip() - (1.0 / x)).abs();
608    ///
609    /// assert!(abs_difference <= f128::EPSILON);
610    /// # }
611    /// ```
612    #[inline]
613    #[unstable(feature = "f128", issue = "116909")]
614    #[must_use = "this returns the result of the operation, without modifying the original"]
615    pub const fn recip(self) -> Self {
616        1.0 / self
617    }
618
619    /// Converts radians to degrees.
620    ///
621    /// ```
622    /// #![feature(f128)]
623    /// # // FIXME(f16_f128): remove when `eqtf2` is available
624    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
625    ///
626    /// let angle = std::f128::consts::PI;
627    ///
628    /// let abs_difference = (angle.to_degrees() - 180.0).abs();
629    /// assert!(abs_difference <= f128::EPSILON);
630    /// # }
631    /// ```
632    #[inline]
633    #[unstable(feature = "f128", issue = "116909")]
634    #[must_use = "this returns the result of the operation, without modifying the original"]
635    pub const fn to_degrees(self) -> Self {
636        // Use a literal for better precision.
637        const PIS_IN_180: f128 = 57.2957795130823208767981548141051703324054724665643215491602_f128;
638        self * PIS_IN_180
639    }
640
641    /// Converts degrees to radians.
642    ///
643    /// ```
644    /// #![feature(f128)]
645    /// # // FIXME(f16_f128): remove when `eqtf2` is available
646    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
647    ///
648    /// let angle = 180.0f128;
649    ///
650    /// let abs_difference = (angle.to_radians() - std::f128::consts::PI).abs();
651    ///
652    /// assert!(abs_difference <= 1e-30);
653    /// # }
654    /// ```
655    #[inline]
656    #[unstable(feature = "f128", issue = "116909")]
657    #[must_use = "this returns the result of the operation, without modifying the original"]
658    pub const fn to_radians(self) -> f128 {
659        // Use a literal for better precision.
660        const RADS_PER_DEG: f128 =
661            0.0174532925199432957692369076848861271344287188854172545609719_f128;
662        self * RADS_PER_DEG
663    }
664
665    /// Returns the maximum of the two numbers, ignoring NaN.
666    ///
667    /// If one of the arguments is NaN, then the other argument is returned.
668    /// This follows the IEEE 754-2008 semantics for maxNum, except for handling of signaling NaNs;
669    /// this function handles all NaNs the same way and avoids maxNum's problems with associativity.
670    /// This also matches the behavior of libm’s fmax. In particular, if the inputs compare equal
671    /// (such as for the case of `+0.0` and `-0.0`), either input may be returned non-deterministically.
672    ///
673    /// ```
674    /// #![feature(f128)]
675    /// # // Using aarch64 because `reliable_f128_math` is needed
676    /// # #[cfg(all(target_arch = "aarch64", target_os = "linux"))] {
677    ///
678    /// let x = 1.0f128;
679    /// let y = 2.0f128;
680    ///
681    /// assert_eq!(x.max(y), y);
682    /// # }
683    /// ```
684    #[inline]
685    #[unstable(feature = "f128", issue = "116909")]
686    #[rustc_const_unstable(feature = "f128", issue = "116909")]
687    #[must_use = "this returns the result of the comparison, without modifying either input"]
688    pub const fn max(self, other: f128) -> f128 {
689        intrinsics::maxnumf128(self, other)
690    }
691
692    /// Returns the minimum of the two numbers, ignoring NaN.
693    ///
694    /// If one of the arguments is NaN, then the other argument is returned.
695    /// This follows the IEEE 754-2008 semantics for minNum, except for handling of signaling NaNs;
696    /// this function handles all NaNs the same way and avoids minNum's problems with associativity.
697    /// This also matches the behavior of libm’s fmin. In particular, if the inputs compare equal
698    /// (such as for the case of `+0.0` and `-0.0`), either input may be returned non-deterministically.
699    ///
700    /// ```
701    /// #![feature(f128)]
702    /// # // Using aarch64 because `reliable_f128_math` is needed
703    /// # #[cfg(all(target_arch = "aarch64", target_os = "linux"))] {
704    ///
705    /// let x = 1.0f128;
706    /// let y = 2.0f128;
707    ///
708    /// assert_eq!(x.min(y), x);
709    /// # }
710    /// ```
711    #[inline]
712    #[unstable(feature = "f128", issue = "116909")]
713    #[rustc_const_unstable(feature = "f128", issue = "116909")]
714    #[must_use = "this returns the result of the comparison, without modifying either input"]
715    pub const fn min(self, other: f128) -> f128 {
716        intrinsics::minnumf128(self, other)
717    }
718
719    /// Returns the maximum of the two numbers, propagating NaN.
720    ///
721    /// This returns NaN when *either* argument is NaN, as opposed to
722    /// [`f128::max`] which only returns NaN when *both* arguments are NaN.
723    ///
724    /// ```
725    /// #![feature(f128)]
726    /// #![feature(float_minimum_maximum)]
727    /// # // Using aarch64 because `reliable_f128_math` is needed
728    /// # #[cfg(all(target_arch = "aarch64", target_os = "linux"))] {
729    ///
730    /// let x = 1.0f128;
731    /// let y = 2.0f128;
732    ///
733    /// assert_eq!(x.maximum(y), y);
734    /// assert!(x.maximum(f128::NAN).is_nan());
735    /// # }
736    /// ```
737    ///
738    /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the greater
739    /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
740    /// Note that this follows the semantics specified in IEEE 754-2019.
741    ///
742    /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
743    /// operand is conserved; see the [specification of NaN bit patterns](f32#nan-bit-patterns) for more info.
744    #[inline]
745    #[unstable(feature = "f128", issue = "116909")]
746    // #[unstable(feature = "float_minimum_maximum", issue = "91079")]
747    #[must_use = "this returns the result of the comparison, without modifying either input"]
748    pub const fn maximum(self, other: f128) -> f128 {
749        if self > other {
750            self
751        } else if other > self {
752            other
753        } else if self == other {
754            if self.is_sign_positive() && other.is_sign_negative() { self } else { other }
755        } else {
756            self + other
757        }
758    }
759
760    /// Returns the minimum of the two numbers, propagating NaN.
761    ///
762    /// This returns NaN when *either* argument is NaN, as opposed to
763    /// [`f128::min`] which only returns NaN when *both* arguments are NaN.
764    ///
765    /// ```
766    /// #![feature(f128)]
767    /// #![feature(float_minimum_maximum)]
768    /// # // Using aarch64 because `reliable_f128_math` is needed
769    /// # #[cfg(all(target_arch = "aarch64", target_os = "linux"))] {
770    ///
771    /// let x = 1.0f128;
772    /// let y = 2.0f128;
773    ///
774    /// assert_eq!(x.minimum(y), x);
775    /// assert!(x.minimum(f128::NAN).is_nan());
776    /// # }
777    /// ```
778    ///
779    /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the lesser
780    /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
781    /// Note that this follows the semantics specified in IEEE 754-2019.
782    ///
783    /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
784    /// operand is conserved; see the [specification of NaN bit patterns](f32#nan-bit-patterns) for more info.
785    #[inline]
786    #[unstable(feature = "f128", issue = "116909")]
787    // #[unstable(feature = "float_minimum_maximum", issue = "91079")]
788    #[must_use = "this returns the result of the comparison, without modifying either input"]
789    pub const fn minimum(self, other: f128) -> f128 {
790        if self < other {
791            self
792        } else if other < self {
793            other
794        } else if self == other {
795            if self.is_sign_negative() && other.is_sign_positive() { self } else { other }
796        } else {
797            // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
798            self + other
799        }
800    }
801
802    /// Calculates the middle point of `self` and `rhs`.
803    ///
804    /// This returns NaN when *either* argument is NaN or if a combination of
805    /// +inf and -inf is provided as arguments.
806    ///
807    /// # Examples
808    ///
809    /// ```
810    /// #![feature(f128)]
811    /// # // Using aarch64 because `reliable_f128_math` is needed
812    /// # #[cfg(all(target_arch = "aarch64", target_os = "linux"))] {
813    ///
814    /// assert_eq!(1f128.midpoint(4.0), 2.5);
815    /// assert_eq!((-5.5f128).midpoint(8.0), 1.25);
816    /// # }
817    /// ```
818    #[inline]
819    #[unstable(feature = "f128", issue = "116909")]
820    #[rustc_const_unstable(feature = "f128", issue = "116909")]
821    pub const fn midpoint(self, other: f128) -> f128 {
822        const LO: f128 = f128::MIN_POSITIVE * 2.;
823        const HI: f128 = f128::MAX / 2.;
824
825        let (a, b) = (self, other);
826        let abs_a = a.abs();
827        let abs_b = b.abs();
828
829        if abs_a <= HI && abs_b <= HI {
830            // Overflow is impossible
831            (a + b) / 2.
832        } else if abs_a < LO {
833            // Not safe to halve `a` (would underflow)
834            a + (b / 2.)
835        } else if abs_b < LO {
836            // Not safe to halve `b` (would underflow)
837            (a / 2.) + b
838        } else {
839            // Safe to halve `a` and `b`
840            (a / 2.) + (b / 2.)
841        }
842    }
843
844    /// Rounds toward zero and converts to any primitive integer type,
845    /// assuming that the value is finite and fits in that type.
846    ///
847    /// ```
848    /// #![feature(f128)]
849    /// # // FIXME(f16_f128): remove when `float*itf` is available
850    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
851    ///
852    /// let value = 4.6_f128;
853    /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
854    /// assert_eq!(rounded, 4);
855    ///
856    /// let value = -128.9_f128;
857    /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
858    /// assert_eq!(rounded, i8::MIN);
859    /// # }
860    /// ```
861    ///
862    /// # Safety
863    ///
864    /// The value must:
865    ///
866    /// * Not be `NaN`
867    /// * Not be infinite
868    /// * Be representable in the return type `Int`, after truncating off its fractional part
869    #[inline]
870    #[unstable(feature = "f128", issue = "116909")]
871    #[must_use = "this returns the result of the operation, without modifying the original"]
872    pub unsafe fn to_int_unchecked<Int>(self) -> Int
873    where
874        Self: FloatToInt<Int>,
875    {
876        // SAFETY: the caller must uphold the safety contract for
877        // `FloatToInt::to_int_unchecked`.
878        unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
879    }
880
881    /// Raw transmutation to `u128`.
882    ///
883    /// This is currently identical to `transmute::<f128, u128>(self)` on all platforms.
884    ///
885    /// See [`from_bits`](#method.from_bits) for some discussion of the
886    /// portability of this operation (there are almost no issues).
887    ///
888    /// Note that this function is distinct from `as` casting, which attempts to
889    /// preserve the *numeric* value, and not the bitwise value.
890    ///
891    /// ```
892    /// #![feature(f128)]
893    ///
894    /// # // FIXME(f16_f128): enable this once const casting works
895    /// # // assert_ne!((1f128).to_bits(), 1f128 as u128); // to_bits() is not casting!
896    /// assert_eq!((12.5f128).to_bits(), 0x40029000000000000000000000000000);
897    /// ```
898    #[inline]
899    #[unstable(feature = "f128", issue = "116909")]
900    #[must_use = "this returns the result of the operation, without modifying the original"]
901    pub const fn to_bits(self) -> u128 {
902        // SAFETY: `u128` is a plain old datatype so we can always transmute to it.
903        unsafe { mem::transmute(self) }
904    }
905
906    /// Raw transmutation from `u128`.
907    ///
908    /// This is currently identical to `transmute::<u128, f128>(v)` on all platforms.
909    /// It turns out this is incredibly portable, for two reasons:
910    ///
911    /// * Floats and Ints have the same endianness on all supported platforms.
912    /// * IEEE 754 very precisely specifies the bit layout of floats.
913    ///
914    /// However there is one caveat: prior to the 2008 version of IEEE 754, how
915    /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
916    /// (notably x86 and ARM) picked the interpretation that was ultimately
917    /// standardized in 2008, but some didn't (notably MIPS). As a result, all
918    /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
919    ///
920    /// Rather than trying to preserve signaling-ness cross-platform, this
921    /// implementation favors preserving the exact bits. This means that
922    /// any payloads encoded in NaNs will be preserved even if the result of
923    /// this method is sent over the network from an x86 machine to a MIPS one.
924    ///
925    /// If the results of this method are only manipulated by the same
926    /// architecture that produced them, then there is no portability concern.
927    ///
928    /// If the input isn't NaN, then there is no portability concern.
929    ///
930    /// If you don't care about signalingness (very likely), then there is no
931    /// portability concern.
932    ///
933    /// Note that this function is distinct from `as` casting, which attempts to
934    /// preserve the *numeric* value, and not the bitwise value.
935    ///
936    /// ```
937    /// #![feature(f128)]
938    /// #  // FIXME(f16_f128): remove when `eqtf2` is available
939    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
940    ///
941    /// let v = f128::from_bits(0x40029000000000000000000000000000);
942    /// assert_eq!(v, 12.5);
943    /// # }
944    /// ```
945    #[inline]
946    #[must_use]
947    #[unstable(feature = "f128", issue = "116909")]
948    pub const fn from_bits(v: u128) -> Self {
949        // It turns out the safety issues with sNaN were overblown! Hooray!
950        // SAFETY: `u128` is a plain old datatype so we can always transmute from it.
951        unsafe { mem::transmute(v) }
952    }
953
954    /// Returns the memory representation of this floating point number as a byte array in
955    /// big-endian (network) byte order.
956    ///
957    /// See [`from_bits`](Self::from_bits) for some discussion of the
958    /// portability of this operation (there are almost no issues).
959    ///
960    /// # Examples
961    ///
962    /// ```
963    /// #![feature(f128)]
964    ///
965    /// let bytes = 12.5f128.to_be_bytes();
966    /// assert_eq!(
967    ///     bytes,
968    ///     [0x40, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,
969    ///      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
970    /// );
971    /// ```
972    #[inline]
973    #[unstable(feature = "f128", issue = "116909")]
974    #[must_use = "this returns the result of the operation, without modifying the original"]
975    pub const fn to_be_bytes(self) -> [u8; 16] {
976        self.to_bits().to_be_bytes()
977    }
978
979    /// Returns the memory representation of this floating point number as a byte array in
980    /// little-endian byte order.
981    ///
982    /// See [`from_bits`](Self::from_bits) for some discussion of the
983    /// portability of this operation (there are almost no issues).
984    ///
985    /// # Examples
986    ///
987    /// ```
988    /// #![feature(f128)]
989    ///
990    /// let bytes = 12.5f128.to_le_bytes();
991    /// assert_eq!(
992    ///     bytes,
993    ///     [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
994    ///      0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x02, 0x40]
995    /// );
996    /// ```
997    #[inline]
998    #[unstable(feature = "f128", issue = "116909")]
999    #[must_use = "this returns the result of the operation, without modifying the original"]
1000    pub const fn to_le_bytes(self) -> [u8; 16] {
1001        self.to_bits().to_le_bytes()
1002    }
1003
1004    /// Returns the memory representation of this floating point number as a byte array in
1005    /// native byte order.
1006    ///
1007    /// As the target platform's native endianness is used, portable code
1008    /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1009    ///
1010    /// [`to_be_bytes`]: f128::to_be_bytes
1011    /// [`to_le_bytes`]: f128::to_le_bytes
1012    ///
1013    /// See [`from_bits`](Self::from_bits) for some discussion of the
1014    /// portability of this operation (there are almost no issues).
1015    ///
1016    /// # Examples
1017    ///
1018    /// ```
1019    /// #![feature(f128)]
1020    ///
1021    /// let bytes = 12.5f128.to_ne_bytes();
1022    /// assert_eq!(
1023    ///     bytes,
1024    ///     if cfg!(target_endian = "big") {
1025    ///         [0x40, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,
1026    ///          0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1027    ///     } else {
1028    ///         [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1029    ///          0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x02, 0x40]
1030    ///     }
1031    /// );
1032    /// ```
1033    #[inline]
1034    #[unstable(feature = "f128", issue = "116909")]
1035    #[must_use = "this returns the result of the operation, without modifying the original"]
1036    pub const fn to_ne_bytes(self) -> [u8; 16] {
1037        self.to_bits().to_ne_bytes()
1038    }
1039
1040    /// Creates a floating point value from its representation as a byte array in big endian.
1041    ///
1042    /// See [`from_bits`](Self::from_bits) for some discussion of the
1043    /// portability of this operation (there are almost no issues).
1044    ///
1045    /// # Examples
1046    ///
1047    /// ```
1048    /// #![feature(f128)]
1049    /// # // FIXME(f16_f128): remove when `eqtf2` is available
1050    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1051    ///
1052    /// let value = f128::from_be_bytes(
1053    ///     [0x40, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,
1054    ///      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1055    /// );
1056    /// assert_eq!(value, 12.5);
1057    /// # }
1058    /// ```
1059    #[inline]
1060    #[must_use]
1061    #[unstable(feature = "f128", issue = "116909")]
1062    pub const fn from_be_bytes(bytes: [u8; 16]) -> Self {
1063        Self::from_bits(u128::from_be_bytes(bytes))
1064    }
1065
1066    /// Creates a floating point value from its representation as a byte array in little endian.
1067    ///
1068    /// See [`from_bits`](Self::from_bits) for some discussion of the
1069    /// portability of this operation (there are almost no issues).
1070    ///
1071    /// # Examples
1072    ///
1073    /// ```
1074    /// #![feature(f128)]
1075    /// # // FIXME(f16_f128): remove when `eqtf2` is available
1076    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1077    ///
1078    /// let value = f128::from_le_bytes(
1079    ///     [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1080    ///      0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x02, 0x40]
1081    /// );
1082    /// assert_eq!(value, 12.5);
1083    /// # }
1084    /// ```
1085    #[inline]
1086    #[must_use]
1087    #[unstable(feature = "f128", issue = "116909")]
1088    pub const fn from_le_bytes(bytes: [u8; 16]) -> Self {
1089        Self::from_bits(u128::from_le_bytes(bytes))
1090    }
1091
1092    /// Creates a floating point value from its representation as a byte array in native endian.
1093    ///
1094    /// As the target platform's native endianness is used, portable code
1095    /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1096    /// appropriate instead.
1097    ///
1098    /// [`from_be_bytes`]: f128::from_be_bytes
1099    /// [`from_le_bytes`]: f128::from_le_bytes
1100    ///
1101    /// See [`from_bits`](Self::from_bits) for some discussion of the
1102    /// portability of this operation (there are almost no issues).
1103    ///
1104    /// # Examples
1105    ///
1106    /// ```
1107    /// #![feature(f128)]
1108    /// # // FIXME(f16_f128): remove when `eqtf2` is available
1109    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1110    ///
1111    /// let value = f128::from_ne_bytes(if cfg!(target_endian = "big") {
1112    ///     [0x40, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,
1113    ///      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1114    /// } else {
1115    ///     [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1116    ///      0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x02, 0x40]
1117    /// });
1118    /// assert_eq!(value, 12.5);
1119    /// # }
1120    /// ```
1121    #[inline]
1122    #[must_use]
1123    #[unstable(feature = "f128", issue = "116909")]
1124    pub const fn from_ne_bytes(bytes: [u8; 16]) -> Self {
1125        Self::from_bits(u128::from_ne_bytes(bytes))
1126    }
1127
1128    /// Returns the ordering between `self` and `other`.
1129    ///
1130    /// Unlike the standard partial comparison between floating point numbers,
1131    /// this comparison always produces an ordering in accordance to
1132    /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1133    /// floating point standard. The values are ordered in the following sequence:
1134    ///
1135    /// - negative quiet NaN
1136    /// - negative signaling NaN
1137    /// - negative infinity
1138    /// - negative numbers
1139    /// - negative subnormal numbers
1140    /// - negative zero
1141    /// - positive zero
1142    /// - positive subnormal numbers
1143    /// - positive numbers
1144    /// - positive infinity
1145    /// - positive signaling NaN
1146    /// - positive quiet NaN.
1147    ///
1148    /// The ordering established by this function does not always agree with the
1149    /// [`PartialOrd`] and [`PartialEq`] implementations of `f128`. For example,
1150    /// they consider negative and positive zero equal, while `total_cmp`
1151    /// doesn't.
1152    ///
1153    /// The interpretation of the signaling NaN bit follows the definition in
1154    /// the IEEE 754 standard, which may not match the interpretation by some of
1155    /// the older, non-conformant (e.g. MIPS) hardware implementations.
1156    ///
1157    /// # Example
1158    ///
1159    /// ```
1160    /// #![feature(f128)]
1161    ///
1162    /// struct GoodBoy {
1163    ///     name: &'static str,
1164    ///     weight: f128,
1165    /// }
1166    ///
1167    /// let mut bois = vec![
1168    ///     GoodBoy { name: "Pucci", weight: 0.1 },
1169    ///     GoodBoy { name: "Woofer", weight: 99.0 },
1170    ///     GoodBoy { name: "Yapper", weight: 10.0 },
1171    ///     GoodBoy { name: "Chonk", weight: f128::INFINITY },
1172    ///     GoodBoy { name: "Abs. Unit", weight: f128::NAN },
1173    ///     GoodBoy { name: "Floaty", weight: -5.0 },
1174    /// ];
1175    ///
1176    /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1177    ///
1178    /// // `f128::NAN` could be positive or negative, which will affect the sort order.
1179    /// if f128::NAN.is_sign_negative() {
1180    ///     bois.into_iter().map(|b| b.weight)
1181    ///         .zip([f128::NAN, -5.0, 0.1, 10.0, 99.0, f128::INFINITY].iter())
1182    ///         .for_each(|(a, b)| assert_eq!(a.to_bits(), b.to_bits()))
1183    /// } else {
1184    ///     bois.into_iter().map(|b| b.weight)
1185    ///         .zip([-5.0, 0.1, 10.0, 99.0, f128::INFINITY, f128::NAN].iter())
1186    ///         .for_each(|(a, b)| assert_eq!(a.to_bits(), b.to_bits()))
1187    /// }
1188    /// ```
1189    #[inline]
1190    #[must_use]
1191    #[unstable(feature = "f128", issue = "116909")]
1192    pub fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1193        let mut left = self.to_bits() as i128;
1194        let mut right = other.to_bits() as i128;
1195
1196        // In case of negatives, flip all the bits except the sign
1197        // to achieve a similar layout as two's complement integers
1198        //
1199        // Why does this work? IEEE 754 floats consist of three fields:
1200        // Sign bit, exponent and mantissa. The set of exponent and mantissa
1201        // fields as a whole have the property that their bitwise order is
1202        // equal to the numeric magnitude where the magnitude is defined.
1203        // The magnitude is not normally defined on NaN values, but
1204        // IEEE 754 totalOrder defines the NaN values also to follow the
1205        // bitwise order. This leads to order explained in the doc comment.
1206        // However, the representation of magnitude is the same for negative
1207        // and positive numbers – only the sign bit is different.
1208        // To easily compare the floats as signed integers, we need to
1209        // flip the exponent and mantissa bits in case of negative numbers.
1210        // We effectively convert the numbers to "two's complement" form.
1211        //
1212        // To do the flipping, we construct a mask and XOR against it.
1213        // We branchlessly calculate an "all-ones except for the sign bit"
1214        // mask from negative-signed values: right shifting sign-extends
1215        // the integer, so we "fill" the mask with sign bits, and then
1216        // convert to unsigned to push one more zero bit.
1217        // On positive values, the mask is all zeros, so it's a no-op.
1218        left ^= (((left >> 127) as u128) >> 1) as i128;
1219        right ^= (((right >> 127) as u128) >> 1) as i128;
1220
1221        left.cmp(&right)
1222    }
1223
1224    /// Restrict a value to a certain interval unless it is NaN.
1225    ///
1226    /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1227    /// less than `min`. Otherwise this returns `self`.
1228    ///
1229    /// Note that this function returns NaN if the initial value was NaN as
1230    /// well.
1231    ///
1232    /// # Panics
1233    ///
1234    /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1235    ///
1236    /// # Examples
1237    ///
1238    /// ```
1239    /// #![feature(f128)]
1240    /// # // FIXME(f16_f128): remove when `{eq,gt,unord}tf` are available
1241    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1242    ///
1243    /// assert!((-3.0f128).clamp(-2.0, 1.0) == -2.0);
1244    /// assert!((0.0f128).clamp(-2.0, 1.0) == 0.0);
1245    /// assert!((2.0f128).clamp(-2.0, 1.0) == 1.0);
1246    /// assert!((f128::NAN).clamp(-2.0, 1.0).is_nan());
1247    /// # }
1248    /// ```
1249    #[inline]
1250    #[unstable(feature = "f128", issue = "116909")]
1251    #[must_use = "method returns a new number and does not mutate the original value"]
1252    pub const fn clamp(mut self, min: f128, max: f128) -> f128 {
1253        const_assert!(
1254            min <= max,
1255            "min > max, or either was NaN",
1256            "min > max, or either was NaN. min = {min:?}, max = {max:?}",
1257            min: f128,
1258            max: f128,
1259        );
1260
1261        if self < min {
1262            self = min;
1263        }
1264        if self > max {
1265            self = max;
1266        }
1267        self
1268    }
1269
1270    /// Computes the absolute value of `self`.
1271    ///
1272    /// This function always returns the precise result.
1273    ///
1274    /// # Examples
1275    ///
1276    /// ```
1277    /// #![feature(f128)]
1278    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1279    ///
1280    /// let x = 3.5_f128;
1281    /// let y = -3.5_f128;
1282    ///
1283    /// assert_eq!(x.abs(), x);
1284    /// assert_eq!(y.abs(), -y);
1285    ///
1286    /// assert!(f128::NAN.abs().is_nan());
1287    /// # }
1288    /// ```
1289    #[inline]
1290    #[unstable(feature = "f128", issue = "116909")]
1291    #[rustc_const_unstable(feature = "f128", issue = "116909")]
1292    #[must_use = "method returns a new number and does not mutate the original value"]
1293    pub const fn abs(self) -> Self {
1294        // FIXME(f16_f128): replace with `intrinsics::fabsf128` when available
1295        // We don't do this now because LLVM has lowering bugs for f128 math.
1296        Self::from_bits(self.to_bits() & !(1 << 127))
1297    }
1298
1299    /// Returns a number that represents the sign of `self`.
1300    ///
1301    /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
1302    /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
1303    /// - NaN if the number is NaN
1304    ///
1305    /// # Examples
1306    ///
1307    /// ```
1308    /// #![feature(f128)]
1309    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1310    ///
1311    /// let f = 3.5_f128;
1312    ///
1313    /// assert_eq!(f.signum(), 1.0);
1314    /// assert_eq!(f128::NEG_INFINITY.signum(), -1.0);
1315    ///
1316    /// assert!(f128::NAN.signum().is_nan());
1317    /// # }
1318    /// ```
1319    #[inline]
1320    #[unstable(feature = "f128", issue = "116909")]
1321    #[rustc_const_unstable(feature = "f128", issue = "116909")]
1322    #[must_use = "method returns a new number and does not mutate the original value"]
1323    pub const fn signum(self) -> f128 {
1324        if self.is_nan() { Self::NAN } else { 1.0_f128.copysign(self) }
1325    }
1326
1327    /// Returns a number composed of the magnitude of `self` and the sign of
1328    /// `sign`.
1329    ///
1330    /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`.
1331    /// If `self` is a NaN, then a NaN with the same payload as `self` and the sign bit of `sign` is
1332    /// returned.
1333    ///
1334    /// If `sign` is a NaN, then this operation will still carry over its sign into the result. Note
1335    /// that IEEE 754 doesn't assign any meaning to the sign bit in case of a NaN, and as Rust
1336    /// doesn't guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the
1337    /// result of `copysign` with `sign` being a NaN might produce an unexpected or non-portable
1338    /// result. See the [specification of NaN bit patterns](primitive@f32#nan-bit-patterns) for more
1339    /// info.
1340    ///
1341    /// # Examples
1342    ///
1343    /// ```
1344    /// #![feature(f128)]
1345    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1346    ///
1347    /// let f = 3.5_f128;
1348    ///
1349    /// assert_eq!(f.copysign(0.42), 3.5_f128);
1350    /// assert_eq!(f.copysign(-0.42), -3.5_f128);
1351    /// assert_eq!((-f).copysign(0.42), 3.5_f128);
1352    /// assert_eq!((-f).copysign(-0.42), -3.5_f128);
1353    ///
1354    /// assert!(f128::NAN.copysign(1.0).is_nan());
1355    /// # }
1356    /// ```
1357    #[inline]
1358    #[unstable(feature = "f128", issue = "116909")]
1359    #[rustc_const_unstable(feature = "f128", issue = "116909")]
1360    #[must_use = "method returns a new number and does not mutate the original value"]
1361    pub const fn copysign(self, sign: f128) -> f128 {
1362        // SAFETY: this is actually a safe intrinsic
1363        unsafe { intrinsics::copysignf128(self, sign) }
1364    }
1365}