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    #[ferrocene::prevalidated]
906    #[inline]
907    #[unstable(feature = "f128", issue = "116909")]
908    #[must_use = "this returns the result of the operation, without modifying the original"]
909    #[allow(unnecessary_transmutes)]
910    pub const fn to_bits(self) -> u128 {
911        // SAFETY: `u128` is a plain old datatype so we can always transmute to it.
912        unsafe { mem::transmute(self) }
913    }
914
915    /// Raw transmutation from `u128`.
916    ///
917    /// This is currently identical to `transmute::<u128, f128>(v)` on all platforms.
918    /// It turns out this is incredibly portable, for two reasons:
919    ///
920    /// * Floats and Ints have the same endianness on all supported platforms.
921    /// * IEEE 754 very precisely specifies the bit layout of floats.
922    ///
923    /// However there is one caveat: prior to the 2008 version of IEEE 754, how
924    /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
925    /// (notably x86 and ARM) picked the interpretation that was ultimately
926    /// standardized in 2008, but some didn't (notably MIPS). As a result, all
927    /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
928    ///
929    /// Rather than trying to preserve signaling-ness cross-platform, this
930    /// implementation favors preserving the exact bits. This means that
931    /// any payloads encoded in NaNs will be preserved even if the result of
932    /// this method is sent over the network from an x86 machine to a MIPS one.
933    ///
934    /// If the results of this method are only manipulated by the same
935    /// architecture that produced them, then there is no portability concern.
936    ///
937    /// If the input isn't NaN, then there is no portability concern.
938    ///
939    /// If you don't care about signalingness (very likely), then there is no
940    /// portability concern.
941    ///
942    /// Note that this function is distinct from `as` casting, which attempts to
943    /// preserve the *numeric* value, and not the bitwise value.
944    ///
945    /// ```
946    /// #![feature(f128)]
947    /// # #[cfg(target_has_reliable_f128)] {
948    ///
949    /// let v = f128::from_bits(0x40029000000000000000000000000000);
950    /// assert_eq!(v, 12.5);
951    /// # }
952    /// ```
953    #[inline]
954    #[must_use]
955    #[unstable(feature = "f128", issue = "116909")]
956    #[allow(unnecessary_transmutes)]
957    pub const fn from_bits(v: u128) -> Self {
958        // It turns out the safety issues with sNaN were overblown! Hooray!
959        // SAFETY: `u128` is a plain old datatype so we can always transmute from it.
960        unsafe { mem::transmute(v) }
961    }
962
963    /// Returns the memory representation of this floating point number as a byte array in
964    /// big-endian (network) byte order.
965    ///
966    /// See [`from_bits`](Self::from_bits) for some discussion of the
967    /// portability of this operation (there are almost no issues).
968    ///
969    /// # Examples
970    ///
971    /// ```
972    /// #![feature(f128)]
973    ///
974    /// let bytes = 12.5f128.to_be_bytes();
975    /// assert_eq!(
976    ///     bytes,
977    ///     [0x40, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,
978    ///      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
979    /// );
980    /// ```
981    #[inline]
982    #[unstable(feature = "f128", issue = "116909")]
983    #[must_use = "this returns the result of the operation, without modifying the original"]
984    pub const fn to_be_bytes(self) -> [u8; 16] {
985        self.to_bits().to_be_bytes()
986    }
987
988    /// Returns the memory representation of this floating point number as a byte array in
989    /// little-endian byte order.
990    ///
991    /// See [`from_bits`](Self::from_bits) for some discussion of the
992    /// portability of this operation (there are almost no issues).
993    ///
994    /// # Examples
995    ///
996    /// ```
997    /// #![feature(f128)]
998    ///
999    /// let bytes = 12.5f128.to_le_bytes();
1000    /// assert_eq!(
1001    ///     bytes,
1002    ///     [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1003    ///      0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x02, 0x40]
1004    /// );
1005    /// ```
1006    #[inline]
1007    #[unstable(feature = "f128", issue = "116909")]
1008    #[must_use = "this returns the result of the operation, without modifying the original"]
1009    pub const fn to_le_bytes(self) -> [u8; 16] {
1010        self.to_bits().to_le_bytes()
1011    }
1012
1013    /// Returns the memory representation of this floating point number as a byte array in
1014    /// native byte order.
1015    ///
1016    /// As the target platform's native endianness is used, portable code
1017    /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1018    ///
1019    /// [`to_be_bytes`]: f128::to_be_bytes
1020    /// [`to_le_bytes`]: f128::to_le_bytes
1021    ///
1022    /// See [`from_bits`](Self::from_bits) for some discussion of the
1023    /// portability of this operation (there are almost no issues).
1024    ///
1025    /// # Examples
1026    ///
1027    /// ```
1028    /// #![feature(f128)]
1029    ///
1030    /// let bytes = 12.5f128.to_ne_bytes();
1031    /// assert_eq!(
1032    ///     bytes,
1033    ///     if cfg!(target_endian = "big") {
1034    ///         [0x40, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,
1035    ///          0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1036    ///     } else {
1037    ///         [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1038    ///          0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x02, 0x40]
1039    ///     }
1040    /// );
1041    /// ```
1042    #[inline]
1043    #[unstable(feature = "f128", issue = "116909")]
1044    #[must_use = "this returns the result of the operation, without modifying the original"]
1045    pub const fn to_ne_bytes(self) -> [u8; 16] {
1046        self.to_bits().to_ne_bytes()
1047    }
1048
1049    /// Creates a floating point value from its representation as a byte array in big endian.
1050    ///
1051    /// See [`from_bits`](Self::from_bits) for some discussion of the
1052    /// portability of this operation (there are almost no issues).
1053    ///
1054    /// # Examples
1055    ///
1056    /// ```
1057    /// #![feature(f128)]
1058    /// # #[cfg(target_has_reliable_f128)] {
1059    ///
1060    /// let value = f128::from_be_bytes(
1061    ///     [0x40, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,
1062    ///      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1063    /// );
1064    /// assert_eq!(value, 12.5);
1065    /// # }
1066    /// ```
1067    #[inline]
1068    #[must_use]
1069    #[unstable(feature = "f128", issue = "116909")]
1070    pub const fn from_be_bytes(bytes: [u8; 16]) -> Self {
1071        Self::from_bits(u128::from_be_bytes(bytes))
1072    }
1073
1074    /// Creates a floating point value from its representation as a byte array in little endian.
1075    ///
1076    /// See [`from_bits`](Self::from_bits) for some discussion of the
1077    /// portability of this operation (there are almost no issues).
1078    ///
1079    /// # Examples
1080    ///
1081    /// ```
1082    /// #![feature(f128)]
1083    /// # #[cfg(target_has_reliable_f128)] {
1084    ///
1085    /// let value = f128::from_le_bytes(
1086    ///     [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1087    ///      0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x02, 0x40]
1088    /// );
1089    /// assert_eq!(value, 12.5);
1090    /// # }
1091    /// ```
1092    #[inline]
1093    #[must_use]
1094    #[unstable(feature = "f128", issue = "116909")]
1095    pub const fn from_le_bytes(bytes: [u8; 16]) -> Self {
1096        Self::from_bits(u128::from_le_bytes(bytes))
1097    }
1098
1099    /// Creates a floating point value from its representation as a byte array in native endian.
1100    ///
1101    /// As the target platform's native endianness is used, portable code
1102    /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1103    /// appropriate instead.
1104    ///
1105    /// [`from_be_bytes`]: f128::from_be_bytes
1106    /// [`from_le_bytes`]: f128::from_le_bytes
1107    ///
1108    /// See [`from_bits`](Self::from_bits) for some discussion of the
1109    /// portability of this operation (there are almost no issues).
1110    ///
1111    /// # Examples
1112    ///
1113    /// ```
1114    /// #![feature(f128)]
1115    /// # #[cfg(target_has_reliable_f128)] {
1116    ///
1117    /// let value = f128::from_ne_bytes(if cfg!(target_endian = "big") {
1118    ///     [0x40, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,
1119    ///      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1120    /// } else {
1121    ///     [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1122    ///      0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x02, 0x40]
1123    /// });
1124    /// assert_eq!(value, 12.5);
1125    /// # }
1126    /// ```
1127    #[inline]
1128    #[must_use]
1129    #[unstable(feature = "f128", issue = "116909")]
1130    pub const fn from_ne_bytes(bytes: [u8; 16]) -> Self {
1131        Self::from_bits(u128::from_ne_bytes(bytes))
1132    }
1133
1134    /// Returns the ordering between `self` and `other`.
1135    ///
1136    /// Unlike the standard partial comparison between floating point numbers,
1137    /// this comparison always produces an ordering in accordance to
1138    /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1139    /// floating point standard. The values are ordered in the following sequence:
1140    ///
1141    /// - negative quiet NaN
1142    /// - negative signaling NaN
1143    /// - negative infinity
1144    /// - negative numbers
1145    /// - negative subnormal numbers
1146    /// - negative zero
1147    /// - positive zero
1148    /// - positive subnormal numbers
1149    /// - positive numbers
1150    /// - positive infinity
1151    /// - positive signaling NaN
1152    /// - positive quiet NaN.
1153    ///
1154    /// The ordering established by this function does not always agree with the
1155    /// [`PartialOrd`] and [`PartialEq`] implementations of `f128`. For example,
1156    /// they consider negative and positive zero equal, while `total_cmp`
1157    /// doesn't.
1158    ///
1159    /// The interpretation of the signaling NaN bit follows the definition in
1160    /// the IEEE 754 standard, which may not match the interpretation by some of
1161    /// the older, non-conformant (e.g. MIPS) hardware implementations.
1162    ///
1163    /// # Example
1164    ///
1165    /// ```
1166    /// #![feature(f128)]
1167    ///
1168    /// struct GoodBoy {
1169    ///     name: &'static str,
1170    ///     weight: f128,
1171    /// }
1172    ///
1173    /// let mut bois = vec![
1174    ///     GoodBoy { name: "Pucci", weight: 0.1 },
1175    ///     GoodBoy { name: "Woofer", weight: 99.0 },
1176    ///     GoodBoy { name: "Yapper", weight: 10.0 },
1177    ///     GoodBoy { name: "Chonk", weight: f128::INFINITY },
1178    ///     GoodBoy { name: "Abs. Unit", weight: f128::NAN },
1179    ///     GoodBoy { name: "Floaty", weight: -5.0 },
1180    /// ];
1181    ///
1182    /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1183    ///
1184    /// // `f128::NAN` could be positive or negative, which will affect the sort order.
1185    /// if f128::NAN.is_sign_negative() {
1186    ///     bois.into_iter().map(|b| b.weight)
1187    ///         .zip([f128::NAN, -5.0, 0.1, 10.0, 99.0, f128::INFINITY].iter())
1188    ///         .for_each(|(a, b)| assert_eq!(a.to_bits(), b.to_bits()))
1189    /// } else {
1190    ///     bois.into_iter().map(|b| b.weight)
1191    ///         .zip([-5.0, 0.1, 10.0, 99.0, f128::INFINITY, f128::NAN].iter())
1192    ///         .for_each(|(a, b)| assert_eq!(a.to_bits(), b.to_bits()))
1193    /// }
1194    /// ```
1195    #[inline]
1196    #[must_use]
1197    #[unstable(feature = "f128", issue = "116909")]
1198    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1199    pub const fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1200        let mut left = self.to_bits() as i128;
1201        let mut right = other.to_bits() as i128;
1202
1203        // In case of negatives, flip all the bits except the sign
1204        // to achieve a similar layout as two's complement integers
1205        //
1206        // Why does this work? IEEE 754 floats consist of three fields:
1207        // Sign bit, exponent and mantissa. The set of exponent and mantissa
1208        // fields as a whole have the property that their bitwise order is
1209        // equal to the numeric magnitude where the magnitude is defined.
1210        // The magnitude is not normally defined on NaN values, but
1211        // IEEE 754 totalOrder defines the NaN values also to follow the
1212        // bitwise order. This leads to order explained in the doc comment.
1213        // However, the representation of magnitude is the same for negative
1214        // and positive numbers – only the sign bit is different.
1215        // To easily compare the floats as signed integers, we need to
1216        // flip the exponent and mantissa bits in case of negative numbers.
1217        // We effectively convert the numbers to "two's complement" form.
1218        //
1219        // To do the flipping, we construct a mask and XOR against it.
1220        // We branchlessly calculate an "all-ones except for the sign bit"
1221        // mask from negative-signed values: right shifting sign-extends
1222        // the integer, so we "fill" the mask with sign bits, and then
1223        // convert to unsigned to push one more zero bit.
1224        // On positive values, the mask is all zeros, so it's a no-op.
1225        left ^= (((left >> 127) as u128) >> 1) as i128;
1226        right ^= (((right >> 127) as u128) >> 1) as i128;
1227
1228        left.cmp(&right)
1229    }
1230
1231    /// Restrict a value to a certain interval unless it is NaN.
1232    ///
1233    /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1234    /// less than `min`. Otherwise this returns `self`.
1235    ///
1236    /// Note that this function returns NaN if the initial value was NaN as
1237    /// well. If the result is zero and among the three inputs `self`, `min`, and `max` there are
1238    /// zeros with different sign, either `0.0` or `-0.0` is returned non-deterministically.
1239    ///
1240    /// # Panics
1241    ///
1242    /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1243    ///
1244    /// # Examples
1245    ///
1246    /// ```
1247    /// #![feature(f128)]
1248    /// # #[cfg(target_has_reliable_f128_math)] {
1249    ///
1250    /// assert!((-3.0f128).clamp(-2.0, 1.0) == -2.0);
1251    /// assert!((0.0f128).clamp(-2.0, 1.0) == 0.0);
1252    /// assert!((2.0f128).clamp(-2.0, 1.0) == 1.0);
1253    /// assert!((f128::NAN).clamp(-2.0, 1.0).is_nan());
1254    ///
1255    /// // These always returns zero, but the sign (which is ignored by `==`) is non-deterministic.
1256    /// assert!((0.0f128).clamp(-0.0, -0.0) == 0.0);
1257    /// assert!((1.0f128).clamp(-0.0, 0.0) == 0.0);
1258    /// // This is definitely a negative zero.
1259    /// assert!((-1.0f128).clamp(-0.0, 1.0).is_sign_negative());
1260    /// # }
1261    /// ```
1262    #[inline]
1263    #[unstable(feature = "f128", issue = "116909")]
1264    #[must_use = "method returns a new number and does not mutate the original value"]
1265    #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "NaN is also invalid")]
1266    pub const fn clamp(mut self, min: f128, max: f128) -> f128 {
1267        const_assert!(
1268            min <= max,
1269            "min > max, or either was NaN",
1270            "min > max, or either was NaN. min = {min:?}, max = {max:?}",
1271            min: f128,
1272            max: f128,
1273        );
1274
1275        if self < min {
1276            self = min;
1277        }
1278        if self > max {
1279            self = max;
1280        }
1281        self
1282    }
1283
1284    /// Clamps this number to a symmetric range centered around zero.
1285    ///
1286    /// The method clamps the number's magnitude (absolute value) to be at most `limit`.
1287    ///
1288    /// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more
1289    /// explicit about the intent.
1290    ///
1291    /// # Panics
1292    ///
1293    /// Panics if `limit` is negative or NaN, as this indicates a logic error.
1294    ///
1295    /// # Examples
1296    ///
1297    /// ```
1298    /// #![feature(f128)]
1299    /// #![feature(clamp_magnitude)]
1300    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1301    /// assert_eq!(5.0f128.clamp_magnitude(3.0), 3.0);
1302    /// assert_eq!((-5.0f128).clamp_magnitude(3.0), -3.0);
1303    /// assert_eq!(2.0f128.clamp_magnitude(3.0), 2.0);
1304    /// assert_eq!((-2.0f128).clamp_magnitude(3.0), -2.0);
1305    /// # }
1306    /// ```
1307    #[inline]
1308    #[unstable(feature = "clamp_magnitude", issue = "148519")]
1309    #[rustc_const_unstable(feature = "clamp_magnitude", issue = "148519")]
1310    #[must_use = "method returns a new number and does not mutate the original value"]
1311    #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "NaN is also invalid")]
1312    pub const fn clamp_magnitude(self, limit: f128) -> f128 {
1313        assert!(limit >= 0.0, "limit must be non-negative and not NaN");
1314        let limit = limit.abs(); // Canonicalises -0.0 to 0.0
1315        self.clamp(-limit, limit)
1316    }
1317
1318    /// Restrict a value to a certain range, unless it is NaN.
1319    ///
1320    /// This is largely equal to `max`, `min`, or `clamp`, depending on whether the range is
1321    /// `min..`, `..=max`, or `min..=max`, respectively. However, unlike `max` and `min`, it will
1322    /// panic if any bound is NaN.
1323    ///
1324    /// Note that this function returns NaN if the initial value was NaN as
1325    /// well.
1326    ///
1327    /// Exclusive ranges are not permitted.
1328    ///
1329    /// # Panics
1330    ///
1331    /// Panics on `min..=max` if `min > max`, or if any bound is NaN.
1332    ///
1333    /// # Examples
1334    ///
1335    /// ```
1336    /// #![feature(f128, clamp_to)]
1337    /// # #[cfg(target_has_reliable_f128_math)] {
1338    /// assert_eq!((-3.0f128).clamp_to(-2.0..=1.0), -2.0);
1339    /// assert_eq!(0.0f128.clamp_to(-2.0..=1.0), 0.0);
1340    /// assert_eq!(2.0f128.clamp_to(..=1.0), 1.0);
1341    /// assert_eq!(5.0f128.clamp_to(7.0..), 7.0);
1342    /// assert!(f128::NAN.clamp_to(1.0..=2.0).is_nan());
1343    /// # }
1344    /// ```
1345    #[must_use]
1346    #[inline]
1347    #[unstable(feature = "clamp_to", issue = "147781")]
1348    pub fn clamp_to<R>(self, range: R) -> Self
1349    where
1350        R: crate::cmp::ClampBounds<Self>,
1351    {
1352        range.clamp(self)
1353    }
1354
1355    /// Computes the absolute value of `self`.
1356    ///
1357    /// This function always returns the precise result.
1358    ///
1359    /// # Examples
1360    ///
1361    /// ```
1362    /// #![feature(f128)]
1363    /// # #[cfg(target_has_reliable_f128)] {
1364    ///
1365    /// let x = 3.5_f128;
1366    /// let y = -3.5_f128;
1367    ///
1368    /// assert_eq!(x.abs(), x);
1369    /// assert_eq!(y.abs(), -y);
1370    ///
1371    /// assert!(f128::NAN.abs().is_nan());
1372    /// # }
1373    /// ```
1374    #[inline]
1375    #[unstable(feature = "f128", issue = "116909")]
1376    #[rustc_const_unstable(feature = "f128", issue = "116909")]
1377    #[must_use = "method returns a new number and does not mutate the original value"]
1378    pub const fn abs(self) -> Self {
1379        intrinsics::fabs(self)
1380    }
1381
1382    /// Returns a number that represents the sign of `self`.
1383    ///
1384    /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
1385    /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
1386    /// - NaN if the number is NaN
1387    ///
1388    /// # Examples
1389    ///
1390    /// ```
1391    /// #![feature(f128)]
1392    /// # #[cfg(target_has_reliable_f128)] {
1393    ///
1394    /// let f = 3.5_f128;
1395    ///
1396    /// assert_eq!(f.signum(), 1.0);
1397    /// assert_eq!(f128::NEG_INFINITY.signum(), -1.0);
1398    ///
1399    /// assert!(f128::NAN.signum().is_nan());
1400    /// # }
1401    /// ```
1402    #[inline]
1403    #[unstable(feature = "f128", issue = "116909")]
1404    #[rustc_const_unstable(feature = "f128", issue = "116909")]
1405    #[must_use = "method returns a new number and does not mutate the original value"]
1406    pub const fn signum(self) -> f128 {
1407        if self.is_nan() { Self::NAN } else { 1.0_f128.copysign(self) }
1408    }
1409
1410    /// Returns a number composed of the magnitude of `self` and the sign of
1411    /// `sign`.
1412    ///
1413    /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`.
1414    /// If `self` is a NaN, then a NaN with the same payload as `self` and the sign bit of `sign` is
1415    /// returned.
1416    ///
1417    /// If `sign` is a NaN, then this operation will still carry over its sign into the result. Note
1418    /// that IEEE 754 doesn't assign any meaning to the sign bit in case of a NaN, and as Rust
1419    /// doesn't guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the
1420    /// result of `copysign` with `sign` being a NaN might produce an unexpected or non-portable
1421    /// result. See the [specification of NaN bit patterns](primitive@f32#nan-bit-patterns) for more
1422    /// info.
1423    ///
1424    /// # Examples
1425    ///
1426    /// ```
1427    /// #![feature(f128)]
1428    /// # #[cfg(target_has_reliable_f128)] {
1429    ///
1430    /// let f = 3.5_f128;
1431    ///
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    /// assert_eq!((-f).copysign(-0.42), -3.5_f128);
1436    ///
1437    /// assert!(f128::NAN.copysign(1.0).is_nan());
1438    /// # }
1439    /// ```
1440    #[inline]
1441    #[unstable(feature = "f128", issue = "116909")]
1442    #[rustc_const_unstable(feature = "f128", issue = "116909")]
1443    #[must_use = "method returns a new number and does not mutate the original value"]
1444    pub const fn copysign(self, sign: f128) -> f128 {
1445        intrinsics::copysignf128(self, sign)
1446    }
1447
1448    /// Float addition that allows optimizations based on algebraic rules.
1449    ///
1450    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1451    #[must_use = "method returns a new number and does not mutate the original value"]
1452    #[unstable(feature = "f128", issue = "116909")]
1453    #[rustc_const_unstable(feature = "f128", issue = "116909")]
1454    #[inline]
1455    pub const fn algebraic_add(self, rhs: f128) -> f128 {
1456        intrinsics::fadd_algebraic(self, rhs)
1457    }
1458
1459    /// Float subtraction that allows optimizations based on algebraic rules.
1460    ///
1461    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1462    #[must_use = "method returns a new number and does not mutate the original value"]
1463    #[unstable(feature = "f128", issue = "116909")]
1464    #[rustc_const_unstable(feature = "f128", issue = "116909")]
1465    #[inline]
1466    pub const fn algebraic_sub(self, rhs: f128) -> f128 {
1467        intrinsics::fsub_algebraic(self, rhs)
1468    }
1469
1470    /// Float multiplication that allows optimizations based on algebraic rules.
1471    ///
1472    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1473    #[must_use = "method returns a new number and does not mutate the original value"]
1474    #[unstable(feature = "f128", issue = "116909")]
1475    #[rustc_const_unstable(feature = "f128", issue = "116909")]
1476    #[inline]
1477    pub const fn algebraic_mul(self, rhs: f128) -> f128 {
1478        intrinsics::fmul_algebraic(self, rhs)
1479    }
1480
1481    /// Float division that allows optimizations based on algebraic rules.
1482    ///
1483    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1484    #[must_use = "method returns a new number and does not mutate the original value"]
1485    #[unstable(feature = "f128", issue = "116909")]
1486    #[rustc_const_unstable(feature = "f128", issue = "116909")]
1487    #[inline]
1488    pub const fn algebraic_div(self, rhs: f128) -> f128 {
1489        intrinsics::fdiv_algebraic(self, rhs)
1490    }
1491
1492    /// Float remainder that allows optimizations based on algebraic rules.
1493    ///
1494    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1495    #[must_use = "method returns a new number and does not mutate the original value"]
1496    #[unstable(feature = "f128", issue = "116909")]
1497    #[rustc_const_unstable(feature = "f128", issue = "116909")]
1498    #[inline]
1499    pub const fn algebraic_rem(self, rhs: f128) -> f128 {
1500        intrinsics::frem_algebraic(self, rhs)
1501    }
1502
1503    /// Returns `self` if the value is not NaN, otherwise returns `replacement`
1504    /// if `self` is NaN.
1505    ///
1506    /// # Examples
1507    ///
1508    /// ```
1509    /// #![feature(f128)]
1510    /// #![feature(float_nan_to)]
1511    /// # #[cfg(target_has_reliable_f128)] {
1512    ///
1513    /// let n = f128::NAN;
1514    /// let x = 2.0f128;
1515    /// let y = f128::INFINITY;
1516    ///
1517    /// assert_eq!(n.nan_to(0.0f128), 0.0f128);
1518    /// assert_eq!(x.nan_to(0.0f128), 2.0f128);
1519    /// assert_eq!(y.nan_to(0.0f128), f128::INFINITY);
1520    /// # }
1521    /// ```
1522    #[must_use = "method returns a new float and does not mutate the original value"]
1523    #[unstable(feature = "float_nan_to", issue = "161248")]
1524    #[rustc_const_unstable(feature = "float_nan_to", issue = "161248")]
1525    #[inline]
1526    pub const fn nan_to(self, replacement: f128) -> f128 {
1527        if self.is_nan() { replacement } else { self }
1528    }
1529}
1530
1531// Functions in this module fall into `core_float_math`
1532// #[unstable(feature = "core_float_math", issue = "137578")]
1533#[cfg(not(test))]
1534#[doc(test(attr(
1535    feature(cfg_target_has_reliable_f16_f128),
1536    expect(internal_features),
1537    allow(unused_features)
1538)))]
1539impl f128 {
1540    /// Returns the largest integer less than or equal to `self`.
1541    ///
1542    /// This function always returns the precise result.
1543    ///
1544    /// # Examples
1545    ///
1546    /// ```
1547    /// #![feature(f128)]
1548    /// # #[cfg(any(miri, target_has_reliable_f128_math))] { // Miri uses softfloats, always works
1549    ///
1550    /// let f = 3.7_f128;
1551    /// let g = 3.0_f128;
1552    /// let h = -3.7_f128;
1553    ///
1554    /// assert_eq!(f.floor(), 3.0);
1555    /// assert_eq!(g.floor(), 3.0);
1556    /// assert_eq!(h.floor(), -4.0);
1557    /// # }
1558    /// ```
1559    #[inline]
1560    #[rustc_allow_incoherent_impl]
1561    #[unstable(feature = "f128", issue = "116909")]
1562    #[rustc_const_unstable(feature = "f128", issue = "116909")]
1563    #[must_use = "method returns a new number and does not mutate the original value"]
1564    pub const fn floor(self) -> f128 {
1565        intrinsics::floor(self)
1566    }
1567
1568    /// Returns the smallest integer greater than or equal to `self`.
1569    ///
1570    /// This function always returns the precise result.
1571    ///
1572    /// # Examples
1573    ///
1574    /// ```
1575    /// #![feature(f128)]
1576    /// # #[cfg(any(miri, target_has_reliable_f128_math))] { // Miri uses softfloats, always works
1577    ///
1578    /// let f = 3.01_f128;
1579    /// let g = 4.0_f128;
1580    ///
1581    /// assert_eq!(f.ceil(), 4.0);
1582    /// assert_eq!(g.ceil(), 4.0);
1583    /// # }
1584    /// ```
1585    #[inline]
1586    #[doc(alias = "ceiling")]
1587    #[rustc_allow_incoherent_impl]
1588    #[unstable(feature = "f128", issue = "116909")]
1589    #[rustc_const_unstable(feature = "f128", issue = "116909")]
1590    #[must_use = "method returns a new number and does not mutate the original value"]
1591    pub const fn ceil(self) -> f128 {
1592        intrinsics::ceil(self)
1593    }
1594
1595    /// Returns the nearest integer to `self`. If a value is half-way between two
1596    /// integers, round away from `0.0`.
1597    ///
1598    /// This function always returns the precise result.
1599    ///
1600    /// # Examples
1601    ///
1602    /// ```
1603    /// #![feature(f128)]
1604    /// # #[cfg(any(miri, target_has_reliable_f128_math))] { // Miri uses softfloats, always works
1605    ///
1606    /// let f = 3.3_f128;
1607    /// let g = -3.3_f128;
1608    /// let h = -3.7_f128;
1609    /// let i = 3.5_f128;
1610    /// let j = 4.5_f128;
1611    ///
1612    /// assert_eq!(f.round(), 3.0);
1613    /// assert_eq!(g.round(), -3.0);
1614    /// assert_eq!(h.round(), -4.0);
1615    /// assert_eq!(i.round(), 4.0);
1616    /// assert_eq!(j.round(), 5.0);
1617    /// # }
1618    /// ```
1619    #[inline]
1620    #[rustc_allow_incoherent_impl]
1621    #[unstable(feature = "f128", issue = "116909")]
1622    #[rustc_const_unstable(feature = "f128", issue = "116909")]
1623    #[must_use = "method returns a new number and does not mutate the original value"]
1624    pub const fn round(self) -> f128 {
1625        intrinsics::round(self)
1626    }
1627
1628    /// Returns the nearest integer to a number. Rounds half-way cases to the number
1629    /// with an even least significant digit.
1630    ///
1631    /// This function always returns the precise result.
1632    ///
1633    /// # Examples
1634    ///
1635    /// ```
1636    /// #![feature(f128)]
1637    /// # #[cfg(any(miri, target_has_reliable_f128_math))] { // Miri uses softfloats, always works
1638    ///
1639    /// let f = 3.3_f128;
1640    /// let g = -3.3_f128;
1641    /// let h = 3.5_f128;
1642    /// let i = 4.5_f128;
1643    ///
1644    /// assert_eq!(f.round_ties_even(), 3.0);
1645    /// assert_eq!(g.round_ties_even(), -3.0);
1646    /// assert_eq!(h.round_ties_even(), 4.0);
1647    /// assert_eq!(i.round_ties_even(), 4.0);
1648    /// # }
1649    /// ```
1650    #[inline]
1651    #[rustc_allow_incoherent_impl]
1652    #[unstable(feature = "f128", issue = "116909")]
1653    #[rustc_const_unstable(feature = "f128", issue = "116909")]
1654    #[must_use = "method returns a new number and does not mutate the original value"]
1655    pub const fn round_ties_even(self) -> f128 {
1656        intrinsics::round_ties_even(self)
1657    }
1658
1659    /// Returns the integer part of `self`.
1660    /// This means that non-integer numbers are always truncated towards zero.
1661    ///
1662    /// This function always returns the precise result.
1663    ///
1664    /// # Examples
1665    ///
1666    /// ```
1667    /// #![feature(f128)]
1668    /// # #[cfg(any(miri, target_has_reliable_f128_math))] { // Miri uses softfloats, always works
1669    ///
1670    /// let f = 3.7_f128;
1671    /// let g = 3.0_f128;
1672    /// let h = -3.7_f128;
1673    ///
1674    /// assert_eq!(f.trunc(), 3.0);
1675    /// assert_eq!(g.trunc(), 3.0);
1676    /// assert_eq!(h.trunc(), -3.0);
1677    /// # }
1678    /// ```
1679    #[inline]
1680    #[doc(alias = "truncate")]
1681    #[rustc_allow_incoherent_impl]
1682    #[unstable(feature = "f128", issue = "116909")]
1683    #[rustc_const_unstable(feature = "f128", issue = "116909")]
1684    #[must_use = "method returns a new number and does not mutate the original value"]
1685    pub const fn trunc(self) -> f128 {
1686        intrinsics::trunc(self)
1687    }
1688
1689    /// Returns the fractional part of `self`.
1690    ///
1691    /// This function always returns the precise result.
1692    ///
1693    /// # Examples
1694    ///
1695    /// ```
1696    /// #![feature(f128)]
1697    /// # #[cfg(any(miri, target_has_reliable_f128_math))] { // Miri uses softfloats, always works
1698    ///
1699    /// let x = 3.6_f128;
1700    /// let y = -3.6_f128;
1701    /// let abs_difference_x = (x.fract() - 0.6).abs();
1702    /// let abs_difference_y = (y.fract() - (-0.6)).abs();
1703    ///
1704    /// assert!(abs_difference_x <= f128::EPSILON);
1705    /// assert!(abs_difference_y <= f128::EPSILON);
1706    /// # }
1707    /// ```
1708    #[inline]
1709    #[rustc_allow_incoherent_impl]
1710    #[unstable(feature = "f128", issue = "116909")]
1711    #[rustc_const_unstable(feature = "f128", issue = "116909")]
1712    #[must_use = "method returns a new number and does not mutate the original value"]
1713    pub const fn fract(self) -> f128 {
1714        self - self.trunc()
1715    }
1716
1717    /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
1718    /// error, yielding a more accurate result than an unfused multiply-add.
1719    ///
1720    /// Using `mul_add` *may* be more performant than an unfused multiply-add if
1721    /// the target architecture has a dedicated `fma` CPU instruction. However,
1722    /// this is not always true, and will be heavily dependant on designing
1723    /// algorithms with specific target hardware in mind.
1724    ///
1725    /// # Precision
1726    ///
1727    /// The result of this operation is guaranteed to be the rounded
1728    /// infinite-precision result. It is specified by IEEE 754 as
1729    /// `fusedMultiplyAdd` and guaranteed not to change.
1730    ///
1731    /// # Examples
1732    ///
1733    /// ```
1734    /// #![feature(f128)]
1735    /// # #[cfg(any(miri, target_has_reliable_f128_math))] { // Miri uses softfloats, always works
1736    ///
1737    /// let m = 10.0_f128;
1738    /// let x = 4.0_f128;
1739    /// let b = 60.0_f128;
1740    ///
1741    /// assert_eq!(m.mul_add(x, b), 100.0);
1742    /// assert_eq!(m * x + b, 100.0);
1743    ///
1744    /// let one_plus_eps = 1.0_f128 + f128::EPSILON;
1745    /// let one_minus_eps = 1.0_f128 - f128::EPSILON;
1746    /// let minus_one = -1.0_f128;
1747    ///
1748    /// // The exact result (1 + eps) * (1 - eps) = 1 - eps * eps.
1749    /// assert_eq!(one_plus_eps.mul_add(one_minus_eps, minus_one), -f128::EPSILON * f128::EPSILON);
1750    /// // Different rounding with the non-fused multiply and add.
1751    /// assert_eq!(one_plus_eps * one_minus_eps + minus_one, 0.0);
1752    /// # }
1753    /// ```
1754    #[inline]
1755    #[rustc_allow_incoherent_impl]
1756    #[doc(alias = "fmaf128", alias = "fusedMultiplyAdd")]
1757    #[unstable(feature = "f128", issue = "116909")]
1758    #[must_use = "method returns a new number and does not mutate the original value"]
1759    pub const fn mul_add(self, a: f128, b: f128) -> f128 {
1760        intrinsics::fma(self, a, b)
1761    }
1762
1763    /// Computes `(self * a) + b` with nondeterministic rounding.
1764    ///
1765    /// This is similar to [`mul_add`](Self::mul_add), but the intermediate
1766    /// result may be rounded differently depending on the implementation.
1767    /// The operation is either executed as a single fused multiply-add
1768    /// instruction, or as separate multiply and add instructions.
1769    ///
1770    /// The choice of which one is used is unspecified and non-deterministic:
1771    /// it may vary by target, optimization level, and surrounding code, and
1772    /// even two invocations of this operation with the same inputs may
1773    /// produce different results.
1774    ///
1775    /// # Examples
1776    ///
1777    /// ```
1778    /// #![feature(f128)]
1779    /// #![feature(float_mul_add_relaxed)]
1780    /// # #[cfg(any(miri, target_has_reliable_f128_math))] { // Miri uses softfloats, always works
1781    ///
1782    /// // When the fused and unfused operations round differently, either
1783    /// // result may be returned:
1784    /// // - 7.824090399073145653039910391751267e-37 is the fused result (one rounding)
1785    /// // - 1.5046327690525280101999827676444745e-36 is the unfused result (two roundings)
1786    /// let r = 0.1_f128.mul_add_relaxed(0.1_f128, -0.01_f128);
1787    /// assert!(
1788    ///     r == 7.824090399073145653039910391751267e-37
1789    ///         || r == 1.5046327690525280101999827676444745e-36
1790    /// );
1791    /// # }
1792    /// ```
1793    #[inline]
1794    #[rustc_allow_incoherent_impl]
1795    #[doc(alias = "fmuladd")]
1796    #[unstable(feature = "float_mul_add_relaxed", issue = "151770")]
1797    #[must_use = "method returns a new number and does not mutate the original value"]
1798    pub const fn mul_add_relaxed(self, a: f128, b: f128) -> f128 {
1799        intrinsics::fmuladd(self, a, b)
1800    }
1801
1802    /// Calculates Euclidean division, the matching method for `rem_euclid`.
1803    ///
1804    /// This computes the integer `n` such that
1805    /// `self = n * rhs + self.rem_euclid(rhs)`.
1806    /// In other words, the result is `self / rhs` rounded to the integer `n`
1807    /// such that `self >= n * rhs`.
1808    ///
1809    /// # Precision
1810    ///
1811    /// The result of this operation is guaranteed to be the rounded
1812    /// infinite-precision result.
1813    ///
1814    /// # Examples
1815    ///
1816    /// ```
1817    /// #![feature(f128)]
1818    /// # #[cfg(any(miri, target_has_reliable_f128_math))] { // Miri uses softfloats, always works
1819    ///
1820    /// let a: f128 = 7.0;
1821    /// let b = 4.0;
1822    /// assert_eq!(a.div_euclid(b), 1.0); // 7.0 > 4.0 * 1.0
1823    /// assert_eq!((-a).div_euclid(b), -2.0); // -7.0 >= 4.0 * -2.0
1824    /// assert_eq!(a.div_euclid(-b), -1.0); // 7.0 >= -4.0 * -1.0
1825    /// assert_eq!((-a).div_euclid(-b), 2.0); // -7.0 >= -4.0 * 2.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 div_euclid(self, rhs: f128) -> f128 {
1833        let q = (self / rhs).trunc();
1834        if self % rhs < 0.0 {
1835            return if rhs > 0.0 { q - 1.0 } else { q + 1.0 };
1836        }
1837        q
1838    }
1839
1840    /// Calculates the least nonnegative remainder of `self` when
1841    /// divided by `rhs`.
1842    ///
1843    /// In particular, the return value `r` satisfies `0.0 <= r < rhs.abs()` in
1844    /// most cases. However, due to a floating point round-off error it can
1845    /// result in `r == rhs.abs()`, violating the mathematical definition, if
1846    /// `self` is much smaller than `rhs.abs()` in magnitude and `self < 0.0`.
1847    /// This result is not an element of the function's codomain, but it is the
1848    /// closest floating point number in the real numbers and thus fulfills the
1849    /// property `self == self.div_euclid(rhs) * rhs + self.rem_euclid(rhs)`
1850    /// approximately.
1851    ///
1852    /// # Precision
1853    ///
1854    /// The result of this operation is guaranteed to be the rounded
1855    /// infinite-precision result.
1856    ///
1857    /// # Examples
1858    ///
1859    /// ```
1860    /// #![feature(f128)]
1861    /// # #[cfg(any(miri, target_has_reliable_f128_math))] { // Miri uses softfloats, always works
1862    ///
1863    /// let a: f128 = 7.0;
1864    /// let b = 4.0;
1865    /// assert_eq!(a.rem_euclid(b), 3.0);
1866    /// assert_eq!((-a).rem_euclid(b), 1.0);
1867    /// assert_eq!(a.rem_euclid(-b), 3.0);
1868    /// assert_eq!((-a).rem_euclid(-b), 1.0);
1869    /// // limitation due to round-off error
1870    /// assert!((-f128::EPSILON).rem_euclid(3.0) != 0.0);
1871    /// # }
1872    /// ```
1873    #[inline]
1874    #[rustc_allow_incoherent_impl]
1875    #[doc(alias = "modulo", alias = "mod")]
1876    #[unstable(feature = "f128", issue = "116909")]
1877    #[must_use = "method returns a new number and does not mutate the original value"]
1878    pub fn rem_euclid(self, rhs: f128) -> f128 {
1879        let r = self % rhs;
1880        if r < 0.0 { r + rhs.abs() } else { r }
1881    }
1882
1883    /// Raises a number to an integer power.
1884    ///
1885    /// Using this function is generally faster than using `powf`.
1886    /// It might have a different sequence of rounding operations than `powf`,
1887    /// so the results are not guaranteed to agree.
1888    ///
1889    /// Note that this function is special in that it can return non-NaN results for NaN inputs. For
1890    /// example, `f128::powi(f128::NAN, 0)` returns `1.0`. However, if an input is a *signaling*
1891    /// NaN, then the result is non-deterministically either a NaN or the result that the
1892    /// corresponding quiet NaN would produce.
1893    ///
1894    /// # Unspecified precision
1895    ///
1896    /// The precision of this function is non-deterministic. This means it varies by platform,
1897    /// Rust version, and can even differ within the same execution from one invocation to the next.
1898    ///
1899    /// # Examples
1900    ///
1901    /// ```
1902    /// #![feature(f128)]
1903    /// # #[cfg(target_has_reliable_f128_math)] {
1904    ///
1905    /// let x = 2.0_f128;
1906    /// let abs_difference = (x.powi(2) - (x * x)).abs();
1907    /// assert!(abs_difference <= 1e-9);
1908    ///
1909    /// assert_eq!(f128::powi(f128::NAN, 0), 1.0);
1910    /// assert_eq!(f128::powi(0.0, 0), 1.0);
1911    /// # }
1912    /// ```
1913    #[inline]
1914    #[rustc_allow_incoherent_impl]
1915    #[unstable(feature = "f128", issue = "116909")]
1916    #[must_use = "method returns a new number and does not mutate the original value"]
1917    pub fn powi(self, n: i32) -> f128 {
1918        intrinsics::powi(self, n)
1919    }
1920
1921    /// Returns the square root of a number.
1922    ///
1923    /// Returns NaN if `self` is a negative number other than `-0.0`.
1924    ///
1925    /// # Precision
1926    ///
1927    /// The result of this operation is guaranteed to be the rounded
1928    /// infinite-precision result. It is specified by IEEE 754 as `squareRoot`
1929    /// and guaranteed not to change.
1930    ///
1931    /// # Examples
1932    ///
1933    /// ```
1934    /// #![feature(f128)]
1935    /// # #[cfg(any(miri, target_has_reliable_f128_math))] { // Miri uses softfloats, always works
1936    ///
1937    /// let positive = 4.0_f128;
1938    /// let negative = -4.0_f128;
1939    /// let negative_zero = -0.0_f128;
1940    ///
1941    /// assert_eq!(positive.sqrt(), 2.0);
1942    /// assert!(negative.sqrt().is_nan());
1943    /// assert!(negative_zero.sqrt() == negative_zero);
1944    /// # }
1945    /// ```
1946    #[inline]
1947    #[doc(alias = "squareRoot")]
1948    #[rustc_allow_incoherent_impl]
1949    #[unstable(feature = "f128", issue = "116909")]
1950    #[must_use = "method returns a new number and does not mutate the original value"]
1951    pub fn sqrt(self) -> f128 {
1952        intrinsics::sqrt(self)
1953    }
1954}