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