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