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