Skip to main content

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