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