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