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")]
21#[rustc_diagnostic_item = "f128_consts_mod"]
22pub mod consts {
23    // FIXME: replace with mathematical constants from cmath.
24
25    /// Archimedes' constant (π)
26    #[unstable(feature = "f128", issue = "116909")]
27    pub const PI: f128 = 3.14159265358979323846264338327950288419716939937510582097494_f128;
28
29    /// The full circle constant (τ)
30    ///
31    /// Equal to 2π.
32    #[unstable(feature = "f128", issue = "116909")]
33    pub const TAU: f128 = 6.28318530717958647692528676655900576839433879875021164194989_f128;
34
35    /// The golden ratio (φ)
36    #[unstable(feature = "f128", issue = "116909")]
37    // Also, #[unstable(feature = "more_float_constants", issue = "146939")]
38    pub const PHI: f128 = 1.61803398874989484820458683436563811772030917980576286213545_f128;
39
40    /// The Euler-Mascheroni constant (γ)
41    #[unstable(feature = "f128", issue = "116909")]
42    // Also, #[unstable(feature = "more_float_constants", issue = "146939")]
43    pub const EGAMMA: f128 = 0.577215664901532860606512090082402431042159335939923598805767_f128;
44
45    /// π/2
46    #[unstable(feature = "f128", issue = "116909")]
47    pub const FRAC_PI_2: f128 = 1.57079632679489661923132169163975144209858469968755291048747_f128;
48
49    /// π/3
50    #[unstable(feature = "f128", issue = "116909")]
51    pub const FRAC_PI_3: f128 = 1.04719755119659774615421446109316762806572313312503527365831_f128;
52
53    /// π/4
54    #[unstable(feature = "f128", issue = "116909")]
55    pub const FRAC_PI_4: f128 = 0.785398163397448309615660845819875721049292349843776455243736_f128;
56
57    /// π/6
58    #[unstable(feature = "f128", issue = "116909")]
59    pub const FRAC_PI_6: f128 = 0.523598775598298873077107230546583814032861566562517636829157_f128;
60
61    /// π/8
62    #[unstable(feature = "f128", issue = "116909")]
63    pub const FRAC_PI_8: f128 = 0.392699081698724154807830422909937860524646174921888227621868_f128;
64
65    /// 1/π
66    #[unstable(feature = "f128", issue = "116909")]
67    pub const FRAC_1_PI: f128 = 0.318309886183790671537767526745028724068919291480912897495335_f128;
68
69    /// 1/sqrt(π)
70    #[unstable(feature = "f128", issue = "116909")]
71    // Also, #[unstable(feature = "more_float_constants", issue = "146939")]
72    pub const FRAC_1_SQRT_PI: f128 =
73        0.564189583547756286948079451560772585844050629328998856844086_f128;
74
75    /// 1/sqrt(2π)
76    #[doc(alias = "FRAC_1_SQRT_TAU")]
77    #[unstable(feature = "f128", issue = "116909")]
78    // Also, #[unstable(feature = "more_float_constants", issue = "146939")]
79    pub const FRAC_1_SQRT_2PI: f128 =
80        0.398942280401432677939946059934381868475858631164934657665926_f128;
81
82    /// 2/π
83    #[unstable(feature = "f128", issue = "116909")]
84    pub const FRAC_2_PI: f128 = 0.636619772367581343075535053490057448137838582961825794990669_f128;
85
86    /// 2/sqrt(π)
87    #[unstable(feature = "f128", issue = "116909")]
88    pub const FRAC_2_SQRT_PI: f128 =
89        1.12837916709551257389615890312154517168810125865799771368817_f128;
90
91    /// sqrt(2)
92    #[unstable(feature = "f128", issue = "116909")]
93    pub const SQRT_2: f128 = 1.41421356237309504880168872420969807856967187537694807317668_f128;
94
95    /// 1/sqrt(2)
96    #[unstable(feature = "f128", issue = "116909")]
97    pub const FRAC_1_SQRT_2: f128 =
98        0.707106781186547524400844362104849039284835937688474036588340_f128;
99
100    /// sqrt(3)
101    #[unstable(feature = "f128", issue = "116909")]
102    // Also, #[unstable(feature = "more_float_constants", issue = "146939")]
103    pub const SQRT_3: f128 = 1.73205080756887729352744634150587236694280525381038062805581_f128;
104
105    /// 1/sqrt(3)
106    #[unstable(feature = "f128", issue = "116909")]
107    // Also, #[unstable(feature = "more_float_constants", issue = "146939")]
108    pub const FRAC_1_SQRT_3: f128 =
109        0.577350269189625764509148780501957455647601751270126876018602_f128;
110
111    /// Euler's number (e)
112    #[unstable(feature = "f128", issue = "116909")]
113    pub const E: f128 = 2.71828182845904523536028747135266249775724709369995957496697_f128;
114
115    /// log<sub>2</sub>(10)
116    #[unstable(feature = "f128", issue = "116909")]
117    pub const LOG2_10: f128 = 3.32192809488736234787031942948939017586483139302458061205476_f128;
118
119    /// log<sub>2</sub>(e)
120    #[unstable(feature = "f128", issue = "116909")]
121    pub const LOG2_E: f128 = 1.44269504088896340735992468100189213742664595415298593413545_f128;
122
123    /// log<sub>10</sub>(2)
124    #[unstable(feature = "f128", issue = "116909")]
125    pub const LOG10_2: f128 = 0.301029995663981195213738894724493026768189881462108541310427_f128;
126
127    /// log<sub>10</sub>(e)
128    #[unstable(feature = "f128", issue = "116909")]
129    pub const LOG10_E: f128 = 0.434294481903251827651128918916605082294397005803666566114454_f128;
130
131    /// ln(2)
132    #[unstable(feature = "f128", issue = "116909")]
133    pub const LN_2: f128 = 0.693147180559945309417232121458176568075500134360255254120680_f128;
134
135    /// ln(10)
136    #[unstable(feature = "f128", issue = "116909")]
137    pub const LN_10: f128 = 2.30258509299404568401799145468436420760110148862877297603333_f128;
138}
139
140impl f128 {
141    // FIXME(f16_f128): almost all methods in this `impl` are missing examples and a const
142    // implementation. Add these once we can run code on all platforms and have f16/f128 in CTFE.
143
144    /// The radix or base of the internal representation of `f128`.
145    #[unstable(feature = "f128", issue = "116909")]
146    pub const RADIX: u32 = 2;
147
148    /// Number of significant digits in base 2.
149    ///
150    /// Note that the size of the mantissa in the bitwise representation is one
151    /// smaller than this since the leading 1 is not stored explicitly.
152    #[unstable(feature = "f128", issue = "116909")]
153    pub const MANTISSA_DIGITS: u32 = 113;
154
155    /// Approximate number of significant digits in base 10.
156    ///
157    /// This is the maximum <i>x</i> such that any decimal number with <i>x</i>
158    /// significant digits can be converted to `f128` and back without loss.
159    ///
160    /// Equal to floor(log<sub>10</sub>&nbsp;2<sup>[`MANTISSA_DIGITS`]&nbsp;&minus;&nbsp;1</sup>).
161    ///
162    /// [`MANTISSA_DIGITS`]: f128::MANTISSA_DIGITS
163    #[unstable(feature = "f128", issue = "116909")]
164    pub const DIGITS: u32 = 33;
165
166    /// [Machine epsilon] value for `f128`.
167    ///
168    /// This is the difference between `1.0` and the next larger representable number.
169    ///
170    /// Equal to 2<sup>1&nbsp;&minus;&nbsp;[`MANTISSA_DIGITS`]</sup>.
171    ///
172    /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
173    /// [`MANTISSA_DIGITS`]: f128::MANTISSA_DIGITS
174    #[unstable(feature = "f128", issue = "116909")]
175    #[rustc_diagnostic_item = "f128_epsilon"]
176    pub const EPSILON: f128 = 1.92592994438723585305597794258492732e-34_f128;
177
178    /// Smallest finite `f128` value.
179    ///
180    /// Equal to &minus;[`MAX`].
181    ///
182    /// [`MAX`]: f128::MAX
183    #[unstable(feature = "f128", issue = "116909")]
184    pub const MIN: f128 = -1.18973149535723176508575932662800702e+4932_f128;
185    /// Smallest positive normal `f128` value.
186    ///
187    /// Equal to 2<sup>[`MIN_EXP`]&nbsp;&minus;&nbsp;1</sup>.
188    ///
189    /// [`MIN_EXP`]: f128::MIN_EXP
190    #[unstable(feature = "f128", issue = "116909")]
191    pub const MIN_POSITIVE: f128 = 3.36210314311209350626267781732175260e-4932_f128;
192    /// Largest finite `f128` value.
193    ///
194    /// Equal to
195    /// (1&nbsp;&minus;&nbsp;2<sup>&minus;[`MANTISSA_DIGITS`]</sup>)&nbsp;2<sup>[`MAX_EXP`]</sup>.
196    ///
197    /// [`MANTISSA_DIGITS`]: f128::MANTISSA_DIGITS
198    /// [`MAX_EXP`]: f128::MAX_EXP
199    #[unstable(feature = "f128", issue = "116909")]
200    pub const MAX: f128 = 1.18973149535723176508575932662800702e+4932_f128;
201
202    /// One greater than the minimum possible *normal* power of 2 exponent
203    /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).
204    ///
205    /// This corresponds to the exact minimum possible *normal* power of 2 exponent
206    /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).
207    /// In other words, all normal numbers representable by this type are
208    /// greater than or equal to 0.5&nbsp;×&nbsp;2<sup><i>MIN_EXP</i></sup>.
209    #[unstable(feature = "f128", issue = "116909")]
210    pub const MIN_EXP: i32 = -16_381;
211    /// One greater than the maximum possible power of 2 exponent
212    /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).
213    ///
214    /// This corresponds to the exact maximum possible power of 2 exponent
215    /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).
216    /// In other words, all numbers representable by this type are
217    /// strictly less than 2<sup><i>MAX_EXP</i></sup>.
218    #[unstable(feature = "f128", issue = "116909")]
219    pub const MAX_EXP: i32 = 16_384;
220
221    /// Minimum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
222    ///
223    /// Equal to ceil(log<sub>10</sub>&nbsp;[`MIN_POSITIVE`]).
224    ///
225    /// [`MIN_POSITIVE`]: f128::MIN_POSITIVE
226    #[unstable(feature = "f128", issue = "116909")]
227    pub const MIN_10_EXP: i32 = -4_931;
228    /// Maximum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
229    ///
230    /// Equal to floor(log<sub>10</sub>&nbsp;[`MAX`]).
231    ///
232    /// [`MAX`]: f128::MAX
233    #[unstable(feature = "f128", issue = "116909")]
234    pub const MAX_10_EXP: i32 = 4_932;
235
236    /// Not a Number (NaN).
237    ///
238    /// Note that IEEE 754 doesn't define just a single NaN value; a plethora of bit patterns are
239    /// considered to be NaN. Furthermore, the standard makes a difference between a "signaling" and
240    /// a "quiet" NaN, and allows inspecting its "payload" (the unspecified bits in the bit pattern)
241    /// and its sign. See the [specification of NaN bit patterns](f32#nan-bit-patterns) for more
242    /// info.
243    ///
244    /// This constant is guaranteed to be a quiet NaN (on targets that follow the Rust assumptions
245    /// that the quiet/signaling bit being set to 1 indicates a quiet NaN). Beyond that, nothing is
246    /// guaranteed about the specific bit pattern chosen here: both payload and sign are arbitrary.
247    /// The concrete bit pattern may change across Rust versions and target platforms.
248    #[allow(clippy::eq_op)]
249    #[rustc_diagnostic_item = "f128_nan"]
250    #[unstable(feature = "f128", issue = "116909")]
251    pub const NAN: f128 = 0.0_f128 / 0.0_f128;
252
253    /// Infinity (∞).
254    #[unstable(feature = "f128", issue = "116909")]
255    pub const INFINITY: f128 = 1.0_f128 / 0.0_f128;
256
257    /// Negative infinity (−∞).
258    #[unstable(feature = "f128", issue = "116909")]
259    pub const NEG_INFINITY: f128 = -1.0_f128 / 0.0_f128;
260
261    /// Sign bit
262    pub(crate) const SIGN_MASK: u128 = 0x8000_0000_0000_0000_0000_0000_0000_0000;
263
264    /// Exponent mask
265    pub(crate) const EXP_MASK: u128 = 0x7fff_0000_0000_0000_0000_0000_0000_0000;
266
267    /// Mantissa mask
268    pub(crate) const MAN_MASK: u128 = 0x0000_ffff_ffff_ffff_ffff_ffff_ffff_ffff;
269
270    /// Minimum representable positive value (min subnormal)
271    const TINY_BITS: u128 = 0x1;
272
273    /// Minimum representable negative value (min negative subnormal)
274    const NEG_TINY_BITS: u128 = Self::TINY_BITS | Self::SIGN_MASK;
275
276    /// Returns `true` if this value is NaN.
277    ///
278    /// ```
279    /// #![feature(f128)]
280    /// # // FIXME(f16_f128): remove when `unordtf2` is available
281    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
282    ///
283    /// let nan = f128::NAN;
284    /// let f = 7.0_f128;
285    ///
286    /// assert!(nan.is_nan());
287    /// assert!(!f.is_nan());
288    /// # }
289    /// ```
290    #[inline]
291    #[must_use]
292    #[unstable(feature = "f128", issue = "116909")]
293    #[allow(clippy::eq_op)] // > if you intended to check if the operand is NaN, use `.is_nan()` instead :)
294    pub const fn is_nan(self) -> bool {
295        self != self
296    }
297
298    /// Returns `true` if this value is positive infinity or negative infinity, and
299    /// `false` otherwise.
300    ///
301    /// ```
302    /// #![feature(f128)]
303    /// # // FIXME(f16_f128): remove when `eqtf2` is available
304    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
305    ///
306    /// let f = 7.0f128;
307    /// let inf = f128::INFINITY;
308    /// let neg_inf = f128::NEG_INFINITY;
309    /// let nan = f128::NAN;
310    ///
311    /// assert!(!f.is_infinite());
312    /// assert!(!nan.is_infinite());
313    ///
314    /// assert!(inf.is_infinite());
315    /// assert!(neg_inf.is_infinite());
316    /// # }
317    /// ```
318    #[inline]
319    #[must_use]
320    #[unstable(feature = "f128", issue = "116909")]
321    pub const fn is_infinite(self) -> bool {
322        (self == f128::INFINITY) | (self == f128::NEG_INFINITY)
323    }
324
325    /// Returns `true` if this number is neither infinite nor NaN.
326    ///
327    /// ```
328    /// #![feature(f128)]
329    /// # // FIXME(f16_f128): remove when `lttf2` is available
330    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
331    ///
332    /// let f = 7.0f128;
333    /// let inf: f128 = f128::INFINITY;
334    /// let neg_inf: f128 = f128::NEG_INFINITY;
335    /// let nan: f128 = f128::NAN;
336    ///
337    /// assert!(f.is_finite());
338    ///
339    /// assert!(!nan.is_finite());
340    /// assert!(!inf.is_finite());
341    /// assert!(!neg_inf.is_finite());
342    /// # }
343    /// ```
344    #[inline]
345    #[must_use]
346    #[unstable(feature = "f128", issue = "116909")]
347    #[rustc_const_unstable(feature = "f128", issue = "116909")]
348    pub const fn is_finite(self) -> bool {
349        // There's no need to handle NaN separately: if self is NaN,
350        // the comparison is not true, exactly as desired.
351        self.abs() < Self::INFINITY
352    }
353
354    /// Returns `true` if the number is [subnormal].
355    ///
356    /// ```
357    /// #![feature(f128)]
358    /// # // FIXME(f16_f128): remove when `eqtf2` is available
359    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
360    ///
361    /// let min = f128::MIN_POSITIVE; // 3.362103143e-4932f128
362    /// let max = f128::MAX;
363    /// let lower_than_min = 1.0e-4960_f128;
364    /// let zero = 0.0_f128;
365    ///
366    /// assert!(!min.is_subnormal());
367    /// assert!(!max.is_subnormal());
368    ///
369    /// assert!(!zero.is_subnormal());
370    /// assert!(!f128::NAN.is_subnormal());
371    /// assert!(!f128::INFINITY.is_subnormal());
372    /// // Values between `0` and `min` are Subnormal.
373    /// assert!(lower_than_min.is_subnormal());
374    /// # }
375    /// ```
376    ///
377    /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
378    #[inline]
379    #[must_use]
380    #[unstable(feature = "f128", issue = "116909")]
381    pub const fn is_subnormal(self) -> bool {
382        matches!(self.classify(), FpCategory::Subnormal)
383    }
384
385    /// Returns `true` if the number is neither zero, infinite, [subnormal], or NaN.
386    ///
387    /// ```
388    /// #![feature(f128)]
389    /// # // FIXME(f16_f128): remove when `eqtf2` is available
390    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
391    ///
392    /// let min = f128::MIN_POSITIVE; // 3.362103143e-4932f128
393    /// let max = f128::MAX;
394    /// let lower_than_min = 1.0e-4960_f128;
395    /// let zero = 0.0_f128;
396    ///
397    /// assert!(min.is_normal());
398    /// assert!(max.is_normal());
399    ///
400    /// assert!(!zero.is_normal());
401    /// assert!(!f128::NAN.is_normal());
402    /// assert!(!f128::INFINITY.is_normal());
403    /// // Values between `0` and `min` are Subnormal.
404    /// assert!(!lower_than_min.is_normal());
405    /// # }
406    /// ```
407    ///
408    /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
409    #[inline]
410    #[must_use]
411    #[unstable(feature = "f128", issue = "116909")]
412    pub const fn is_normal(self) -> bool {
413        matches!(self.classify(), FpCategory::Normal)
414    }
415
416    /// Returns the floating point category of the number. If only one property
417    /// is going to be tested, it is generally faster to use the specific
418    /// predicate instead.
419    ///
420    /// ```
421    /// #![feature(f128)]
422    /// # // FIXME(f16_f128): remove when `eqtf2` is available
423    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
424    ///
425    /// use std::num::FpCategory;
426    ///
427    /// let num = 12.4_f128;
428    /// let inf = f128::INFINITY;
429    ///
430    /// assert_eq!(num.classify(), FpCategory::Normal);
431    /// assert_eq!(inf.classify(), FpCategory::Infinite);
432    /// # }
433    /// ```
434    #[inline]
435    #[unstable(feature = "f128", issue = "116909")]
436    pub const fn classify(self) -> FpCategory {
437        let bits = self.to_bits();
438        match (bits & Self::MAN_MASK, bits & Self::EXP_MASK) {
439            (0, Self::EXP_MASK) => FpCategory::Infinite,
440            (_, Self::EXP_MASK) => FpCategory::Nan,
441            (0, 0) => FpCategory::Zero,
442            (_, 0) => FpCategory::Subnormal,
443            _ => FpCategory::Normal,
444        }
445    }
446
447    /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with
448    /// positive sign bit and positive infinity.
449    ///
450    /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
451    /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
452    /// conserved over arithmetic operations, the result of `is_sign_positive` on
453    /// a NaN might produce an unexpected or non-portable result. See the [specification
454    /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == 1.0`
455    /// if you need fully portable behavior (will return `false` for all NaNs).
456    ///
457    /// ```
458    /// #![feature(f128)]
459    ///
460    /// let f = 7.0_f128;
461    /// let g = -7.0_f128;
462    ///
463    /// assert!(f.is_sign_positive());
464    /// assert!(!g.is_sign_positive());
465    /// ```
466    #[inline]
467    #[must_use]
468    #[unstable(feature = "f128", issue = "116909")]
469    pub const fn is_sign_positive(self) -> bool {
470        !self.is_sign_negative()
471    }
472
473    /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with
474    /// negative sign bit and negative infinity.
475    ///
476    /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
477    /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
478    /// conserved over arithmetic operations, the result of `is_sign_negative` on
479    /// a NaN might produce an unexpected or non-portable result. See the [specification
480    /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == -1.0`
481    /// if you need fully portable behavior (will return `false` for all NaNs).
482    ///
483    /// ```
484    /// #![feature(f128)]
485    ///
486    /// let f = 7.0_f128;
487    /// let g = -7.0_f128;
488    ///
489    /// assert!(!f.is_sign_negative());
490    /// assert!(g.is_sign_negative());
491    /// ```
492    #[inline]
493    #[must_use]
494    #[unstable(feature = "f128", issue = "116909")]
495    pub const fn is_sign_negative(self) -> bool {
496        // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
497        // applies to zeros and NaNs as well.
498        // SAFETY: This is just transmuting to get the sign bit, it's fine.
499        (self.to_bits() & (1 << 127)) != 0
500    }
501
502    /// Returns the least number greater than `self`.
503    ///
504    /// Let `TINY` be the smallest representable positive `f128`. Then,
505    ///  - if `self.is_nan()`, this returns `self`;
506    ///  - if `self` is [`NEG_INFINITY`], this returns [`MIN`];
507    ///  - if `self` is `-TINY`, this returns -0.0;
508    ///  - if `self` is -0.0 or +0.0, this returns `TINY`;
509    ///  - if `self` is [`MAX`] or [`INFINITY`], this returns [`INFINITY`];
510    ///  - otherwise the unique least value greater than `self` is returned.
511    ///
512    /// The identity `x.next_up() == -(-x).next_down()` holds for all non-NaN `x`. When `x`
513    /// is finite `x == x.next_up().next_down()` also holds.
514    ///
515    /// ```rust
516    /// #![feature(f128)]
517    /// # // FIXME(f16_f128): remove when `eqtf2` is available
518    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
519    ///
520    /// // f128::EPSILON is the difference between 1.0 and the next number up.
521    /// assert_eq!(1.0f128.next_up(), 1.0 + f128::EPSILON);
522    /// // But not for most numbers.
523    /// assert!(0.1f128.next_up() < 0.1 + f128::EPSILON);
524    /// assert_eq!(4611686018427387904f128.next_up(), 4611686018427387904.000000000000001);
525    /// # }
526    /// ```
527    ///
528    /// This operation corresponds to IEEE-754 `nextUp`.
529    ///
530    /// [`NEG_INFINITY`]: Self::NEG_INFINITY
531    /// [`INFINITY`]: Self::INFINITY
532    /// [`MIN`]: Self::MIN
533    /// [`MAX`]: Self::MAX
534    #[inline]
535    #[doc(alias = "nextUp")]
536    #[unstable(feature = "f128", issue = "116909")]
537    pub const fn next_up(self) -> Self {
538        // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
539        // denormals to zero. This is in general unsound and unsupported, but here
540        // we do our best to still produce the correct result on such targets.
541        let bits = self.to_bits();
542        if self.is_nan() || bits == Self::INFINITY.to_bits() {
543            return self;
544        }
545
546        let abs = bits & !Self::SIGN_MASK;
547        let next_bits = if abs == 0 {
548            Self::TINY_BITS
549        } else if bits == abs {
550            bits + 1
551        } else {
552            bits - 1
553        };
554        Self::from_bits(next_bits)
555    }
556
557    /// Returns the greatest number less than `self`.
558    ///
559    /// Let `TINY` be the smallest representable positive `f128`. Then,
560    ///  - if `self.is_nan()`, this returns `self`;
561    ///  - if `self` is [`INFINITY`], this returns [`MAX`];
562    ///  - if `self` is `TINY`, this returns 0.0;
563    ///  - if `self` is -0.0 or +0.0, this returns `-TINY`;
564    ///  - if `self` is [`MIN`] or [`NEG_INFINITY`], this returns [`NEG_INFINITY`];
565    ///  - otherwise the unique greatest value less than `self` is returned.
566    ///
567    /// The identity `x.next_down() == -(-x).next_up()` holds for all non-NaN `x`. When `x`
568    /// is finite `x == x.next_down().next_up()` also holds.
569    ///
570    /// ```rust
571    /// #![feature(f128)]
572    /// # // FIXME(f16_f128): remove when `eqtf2` is available
573    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
574    ///
575    /// let x = 1.0f128;
576    /// // Clamp value into range [0, 1).
577    /// let clamped = x.clamp(0.0, 1.0f128.next_down());
578    /// assert!(clamped < 1.0);
579    /// assert_eq!(clamped.next_up(), 1.0);
580    /// # }
581    /// ```
582    ///
583    /// This operation corresponds to IEEE-754 `nextDown`.
584    ///
585    /// [`NEG_INFINITY`]: Self::NEG_INFINITY
586    /// [`INFINITY`]: Self::INFINITY
587    /// [`MIN`]: Self::MIN
588    /// [`MAX`]: Self::MAX
589    #[inline]
590    #[doc(alias = "nextDown")]
591    #[unstable(feature = "f128", issue = "116909")]
592    pub const fn next_down(self) -> Self {
593        // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
594        // denormals to zero. This is in general unsound and unsupported, but here
595        // we do our best to still produce the correct result on such targets.
596        let bits = self.to_bits();
597        if self.is_nan() || bits == Self::NEG_INFINITY.to_bits() {
598            return self;
599        }
600
601        let abs = bits & !Self::SIGN_MASK;
602        let next_bits = if abs == 0 {
603            Self::NEG_TINY_BITS
604        } else if bits == abs {
605            bits - 1
606        } else {
607            bits + 1
608        };
609        Self::from_bits(next_bits)
610    }
611
612    /// Takes the reciprocal (inverse) of a number, `1/x`.
613    ///
614    /// ```
615    /// #![feature(f128)]
616    /// # // FIXME(f16_f128): remove when `eqtf2` is available
617    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
618    ///
619    /// let x = 2.0_f128;
620    /// let abs_difference = (x.recip() - (1.0 / x)).abs();
621    ///
622    /// assert!(abs_difference <= f128::EPSILON);
623    /// # }
624    /// ```
625    #[inline]
626    #[unstable(feature = "f128", issue = "116909")]
627    #[must_use = "this returns the result of the operation, without modifying the original"]
628    pub const fn recip(self) -> Self {
629        1.0 / self
630    }
631
632    /// Converts radians to degrees.
633    ///
634    /// # Unspecified precision
635    ///
636    /// The precision of this function is non-deterministic. This means it varies by platform,
637    /// Rust version, and can even differ within the same execution from one invocation to the next.
638    ///
639    /// # Examples
640    ///
641    /// ```
642    /// #![feature(f128)]
643    /// # // FIXME(f16_f128): remove when `eqtf2` is available
644    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
645    ///
646    /// let angle = std::f128::consts::PI;
647    ///
648    /// let abs_difference = (angle.to_degrees() - 180.0).abs();
649    /// assert!(abs_difference <= f128::EPSILON);
650    /// # }
651    /// ```
652    #[inline]
653    #[unstable(feature = "f128", issue = "116909")]
654    #[must_use = "this returns the result of the operation, without modifying the original"]
655    pub const fn to_degrees(self) -> Self {
656        // The division here is correctly rounded with respect to the true value of 180/π.
657        // Although π is irrational and already rounded, the double rounding happens
658        // to produce correct result for f128.
659        const PIS_IN_180: f128 = 180.0 / consts::PI;
660        self * PIS_IN_180
661    }
662
663    /// Converts degrees to radians.
664    ///
665    /// # Unspecified precision
666    ///
667    /// The precision of this function is non-deterministic. This means it varies by platform,
668    /// Rust version, and can even differ within the same execution from one invocation to the next.
669    ///
670    /// # Examples
671    ///
672    /// ```
673    /// #![feature(f128)]
674    /// # // FIXME(f16_f128): remove when `eqtf2` is available
675    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
676    ///
677    /// let angle = 180.0f128;
678    ///
679    /// let abs_difference = (angle.to_radians() - std::f128::consts::PI).abs();
680    ///
681    /// assert!(abs_difference <= 1e-30);
682    /// # }
683    /// ```
684    #[inline]
685    #[unstable(feature = "f128", issue = "116909")]
686    #[must_use = "this returns the result of the operation, without modifying the original"]
687    pub const fn to_radians(self) -> f128 {
688        // Use a literal to avoid double rounding, consts::PI is already rounded,
689        // and dividing would round again.
690        const RADS_PER_DEG: f128 =
691            0.0174532925199432957692369076848861271344287188854172545609719_f128;
692        self * RADS_PER_DEG
693    }
694
695    /// Returns the maximum of the two numbers, ignoring NaN.
696    ///
697    /// If exactly one of the arguments is NaN, then the other argument is returned. If both
698    /// arguments are NaN, the return value is NaN, with the bit pattern picked using the usual
699    /// [rules for arithmetic operations](f32#nan-bit-patterns). If the inputs compare equal (such
700    /// as for the case of `+0.0` and `-0.0`), either input may be returned non-deterministically.
701    ///
702    /// This follows the IEEE 754-2008 semantics for `maxNum`, except for handling of signaling NaNs;
703    /// this function handles all NaNs the same way and avoids `maxNum`'s problems with associativity.
704    /// This also matches the behavior of libm’s `fmax`.
705    ///
706    /// ```
707    /// #![feature(f128)]
708    /// # // Using aarch64 because `reliable_f128_math` is needed
709    /// # #[cfg(all(target_arch = "aarch64", target_os = "linux"))] {
710    ///
711    /// let x = 1.0f128;
712    /// let y = 2.0f128;
713    ///
714    /// assert_eq!(x.max(y), y);
715    /// assert_eq!(x.max(f128::NAN), x);
716    /// # }
717    /// ```
718    #[inline]
719    #[unstable(feature = "f128", issue = "116909")]
720    #[rustc_const_unstable(feature = "f128", issue = "116909")]
721    #[must_use = "this returns the result of the comparison, without modifying either input"]
722    pub const fn max(self, other: f128) -> f128 {
723        intrinsics::maxnumf128(self, other)
724    }
725
726    /// Returns the minimum of the two numbers, ignoring NaN.
727    ///
728    /// If exactly one of the arguments is NaN, then the other argument is returned. If both
729    /// arguments are NaN, the return value is NaN, with the bit pattern picked using the usual
730    /// [rules for arithmetic operations](f32#nan-bit-patterns). If the inputs compare equal (such
731    /// as for the case of `+0.0` and `-0.0`), either input may be returned non-deterministically.
732    ///
733    /// This follows the IEEE 754-2008 semantics for `minNum`, except for handling of signaling NaNs;
734    /// this function handles all NaNs the same way and avoids `minNum`'s problems with associativity.
735    /// This also matches the behavior of libm’s `fmin`.
736    ///
737    /// ```
738    /// #![feature(f128)]
739    /// # // Using aarch64 because `reliable_f128_math` is needed
740    /// # #[cfg(all(target_arch = "aarch64", target_os = "linux"))] {
741    ///
742    /// let x = 1.0f128;
743    /// let y = 2.0f128;
744    ///
745    /// assert_eq!(x.min(y), x);
746    /// assert_eq!(x.min(f128::NAN), x);
747    /// # }
748    /// ```
749    #[inline]
750    #[unstable(feature = "f128", issue = "116909")]
751    #[rustc_const_unstable(feature = "f128", issue = "116909")]
752    #[must_use = "this returns the result of the comparison, without modifying either input"]
753    pub const fn min(self, other: f128) -> f128 {
754        intrinsics::minnumf128(self, other)
755    }
756
757    /// Returns the maximum of the two numbers, propagating NaN.
758    ///
759    /// If at least one of the arguments is NaN, the return value is NaN, with the bit pattern
760    /// picked using the usual [rules for arithmetic operations](f32#nan-bit-patterns). Furthermore,
761    /// `-0.0` is considered to be less than `+0.0`, making this function fully deterministic for
762    /// non-NaN inputs.
763    ///
764    /// This is in contrast to [`f128::max`] which only returns NaN when *both* arguments are NaN,
765    /// and which does not reliably order `-0.0` and `+0.0`.
766    ///
767    /// This follows the IEEE 754-2019 semantics for `maximum`.
768    ///
769    /// ```
770    /// #![feature(f128)]
771    /// #![feature(float_minimum_maximum)]
772    /// # // Using aarch64 because `reliable_f128_math` is needed
773    /// # #[cfg(all(target_arch = "aarch64", target_os = "linux"))] {
774    ///
775    /// let x = 1.0f128;
776    /// let y = 2.0f128;
777    ///
778    /// assert_eq!(x.maximum(y), y);
779    /// assert!(x.maximum(f128::NAN).is_nan());
780    /// # }
781    /// ```
782    #[inline]
783    #[unstable(feature = "f128", issue = "116909")]
784    // #[unstable(feature = "float_minimum_maximum", issue = "91079")]
785    #[must_use = "this returns the result of the comparison, without modifying either input"]
786    pub const fn maximum(self, other: f128) -> f128 {
787        intrinsics::maximumf128(self, other)
788    }
789
790    /// Returns the minimum of the two numbers, propagating NaN.
791    ///
792    /// If at least one of the arguments is NaN, the return value is NaN, with the bit pattern
793    /// picked using the usual [rules for arithmetic operations](f32#nan-bit-patterns). Furthermore,
794    /// `-0.0` is considered to be less than `+0.0`, making this function fully deterministic for
795    /// non-NaN inputs.
796    ///
797    /// This is in contrast to [`f128::min`] which only returns NaN when *both* arguments are NaN,
798    /// and which does not reliably order `-0.0` and `+0.0`.
799    ///
800    /// This follows the IEEE 754-2019 semantics for `minimum`.
801    ///
802    /// ```
803    /// #![feature(f128)]
804    /// #![feature(float_minimum_maximum)]
805    /// # // Using aarch64 because `reliable_f128_math` is needed
806    /// # #[cfg(all(target_arch = "aarch64", target_os = "linux"))] {
807    ///
808    /// let x = 1.0f128;
809    /// let y = 2.0f128;
810    ///
811    /// assert_eq!(x.minimum(y), x);
812    /// assert!(x.minimum(f128::NAN).is_nan());
813    /// # }
814    /// ```
815    #[inline]
816    #[unstable(feature = "f128", issue = "116909")]
817    // #[unstable(feature = "float_minimum_maximum", issue = "91079")]
818    #[must_use = "this returns the result of the comparison, without modifying either input"]
819    pub const fn minimum(self, other: f128) -> f128 {
820        intrinsics::minimumf128(self, other)
821    }
822
823    /// Calculates the midpoint (average) between `self` and `rhs`.
824    ///
825    /// This returns NaN when *either* argument is NaN or if a combination of
826    /// +inf and -inf is provided as arguments.
827    ///
828    /// # Examples
829    ///
830    /// ```
831    /// #![feature(f128)]
832    /// # // Using aarch64 because `reliable_f128_math` is needed
833    /// # #[cfg(all(target_arch = "aarch64", target_os = "linux"))] {
834    ///
835    /// assert_eq!(1f128.midpoint(4.0), 2.5);
836    /// assert_eq!((-5.5f128).midpoint(8.0), 1.25);
837    /// # }
838    /// ```
839    #[inline]
840    #[doc(alias = "average")]
841    #[unstable(feature = "f128", issue = "116909")]
842    #[rustc_const_unstable(feature = "f128", issue = "116909")]
843    pub const fn midpoint(self, other: f128) -> f128 {
844        const HI: f128 = f128::MAX / 2.;
845
846        let (a, b) = (self, other);
847        let abs_a = a.abs();
848        let abs_b = b.abs();
849
850        if abs_a <= HI && abs_b <= HI {
851            // Overflow is impossible
852            (a + b) / 2.
853        } else {
854            (a / 2.) + (b / 2.)
855        }
856    }
857
858    /// Rounds toward zero and converts to any primitive integer type,
859    /// assuming that the value is finite and fits in that type.
860    ///
861    /// ```
862    /// #![feature(f128)]
863    /// # // FIXME(f16_f128): remove when `float*itf` is available
864    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
865    ///
866    /// let value = 4.6_f128;
867    /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
868    /// assert_eq!(rounded, 4);
869    ///
870    /// let value = -128.9_f128;
871    /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
872    /// assert_eq!(rounded, i8::MIN);
873    /// # }
874    /// ```
875    ///
876    /// # Safety
877    ///
878    /// The value must:
879    ///
880    /// * Not be `NaN`
881    /// * Not be infinite
882    /// * Be representable in the return type `Int`, after truncating off its fractional part
883    #[inline]
884    #[unstable(feature = "f128", issue = "116909")]
885    #[must_use = "this returns the result of the operation, without modifying the original"]
886    pub unsafe fn to_int_unchecked<Int>(self) -> Int
887    where
888        Self: FloatToInt<Int>,
889    {
890        // SAFETY: the caller must uphold the safety contract for
891        // `FloatToInt::to_int_unchecked`.
892        unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
893    }
894
895    /// Raw transmutation to `u128`.
896    ///
897    /// This is currently identical to `transmute::<f128, u128>(self)` on all platforms.
898    ///
899    /// See [`from_bits`](#method.from_bits) for some discussion of the
900    /// portability of this operation (there are almost no issues).
901    ///
902    /// Note that this function is distinct from `as` casting, which attempts to
903    /// preserve the *numeric* value, and not the bitwise value.
904    ///
905    /// ```
906    /// #![feature(f128)]
907    ///
908    /// # // FIXME(f16_f128): enable this once const casting works
909    /// # // assert_ne!((1f128).to_bits(), 1f128 as u128); // to_bits() is not casting!
910    /// assert_eq!((12.5f128).to_bits(), 0x40029000000000000000000000000000);
911    /// ```
912    #[inline]
913    #[unstable(feature = "f128", issue = "116909")]
914    #[must_use = "this returns the result of the operation, without modifying the original"]
915    #[allow(unnecessary_transmutes)]
916    pub const fn to_bits(self) -> u128 {
917        // SAFETY: `u128` is a plain old datatype so we can always transmute to it.
918        unsafe { mem::transmute(self) }
919    }
920
921    /// Raw transmutation from `u128`.
922    ///
923    /// This is currently identical to `transmute::<u128, f128>(v)` on all platforms.
924    /// It turns out this is incredibly portable, for two reasons:
925    ///
926    /// * Floats and Ints have the same endianness on all supported platforms.
927    /// * IEEE 754 very precisely specifies the bit layout of floats.
928    ///
929    /// However there is one caveat: prior to the 2008 version of IEEE 754, how
930    /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
931    /// (notably x86 and ARM) picked the interpretation that was ultimately
932    /// standardized in 2008, but some didn't (notably MIPS). As a result, all
933    /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
934    ///
935    /// Rather than trying to preserve signaling-ness cross-platform, this
936    /// implementation favors preserving the exact bits. This means that
937    /// any payloads encoded in NaNs will be preserved even if the result of
938    /// this method is sent over the network from an x86 machine to a MIPS one.
939    ///
940    /// If the results of this method are only manipulated by the same
941    /// architecture that produced them, then there is no portability concern.
942    ///
943    /// If the input isn't NaN, then there is no portability concern.
944    ///
945    /// If you don't care about signalingness (very likely), then there is no
946    /// portability concern.
947    ///
948    /// Note that this function is distinct from `as` casting, which attempts to
949    /// preserve the *numeric* value, and not the bitwise value.
950    ///
951    /// ```
952    /// #![feature(f128)]
953    /// #  // FIXME(f16_f128): remove when `eqtf2` is available
954    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
955    ///
956    /// let v = f128::from_bits(0x40029000000000000000000000000000);
957    /// assert_eq!(v, 12.5);
958    /// # }
959    /// ```
960    #[inline]
961    #[must_use]
962    #[unstable(feature = "f128", issue = "116909")]
963    #[allow(unnecessary_transmutes)]
964    pub const fn from_bits(v: u128) -> Self {
965        // It turns out the safety issues with sNaN were overblown! Hooray!
966        // SAFETY: `u128` is a plain old datatype so we can always transmute from it.
967        unsafe { mem::transmute(v) }
968    }
969
970    /// Returns the memory representation of this floating point number as a byte array in
971    /// big-endian (network) byte order.
972    ///
973    /// See [`from_bits`](Self::from_bits) for some discussion of the
974    /// portability of this operation (there are almost no issues).
975    ///
976    /// # Examples
977    ///
978    /// ```
979    /// #![feature(f128)]
980    ///
981    /// let bytes = 12.5f128.to_be_bytes();
982    /// assert_eq!(
983    ///     bytes,
984    ///     [0x40, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,
985    ///      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
986    /// );
987    /// ```
988    #[inline]
989    #[unstable(feature = "f128", issue = "116909")]
990    #[must_use = "this returns the result of the operation, without modifying the original"]
991    pub const fn to_be_bytes(self) -> [u8; 16] {
992        self.to_bits().to_be_bytes()
993    }
994
995    /// Returns the memory representation of this floating point number as a byte array in
996    /// little-endian byte order.
997    ///
998    /// See [`from_bits`](Self::from_bits) for some discussion of the
999    /// portability of this operation (there are almost no issues).
1000    ///
1001    /// # Examples
1002    ///
1003    /// ```
1004    /// #![feature(f128)]
1005    ///
1006    /// let bytes = 12.5f128.to_le_bytes();
1007    /// assert_eq!(
1008    ///     bytes,
1009    ///     [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1010    ///      0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x02, 0x40]
1011    /// );
1012    /// ```
1013    #[inline]
1014    #[unstable(feature = "f128", issue = "116909")]
1015    #[must_use = "this returns the result of the operation, without modifying the original"]
1016    pub const fn to_le_bytes(self) -> [u8; 16] {
1017        self.to_bits().to_le_bytes()
1018    }
1019
1020    /// Returns the memory representation of this floating point number as a byte array in
1021    /// native byte order.
1022    ///
1023    /// As the target platform's native endianness is used, portable code
1024    /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1025    ///
1026    /// [`to_be_bytes`]: f128::to_be_bytes
1027    /// [`to_le_bytes`]: f128::to_le_bytes
1028    ///
1029    /// See [`from_bits`](Self::from_bits) for some discussion of the
1030    /// portability of this operation (there are almost no issues).
1031    ///
1032    /// # Examples
1033    ///
1034    /// ```
1035    /// #![feature(f128)]
1036    ///
1037    /// let bytes = 12.5f128.to_ne_bytes();
1038    /// assert_eq!(
1039    ///     bytes,
1040    ///     if cfg!(target_endian = "big") {
1041    ///         [0x40, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,
1042    ///          0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1043    ///     } else {
1044    ///         [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1045    ///          0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x02, 0x40]
1046    ///     }
1047    /// );
1048    /// ```
1049    #[inline]
1050    #[unstable(feature = "f128", issue = "116909")]
1051    #[must_use = "this returns the result of the operation, without modifying the original"]
1052    pub const fn to_ne_bytes(self) -> [u8; 16] {
1053        self.to_bits().to_ne_bytes()
1054    }
1055
1056    /// Creates a floating point value from its representation as a byte array in big endian.
1057    ///
1058    /// See [`from_bits`](Self::from_bits) for some discussion of the
1059    /// portability of this operation (there are almost no issues).
1060    ///
1061    /// # Examples
1062    ///
1063    /// ```
1064    /// #![feature(f128)]
1065    /// # // FIXME(f16_f128): remove when `eqtf2` is available
1066    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1067    ///
1068    /// let value = f128::from_be_bytes(
1069    ///     [0x40, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,
1070    ///      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1071    /// );
1072    /// assert_eq!(value, 12.5);
1073    /// # }
1074    /// ```
1075    #[inline]
1076    #[must_use]
1077    #[unstable(feature = "f128", issue = "116909")]
1078    pub const fn from_be_bytes(bytes: [u8; 16]) -> Self {
1079        Self::from_bits(u128::from_be_bytes(bytes))
1080    }
1081
1082    /// Creates a floating point value from its representation as a byte array in little endian.
1083    ///
1084    /// See [`from_bits`](Self::from_bits) for some discussion of the
1085    /// portability of this operation (there are almost no issues).
1086    ///
1087    /// # Examples
1088    ///
1089    /// ```
1090    /// #![feature(f128)]
1091    /// # // FIXME(f16_f128): remove when `eqtf2` is available
1092    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1093    ///
1094    /// let value = f128::from_le_bytes(
1095    ///     [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1096    ///      0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x02, 0x40]
1097    /// );
1098    /// assert_eq!(value, 12.5);
1099    /// # }
1100    /// ```
1101    #[inline]
1102    #[must_use]
1103    #[unstable(feature = "f128", issue = "116909")]
1104    pub const fn from_le_bytes(bytes: [u8; 16]) -> Self {
1105        Self::from_bits(u128::from_le_bytes(bytes))
1106    }
1107
1108    /// Creates a floating point value from its representation as a byte array in native endian.
1109    ///
1110    /// As the target platform's native endianness is used, portable code
1111    /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1112    /// appropriate instead.
1113    ///
1114    /// [`from_be_bytes`]: f128::from_be_bytes
1115    /// [`from_le_bytes`]: f128::from_le_bytes
1116    ///
1117    /// See [`from_bits`](Self::from_bits) for some discussion of the
1118    /// portability of this operation (there are almost no issues).
1119    ///
1120    /// # Examples
1121    ///
1122    /// ```
1123    /// #![feature(f128)]
1124    /// # // FIXME(f16_f128): remove when `eqtf2` is available
1125    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1126    ///
1127    /// let value = f128::from_ne_bytes(if cfg!(target_endian = "big") {
1128    ///     [0x40, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,
1129    ///      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1130    /// } else {
1131    ///     [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1132    ///      0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x02, 0x40]
1133    /// });
1134    /// assert_eq!(value, 12.5);
1135    /// # }
1136    /// ```
1137    #[inline]
1138    #[must_use]
1139    #[unstable(feature = "f128", issue = "116909")]
1140    pub const fn from_ne_bytes(bytes: [u8; 16]) -> Self {
1141        Self::from_bits(u128::from_ne_bytes(bytes))
1142    }
1143
1144    /// Returns the ordering between `self` and `other`.
1145    ///
1146    /// Unlike the standard partial comparison between floating point numbers,
1147    /// this comparison always produces an ordering in accordance to
1148    /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1149    /// floating point standard. The values are ordered in the following sequence:
1150    ///
1151    /// - negative quiet NaN
1152    /// - negative signaling NaN
1153    /// - negative infinity
1154    /// - negative numbers
1155    /// - negative subnormal numbers
1156    /// - negative zero
1157    /// - positive zero
1158    /// - positive subnormal numbers
1159    /// - positive numbers
1160    /// - positive infinity
1161    /// - positive signaling NaN
1162    /// - positive quiet NaN.
1163    ///
1164    /// The ordering established by this function does not always agree with the
1165    /// [`PartialOrd`] and [`PartialEq`] implementations of `f128`. For example,
1166    /// they consider negative and positive zero equal, while `total_cmp`
1167    /// doesn't.
1168    ///
1169    /// The interpretation of the signaling NaN bit follows the definition in
1170    /// the IEEE 754 standard, which may not match the interpretation by some of
1171    /// the older, non-conformant (e.g. MIPS) hardware implementations.
1172    ///
1173    /// # Example
1174    ///
1175    /// ```
1176    /// #![feature(f128)]
1177    ///
1178    /// struct GoodBoy {
1179    ///     name: &'static str,
1180    ///     weight: f128,
1181    /// }
1182    ///
1183    /// let mut bois = vec![
1184    ///     GoodBoy { name: "Pucci", weight: 0.1 },
1185    ///     GoodBoy { name: "Woofer", weight: 99.0 },
1186    ///     GoodBoy { name: "Yapper", weight: 10.0 },
1187    ///     GoodBoy { name: "Chonk", weight: f128::INFINITY },
1188    ///     GoodBoy { name: "Abs. Unit", weight: f128::NAN },
1189    ///     GoodBoy { name: "Floaty", weight: -5.0 },
1190    /// ];
1191    ///
1192    /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1193    ///
1194    /// // `f128::NAN` could be positive or negative, which will affect the sort order.
1195    /// if f128::NAN.is_sign_negative() {
1196    ///     bois.into_iter().map(|b| b.weight)
1197    ///         .zip([f128::NAN, -5.0, 0.1, 10.0, 99.0, f128::INFINITY].iter())
1198    ///         .for_each(|(a, b)| assert_eq!(a.to_bits(), b.to_bits()))
1199    /// } else {
1200    ///     bois.into_iter().map(|b| b.weight)
1201    ///         .zip([-5.0, 0.1, 10.0, 99.0, f128::INFINITY, f128::NAN].iter())
1202    ///         .for_each(|(a, b)| assert_eq!(a.to_bits(), b.to_bits()))
1203    /// }
1204    /// ```
1205    #[inline]
1206    #[must_use]
1207    #[unstable(feature = "f128", issue = "116909")]
1208    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1209    pub const fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1210        let mut left = self.to_bits() as i128;
1211        let mut right = other.to_bits() as i128;
1212
1213        // In case of negatives, flip all the bits except the sign
1214        // to achieve a similar layout as two's complement integers
1215        //
1216        // Why does this work? IEEE 754 floats consist of three fields:
1217        // Sign bit, exponent and mantissa. The set of exponent and mantissa
1218        // fields as a whole have the property that their bitwise order is
1219        // equal to the numeric magnitude where the magnitude is defined.
1220        // The magnitude is not normally defined on NaN values, but
1221        // IEEE 754 totalOrder defines the NaN values also to follow the
1222        // bitwise order. This leads to order explained in the doc comment.
1223        // However, the representation of magnitude is the same for negative
1224        // and positive numbers – only the sign bit is different.
1225        // To easily compare the floats as signed integers, we need to
1226        // flip the exponent and mantissa bits in case of negative numbers.
1227        // We effectively convert the numbers to "two's complement" form.
1228        //
1229        // To do the flipping, we construct a mask and XOR against it.
1230        // We branchlessly calculate an "all-ones except for the sign bit"
1231        // mask from negative-signed values: right shifting sign-extends
1232        // the integer, so we "fill" the mask with sign bits, and then
1233        // convert to unsigned to push one more zero bit.
1234        // On positive values, the mask is all zeros, so it's a no-op.
1235        left ^= (((left >> 127) as u128) >> 1) as i128;
1236        right ^= (((right >> 127) as u128) >> 1) as i128;
1237
1238        left.cmp(&right)
1239    }
1240
1241    /// Restrict a value to a certain interval unless it is NaN.
1242    ///
1243    /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1244    /// less than `min`. Otherwise this returns `self`.
1245    ///
1246    /// Note that this function returns NaN if the initial value was NaN as
1247    /// well. If the result is zero and among the three inputs `self`, `min`, and `max` there are
1248    /// zeros with different sign, either `0.0` or `-0.0` is returned non-deterministically.
1249    ///
1250    /// # Panics
1251    ///
1252    /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1253    ///
1254    /// # Examples
1255    ///
1256    /// ```
1257    /// #![feature(f128)]
1258    /// # // FIXME(f16_f128): remove when `{eq,gt,unord}tf` are available
1259    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1260    ///
1261    /// assert!((-3.0f128).clamp(-2.0, 1.0) == -2.0);
1262    /// assert!((0.0f128).clamp(-2.0, 1.0) == 0.0);
1263    /// assert!((2.0f128).clamp(-2.0, 1.0) == 1.0);
1264    /// assert!((f128::NAN).clamp(-2.0, 1.0).is_nan());
1265    ///
1266    /// // These always returns zero, but the sign (which is ignored by `==`) is non-deterministic.
1267    /// assert!((0.0f128).clamp(-0.0, -0.0) == 0.0);
1268    /// assert!((1.0f128).clamp(-0.0, 0.0) == 0.0);
1269    /// // This is definitely a negative zero.
1270    /// assert!((-1.0f128).clamp(-0.0, 1.0).is_sign_negative());
1271    /// # }
1272    /// ```
1273    #[inline]
1274    #[unstable(feature = "f128", issue = "116909")]
1275    #[must_use = "method returns a new number and does not mutate the original value"]
1276    pub const fn clamp(mut self, min: f128, max: f128) -> f128 {
1277        const_assert!(
1278            min <= max,
1279            "min > max, or either was NaN",
1280            "min > max, or either was NaN. min = {min:?}, max = {max:?}",
1281            min: f128,
1282            max: f128,
1283        );
1284
1285        if self < min {
1286            self = min;
1287        }
1288        if self > max {
1289            self = max;
1290        }
1291        self
1292    }
1293
1294    /// Clamps this number to a symmetric range centered around zero.
1295    ///
1296    /// The method clamps the number's magnitude (absolute value) to be at most `limit`.
1297    ///
1298    /// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more
1299    /// explicit about the intent.
1300    ///
1301    /// # Panics
1302    ///
1303    /// Panics if `limit` is negative or NaN, as this indicates a logic error.
1304    ///
1305    /// # Examples
1306    ///
1307    /// ```
1308    /// #![feature(f128)]
1309    /// #![feature(clamp_magnitude)]
1310    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1311    /// assert_eq!(5.0f128.clamp_magnitude(3.0), 3.0);
1312    /// assert_eq!((-5.0f128).clamp_magnitude(3.0), -3.0);
1313    /// assert_eq!(2.0f128.clamp_magnitude(3.0), 2.0);
1314    /// assert_eq!((-2.0f128).clamp_magnitude(3.0), -2.0);
1315    /// # }
1316    /// ```
1317    #[inline]
1318    #[unstable(feature = "clamp_magnitude", issue = "148519")]
1319    #[must_use = "this returns the clamped value and does not modify the original"]
1320    pub fn clamp_magnitude(self, limit: f128) -> f128 {
1321        assert!(limit >= 0.0, "limit must be non-negative");
1322        let limit = limit.abs(); // Canonicalises -0.0 to 0.0
1323        self.clamp(-limit, limit)
1324    }
1325
1326    /// Computes the absolute value of `self`.
1327    ///
1328    /// This function always returns the precise result.
1329    ///
1330    /// # Examples
1331    ///
1332    /// ```
1333    /// #![feature(f128)]
1334    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1335    ///
1336    /// let x = 3.5_f128;
1337    /// let y = -3.5_f128;
1338    ///
1339    /// assert_eq!(x.abs(), x);
1340    /// assert_eq!(y.abs(), -y);
1341    ///
1342    /// assert!(f128::NAN.abs().is_nan());
1343    /// # }
1344    /// ```
1345    #[inline]
1346    #[unstable(feature = "f128", issue = "116909")]
1347    #[rustc_const_unstable(feature = "f128", issue = "116909")]
1348    #[must_use = "method returns a new number and does not mutate the original value"]
1349    pub const fn abs(self) -> Self {
1350        // FIXME(f16_f128): replace with `intrinsics::fabsf128` when available
1351        // We don't do this now because LLVM has lowering bugs for f128 math.
1352        Self::from_bits(self.to_bits() & !(1 << 127))
1353    }
1354
1355    /// Returns a number that represents the sign of `self`.
1356    ///
1357    /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
1358    /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
1359    /// - NaN if the number is NaN
1360    ///
1361    /// # Examples
1362    ///
1363    /// ```
1364    /// #![feature(f128)]
1365    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1366    ///
1367    /// let f = 3.5_f128;
1368    ///
1369    /// assert_eq!(f.signum(), 1.0);
1370    /// assert_eq!(f128::NEG_INFINITY.signum(), -1.0);
1371    ///
1372    /// assert!(f128::NAN.signum().is_nan());
1373    /// # }
1374    /// ```
1375    #[inline]
1376    #[unstable(feature = "f128", issue = "116909")]
1377    #[rustc_const_unstable(feature = "f128", issue = "116909")]
1378    #[must_use = "method returns a new number and does not mutate the original value"]
1379    pub const fn signum(self) -> f128 {
1380        if self.is_nan() { Self::NAN } else { 1.0_f128.copysign(self) }
1381    }
1382
1383    /// Returns a number composed of the magnitude of `self` and the sign of
1384    /// `sign`.
1385    ///
1386    /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`.
1387    /// If `self` is a NaN, then a NaN with the same payload as `self` and the sign bit of `sign` is
1388    /// returned.
1389    ///
1390    /// If `sign` is a NaN, then this operation will still carry over its sign into the result. Note
1391    /// that IEEE 754 doesn't assign any meaning to the sign bit in case of a NaN, and as Rust
1392    /// doesn't guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the
1393    /// result of `copysign` with `sign` being a NaN might produce an unexpected or non-portable
1394    /// result. See the [specification of NaN bit patterns](primitive@f32#nan-bit-patterns) for more
1395    /// info.
1396    ///
1397    /// # Examples
1398    ///
1399    /// ```
1400    /// #![feature(f128)]
1401    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1402    ///
1403    /// let f = 3.5_f128;
1404    ///
1405    /// assert_eq!(f.copysign(0.42), 3.5_f128);
1406    /// assert_eq!(f.copysign(-0.42), -3.5_f128);
1407    /// assert_eq!((-f).copysign(0.42), 3.5_f128);
1408    /// assert_eq!((-f).copysign(-0.42), -3.5_f128);
1409    ///
1410    /// assert!(f128::NAN.copysign(1.0).is_nan());
1411    /// # }
1412    /// ```
1413    #[inline]
1414    #[unstable(feature = "f128", issue = "116909")]
1415    #[rustc_const_unstable(feature = "f128", issue = "116909")]
1416    #[must_use = "method returns a new number and does not mutate the original value"]
1417    pub const fn copysign(self, sign: f128) -> f128 {
1418        intrinsics::copysignf128(self, sign)
1419    }
1420
1421    /// Float addition that allows optimizations based on algebraic rules.
1422    ///
1423    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1424    #[must_use = "method returns a new number and does not mutate the original value"]
1425    #[unstable(feature = "float_algebraic", issue = "136469")]
1426    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1427    #[inline]
1428    pub const fn algebraic_add(self, rhs: f128) -> f128 {
1429        intrinsics::fadd_algebraic(self, rhs)
1430    }
1431
1432    /// Float subtraction that allows optimizations based on algebraic rules.
1433    ///
1434    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1435    #[must_use = "method returns a new number and does not mutate the original value"]
1436    #[unstable(feature = "float_algebraic", issue = "136469")]
1437    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1438    #[inline]
1439    pub const fn algebraic_sub(self, rhs: f128) -> f128 {
1440        intrinsics::fsub_algebraic(self, rhs)
1441    }
1442
1443    /// Float multiplication that allows optimizations based on algebraic rules.
1444    ///
1445    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1446    #[must_use = "method returns a new number and does not mutate the original value"]
1447    #[unstable(feature = "float_algebraic", issue = "136469")]
1448    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1449    #[inline]
1450    pub const fn algebraic_mul(self, rhs: f128) -> f128 {
1451        intrinsics::fmul_algebraic(self, rhs)
1452    }
1453
1454    /// Float division that allows optimizations based on algebraic rules.
1455    ///
1456    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1457    #[must_use = "method returns a new number and does not mutate the original value"]
1458    #[unstable(feature = "float_algebraic", issue = "136469")]
1459    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1460    #[inline]
1461    pub const fn algebraic_div(self, rhs: f128) -> f128 {
1462        intrinsics::fdiv_algebraic(self, rhs)
1463    }
1464
1465    /// Float remainder that allows optimizations based on algebraic rules.
1466    ///
1467    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1468    #[must_use = "method returns a new number and does not mutate the original value"]
1469    #[unstable(feature = "float_algebraic", issue = "136469")]
1470    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1471    #[inline]
1472    pub const fn algebraic_rem(self, rhs: f128) -> f128 {
1473        intrinsics::frem_algebraic(self, rhs)
1474    }
1475}
1476
1477// Functions in this module fall into `core_float_math`
1478// FIXME(f16_f128): all doctests must be gated to platforms that have `long double` === `_Float128`
1479// due to https://github.com/llvm/llvm-project/issues/44744. aarch64 linux matches this.
1480// #[unstable(feature = "core_float_math", issue = "137578")]
1481#[cfg(not(test))]
1482#[doc(test(attr(feature(cfg_target_has_reliable_f16_f128), expect(internal_features))))]
1483impl f128 {
1484    /// Returns the largest integer less than or equal to `self`.
1485    ///
1486    /// This function always returns the precise result.
1487    ///
1488    /// # Examples
1489    ///
1490    /// ```
1491    /// #![feature(f128)]
1492    /// # #[cfg(not(miri))]
1493    /// # #[cfg(target_has_reliable_f128_math)] {
1494    ///
1495    /// let f = 3.7_f128;
1496    /// let g = 3.0_f128;
1497    /// let h = -3.7_f128;
1498    ///
1499    /// assert_eq!(f.floor(), 3.0);
1500    /// assert_eq!(g.floor(), 3.0);
1501    /// assert_eq!(h.floor(), -4.0);
1502    /// # }
1503    /// ```
1504    #[inline]
1505    #[rustc_allow_incoherent_impl]
1506    #[unstable(feature = "f128", issue = "116909")]
1507    #[rustc_const_unstable(feature = "f128", issue = "116909")]
1508    #[must_use = "method returns a new number and does not mutate the original value"]
1509    pub const fn floor(self) -> f128 {
1510        intrinsics::floorf128(self)
1511    }
1512
1513    /// Returns the smallest integer greater than or equal to `self`.
1514    ///
1515    /// This function always returns the precise result.
1516    ///
1517    /// # Examples
1518    ///
1519    /// ```
1520    /// #![feature(f128)]
1521    /// # #[cfg(not(miri))]
1522    /// # #[cfg(target_has_reliable_f128_math)] {
1523    ///
1524    /// let f = 3.01_f128;
1525    /// let g = 4.0_f128;
1526    ///
1527    /// assert_eq!(f.ceil(), 4.0);
1528    /// assert_eq!(g.ceil(), 4.0);
1529    /// # }
1530    /// ```
1531    #[inline]
1532    #[doc(alias = "ceiling")]
1533    #[rustc_allow_incoherent_impl]
1534    #[unstable(feature = "f128", issue = "116909")]
1535    #[rustc_const_unstable(feature = "f128", issue = "116909")]
1536    #[must_use = "method returns a new number and does not mutate the original value"]
1537    pub const fn ceil(self) -> f128 {
1538        intrinsics::ceilf128(self)
1539    }
1540
1541    /// Returns the nearest integer to `self`. If a value is half-way between two
1542    /// integers, round away from `0.0`.
1543    ///
1544    /// This function always returns the precise result.
1545    ///
1546    /// # Examples
1547    ///
1548    /// ```
1549    /// #![feature(f128)]
1550    /// # #[cfg(not(miri))]
1551    /// # #[cfg(target_has_reliable_f128_math)] {
1552    ///
1553    /// let f = 3.3_f128;
1554    /// let g = -3.3_f128;
1555    /// let h = -3.7_f128;
1556    /// let i = 3.5_f128;
1557    /// let j = 4.5_f128;
1558    ///
1559    /// assert_eq!(f.round(), 3.0);
1560    /// assert_eq!(g.round(), -3.0);
1561    /// assert_eq!(h.round(), -4.0);
1562    /// assert_eq!(i.round(), 4.0);
1563    /// assert_eq!(j.round(), 5.0);
1564    /// # }
1565    /// ```
1566    #[inline]
1567    #[rustc_allow_incoherent_impl]
1568    #[unstable(feature = "f128", issue = "116909")]
1569    #[rustc_const_unstable(feature = "f128", issue = "116909")]
1570    #[must_use = "method returns a new number and does not mutate the original value"]
1571    pub const fn round(self) -> f128 {
1572        intrinsics::roundf128(self)
1573    }
1574
1575    /// Returns the nearest integer to a number. Rounds half-way cases to the number
1576    /// with an even least significant digit.
1577    ///
1578    /// This function always returns the precise result.
1579    ///
1580    /// # Examples
1581    ///
1582    /// ```
1583    /// #![feature(f128)]
1584    /// # #[cfg(not(miri))]
1585    /// # #[cfg(target_has_reliable_f128_math)] {
1586    ///
1587    /// let f = 3.3_f128;
1588    /// let g = -3.3_f128;
1589    /// let h = 3.5_f128;
1590    /// let i = 4.5_f128;
1591    ///
1592    /// assert_eq!(f.round_ties_even(), 3.0);
1593    /// assert_eq!(g.round_ties_even(), -3.0);
1594    /// assert_eq!(h.round_ties_even(), 4.0);
1595    /// assert_eq!(i.round_ties_even(), 4.0);
1596    /// # }
1597    /// ```
1598    #[inline]
1599    #[rustc_allow_incoherent_impl]
1600    #[unstable(feature = "f128", issue = "116909")]
1601    #[rustc_const_unstable(feature = "f128", issue = "116909")]
1602    #[must_use = "method returns a new number and does not mutate the original value"]
1603    pub const fn round_ties_even(self) -> f128 {
1604        intrinsics::round_ties_even_f128(self)
1605    }
1606
1607    /// Returns the integer part of `self`.
1608    /// This means that non-integer numbers are always truncated towards zero.
1609    ///
1610    /// This function always returns the precise result.
1611    ///
1612    /// # Examples
1613    ///
1614    /// ```
1615    /// #![feature(f128)]
1616    /// # #[cfg(not(miri))]
1617    /// # #[cfg(target_has_reliable_f128_math)] {
1618    ///
1619    /// let f = 3.7_f128;
1620    /// let g = 3.0_f128;
1621    /// let h = -3.7_f128;
1622    ///
1623    /// assert_eq!(f.trunc(), 3.0);
1624    /// assert_eq!(g.trunc(), 3.0);
1625    /// assert_eq!(h.trunc(), -3.0);
1626    /// # }
1627    /// ```
1628    #[inline]
1629    #[doc(alias = "truncate")]
1630    #[rustc_allow_incoherent_impl]
1631    #[unstable(feature = "f128", issue = "116909")]
1632    #[rustc_const_unstable(feature = "f128", issue = "116909")]
1633    #[must_use = "method returns a new number and does not mutate the original value"]
1634    pub const fn trunc(self) -> f128 {
1635        intrinsics::truncf128(self)
1636    }
1637
1638    /// Returns the fractional part of `self`.
1639    ///
1640    /// This function always returns the precise result.
1641    ///
1642    /// # Examples
1643    ///
1644    /// ```
1645    /// #![feature(f128)]
1646    /// # #[cfg(not(miri))]
1647    /// # #[cfg(target_has_reliable_f128_math)] {
1648    ///
1649    /// let x = 3.6_f128;
1650    /// let y = -3.6_f128;
1651    /// let abs_difference_x = (x.fract() - 0.6).abs();
1652    /// let abs_difference_y = (y.fract() - (-0.6)).abs();
1653    ///
1654    /// assert!(abs_difference_x <= f128::EPSILON);
1655    /// assert!(abs_difference_y <= f128::EPSILON);
1656    /// # }
1657    /// ```
1658    #[inline]
1659    #[rustc_allow_incoherent_impl]
1660    #[unstable(feature = "f128", issue = "116909")]
1661    #[rustc_const_unstable(feature = "f128", issue = "116909")]
1662    #[must_use = "method returns a new number and does not mutate the original value"]
1663    pub const fn fract(self) -> f128 {
1664        self - self.trunc()
1665    }
1666
1667    /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
1668    /// error, yielding a more accurate result than an unfused multiply-add.
1669    ///
1670    /// Using `mul_add` *may* be more performant than an unfused multiply-add if
1671    /// the target architecture has a dedicated `fma` CPU instruction. However,
1672    /// this is not always true, and will be heavily dependant on designing
1673    /// algorithms with specific target hardware in mind.
1674    ///
1675    /// # Precision
1676    ///
1677    /// The result of this operation is guaranteed to be the rounded
1678    /// infinite-precision result. It is specified by IEEE 754 as
1679    /// `fusedMultiplyAdd` and guaranteed not to change.
1680    ///
1681    /// # Examples
1682    ///
1683    /// ```
1684    /// #![feature(f128)]
1685    /// # #[cfg(not(miri))]
1686    /// # #[cfg(target_has_reliable_f128_math)] {
1687    ///
1688    /// let m = 10.0_f128;
1689    /// let x = 4.0_f128;
1690    /// let b = 60.0_f128;
1691    ///
1692    /// assert_eq!(m.mul_add(x, b), 100.0);
1693    /// assert_eq!(m * x + b, 100.0);
1694    ///
1695    /// let one_plus_eps = 1.0_f128 + f128::EPSILON;
1696    /// let one_minus_eps = 1.0_f128 - f128::EPSILON;
1697    /// let minus_one = -1.0_f128;
1698    ///
1699    /// // The exact result (1 + eps) * (1 - eps) = 1 - eps * eps.
1700    /// assert_eq!(one_plus_eps.mul_add(one_minus_eps, minus_one), -f128::EPSILON * f128::EPSILON);
1701    /// // Different rounding with the non-fused multiply and add.
1702    /// assert_eq!(one_plus_eps * one_minus_eps + minus_one, 0.0);
1703    /// # }
1704    /// ```
1705    #[inline]
1706    #[rustc_allow_incoherent_impl]
1707    #[doc(alias = "fmaf128", alias = "fusedMultiplyAdd")]
1708    #[unstable(feature = "f128", issue = "116909")]
1709    #[must_use = "method returns a new number and does not mutate the original value"]
1710    #[rustc_const_unstable(feature = "const_mul_add", issue = "146724")]
1711    pub const fn mul_add(self, a: f128, b: f128) -> f128 {
1712        intrinsics::fmaf128(self, a, b)
1713    }
1714
1715    /// Calculates Euclidean division, the matching method for `rem_euclid`.
1716    ///
1717    /// This computes the integer `n` such that
1718    /// `self = n * rhs + self.rem_euclid(rhs)`.
1719    /// In other words, the result is `self / rhs` rounded to the integer `n`
1720    /// such that `self >= n * rhs`.
1721    ///
1722    /// # Precision
1723    ///
1724    /// The result of this operation is guaranteed to be the rounded
1725    /// infinite-precision result.
1726    ///
1727    /// # Examples
1728    ///
1729    /// ```
1730    /// #![feature(f128)]
1731    /// # #[cfg(not(miri))]
1732    /// # #[cfg(target_has_reliable_f128_math)] {
1733    ///
1734    /// let a: f128 = 7.0;
1735    /// let b = 4.0;
1736    /// assert_eq!(a.div_euclid(b), 1.0); // 7.0 > 4.0 * 1.0
1737    /// assert_eq!((-a).div_euclid(b), -2.0); // -7.0 >= 4.0 * -2.0
1738    /// assert_eq!(a.div_euclid(-b), -1.0); // 7.0 >= -4.0 * -1.0
1739    /// assert_eq!((-a).div_euclid(-b), 2.0); // -7.0 >= -4.0 * 2.0
1740    /// # }
1741    /// ```
1742    #[inline]
1743    #[rustc_allow_incoherent_impl]
1744    #[unstable(feature = "f128", issue = "116909")]
1745    #[must_use = "method returns a new number and does not mutate the original value"]
1746    pub fn div_euclid(self, rhs: f128) -> f128 {
1747        let q = (self / rhs).trunc();
1748        if self % rhs < 0.0 {
1749            return if rhs > 0.0 { q - 1.0 } else { q + 1.0 };
1750        }
1751        q
1752    }
1753
1754    /// Calculates the least nonnegative remainder of `self (mod rhs)`.
1755    ///
1756    /// In particular, the return value `r` satisfies `0.0 <= r < rhs.abs()` in
1757    /// most cases. However, due to a floating point round-off error it can
1758    /// result in `r == rhs.abs()`, violating the mathematical definition, if
1759    /// `self` is much smaller than `rhs.abs()` in magnitude and `self < 0.0`.
1760    /// This result is not an element of the function's codomain, but it is the
1761    /// closest floating point number in the real numbers and thus fulfills the
1762    /// property `self == self.div_euclid(rhs) * rhs + self.rem_euclid(rhs)`
1763    /// approximately.
1764    ///
1765    /// # Precision
1766    ///
1767    /// The result of this operation is guaranteed to be the rounded
1768    /// infinite-precision result.
1769    ///
1770    /// # Examples
1771    ///
1772    /// ```
1773    /// #![feature(f128)]
1774    /// # #[cfg(not(miri))]
1775    /// # #[cfg(target_has_reliable_f128_math)] {
1776    ///
1777    /// let a: f128 = 7.0;
1778    /// let b = 4.0;
1779    /// assert_eq!(a.rem_euclid(b), 3.0);
1780    /// assert_eq!((-a).rem_euclid(b), 1.0);
1781    /// assert_eq!(a.rem_euclid(-b), 3.0);
1782    /// assert_eq!((-a).rem_euclid(-b), 1.0);
1783    /// // limitation due to round-off error
1784    /// assert!((-f128::EPSILON).rem_euclid(3.0) != 0.0);
1785    /// # }
1786    /// ```
1787    #[inline]
1788    #[rustc_allow_incoherent_impl]
1789    #[doc(alias = "modulo", alias = "mod")]
1790    #[unstable(feature = "f128", issue = "116909")]
1791    #[must_use = "method returns a new number and does not mutate the original value"]
1792    pub fn rem_euclid(self, rhs: f128) -> f128 {
1793        let r = self % rhs;
1794        if r < 0.0 { r + rhs.abs() } else { r }
1795    }
1796
1797    /// Raises a number to an integer power.
1798    ///
1799    /// Using this function is generally faster than using `powf`.
1800    /// It might have a different sequence of rounding operations than `powf`,
1801    /// so the results are not guaranteed to agree.
1802    ///
1803    /// Note that this function is special in that it can return non-NaN results for NaN inputs. For
1804    /// example, `f128::powi(f128::NAN, 0)` returns `1.0`. However, if an input is a *signaling*
1805    /// NaN, then the result is non-deterministically either a NaN or the result that the
1806    /// corresponding quiet NaN would produce.
1807    ///
1808    /// # Unspecified precision
1809    ///
1810    /// The precision of this function is non-deterministic. This means it varies by platform,
1811    /// Rust version, and can even differ within the same execution from one invocation to the next.
1812    ///
1813    /// # Examples
1814    ///
1815    /// ```
1816    /// #![feature(f128)]
1817    /// # #[cfg(not(miri))]
1818    /// # #[cfg(target_has_reliable_f128_math)] {
1819    ///
1820    /// let x = 2.0_f128;
1821    /// let abs_difference = (x.powi(2) - (x * x)).abs();
1822    /// assert!(abs_difference <= f128::EPSILON);
1823    ///
1824    /// assert_eq!(f128::powi(f128::NAN, 0), 1.0);
1825    /// assert_eq!(f128::powi(0.0, 0), 1.0);
1826    /// # }
1827    /// ```
1828    #[inline]
1829    #[rustc_allow_incoherent_impl]
1830    #[unstable(feature = "f128", issue = "116909")]
1831    #[must_use = "method returns a new number and does not mutate the original value"]
1832    pub fn powi(self, n: i32) -> f128 {
1833        intrinsics::powif128(self, n)
1834    }
1835
1836    /// Returns the square root of a number.
1837    ///
1838    /// Returns NaN if `self` is a negative number other than `-0.0`.
1839    ///
1840    /// # Precision
1841    ///
1842    /// The result of this operation is guaranteed to be the rounded
1843    /// infinite-precision result. It is specified by IEEE 754 as `squareRoot`
1844    /// and guaranteed not to change.
1845    ///
1846    /// # Examples
1847    ///
1848    /// ```
1849    /// #![feature(f128)]
1850    /// # #[cfg(not(miri))]
1851    /// # #[cfg(target_has_reliable_f128_math)] {
1852    ///
1853    /// let positive = 4.0_f128;
1854    /// let negative = -4.0_f128;
1855    /// let negative_zero = -0.0_f128;
1856    ///
1857    /// assert_eq!(positive.sqrt(), 2.0);
1858    /// assert!(negative.sqrt().is_nan());
1859    /// assert!(negative_zero.sqrt() == negative_zero);
1860    /// # }
1861    /// ```
1862    #[inline]
1863    #[doc(alias = "squareRoot")]
1864    #[rustc_allow_incoherent_impl]
1865    #[unstable(feature = "f128", issue = "116909")]
1866    #[must_use = "method returns a new number and does not mutate the original value"]
1867    pub fn sqrt(self) -> f128 {
1868        intrinsics::sqrtf128(self)
1869    }
1870}