f128.rs - source
Description: Source of the Rust file `library/core/src/num/f128.rs`.

#
core/num/
f128.rs

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