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