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