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;
15#[cfg(not(test))]
16use crate::intrinsics;
17use crate::mem;
18use crate::num::FpCategory;
19use crate::panic::const_assert;
20
21/// Basic mathematical constants.
22#[unstable(feature = "f128", issue = "116909")]
23pub mod consts {
24 // FIXME: replace with mathematical constants from cmath.
25
26 /// Archimedes' constant (π)
27 #[unstable(feature = "f128", issue = "116909")]
28 pub const PI: f128 = 3.14159265358979323846264338327950288419716939937510582097494_f128;
29
30 /// The full circle constant (τ)
31 ///
32 /// Equal to 2π.
33 #[unstable(feature = "f128", issue = "116909")]
34 pub const TAU: f128 = 6.28318530717958647692528676655900576839433879875021164194989_f128;
35
36 /// The golden ratio (φ)
37 #[unstable(feature = "f128", issue = "116909")]
38 // Also, #[unstable(feature = "more_float_constants", issue = "103883")]
39 pub const PHI: f128 = 1.61803398874989484820458683436563811772030917980576286213545_f128;
40
41 /// The Euler-Mascheroni constant (γ)
42 #[unstable(feature = "f128", issue = "116909")]
43 // Also, #[unstable(feature = "more_float_constants", issue = "103883")]
44 pub const EGAMMA: f128 = 0.577215664901532860606512090082402431042159335939923598805767_f128;
45
46 /// π/2
47 #[unstable(feature = "f128", issue = "116909")]
48 pub const FRAC_PI_2: f128 = 1.57079632679489661923132169163975144209858469968755291048747_f128;
49
50 /// π/3
51 #[unstable(feature = "f128", issue = "116909")]
52 pub const FRAC_PI_3: f128 = 1.04719755119659774615421446109316762806572313312503527365831_f128;
53
54 /// π/4
55 #[unstable(feature = "f128", issue = "116909")]
56 pub const FRAC_PI_4: f128 = 0.785398163397448309615660845819875721049292349843776455243736_f128;
57
58 /// π/6
59 #[unstable(feature = "f128", issue = "116909")]
60 pub const FRAC_PI_6: f128 = 0.523598775598298873077107230546583814032861566562517636829157_f128;
61
62 /// π/8
63 #[unstable(feature = "f128", issue = "116909")]
64 pub const FRAC_PI_8: f128 = 0.392699081698724154807830422909937860524646174921888227621868_f128;
65
66 /// 1/π
67 #[unstable(feature = "f128", issue = "116909")]
68 pub const FRAC_1_PI: f128 = 0.318309886183790671537767526745028724068919291480912897495335_f128;
69
70 /// 1/sqrt(π)
71 #[unstable(feature = "f128", issue = "116909")]
72 // Also, #[unstable(feature = "more_float_constants", issue = "103883")]
73 pub const FRAC_1_SQRT_PI: f128 =
74 0.564189583547756286948079451560772585844050629328998856844086_f128;
75
76 /// 1/sqrt(2π)
77 #[doc(alias = "FRAC_1_SQRT_TAU")]
78 #[unstable(feature = "f128", issue = "116909")]
79 // Also, #[unstable(feature = "more_float_constants", issue = "103883")]
80 pub const FRAC_1_SQRT_2PI: f128 =
81 0.398942280401432677939946059934381868475858631164934657665926_f128;
82
83 /// 2/π
84 #[unstable(feature = "f128", issue = "116909")]
85 pub const FRAC_2_PI: f128 = 0.636619772367581343075535053490057448137838582961825794990669_f128;
86
87 /// 2/sqrt(π)
88 #[unstable(feature = "f128", issue = "116909")]
89 pub const FRAC_2_SQRT_PI: f128 =
90 1.12837916709551257389615890312154517168810125865799771368817_f128;
91
92 /// sqrt(2)
93 #[unstable(feature = "f128", issue = "116909")]
94 pub const SQRT_2: f128 = 1.41421356237309504880168872420969807856967187537694807317668_f128;
95
96 /// 1/sqrt(2)
97 #[unstable(feature = "f128", issue = "116909")]
98 pub const FRAC_1_SQRT_2: f128 =
99 0.707106781186547524400844362104849039284835937688474036588340_f128;
100
101 /// sqrt(3)
102 #[unstable(feature = "f128", issue = "116909")]
103 // Also, #[unstable(feature = "more_float_constants", issue = "103883")]
104 pub const SQRT_3: f128 = 1.73205080756887729352744634150587236694280525381038062805581_f128;
105
106 /// 1/sqrt(3)
107 #[unstable(feature = "f128", issue = "116909")]
108 // Also, #[unstable(feature = "more_float_constants", issue = "103883")]
109 pub const FRAC_1_SQRT_3: f128 =
110 0.577350269189625764509148780501957455647601751270126876018602_f128;
111
112 /// Euler's number (e)
113 #[unstable(feature = "f128", issue = "116909")]
114 pub const E: f128 = 2.71828182845904523536028747135266249775724709369995957496697_f128;
115
116 /// log<sub>2</sub>(10)
117 #[unstable(feature = "f128", issue = "116909")]
118 pub const LOG2_10: f128 = 3.32192809488736234787031942948939017586483139302458061205476_f128;
119
120 /// log<sub>2</sub>(e)
121 #[unstable(feature = "f128", issue = "116909")]
122 pub const LOG2_E: f128 = 1.44269504088896340735992468100189213742664595415298593413545_f128;
123
124 /// log<sub>10</sub>(2)
125 #[unstable(feature = "f128", issue = "116909")]
126 pub const LOG10_2: f128 = 0.301029995663981195213738894724493026768189881462108541310427_f128;
127
128 /// log<sub>10</sub>(e)
129 #[unstable(feature = "f128", issue = "116909")]
130 pub const LOG10_E: f128 = 0.434294481903251827651128918916605082294397005803666566114454_f128;
131
132 /// ln(2)
133 #[unstable(feature = "f128", issue = "116909")]
134 pub const LN_2: f128 = 0.693147180559945309417232121458176568075500134360255254120680_f128;
135
136 /// ln(10)
137 #[unstable(feature = "f128", issue = "116909")]
138 pub const LN_10: f128 = 2.30258509299404568401799145468436420760110148862877297603333_f128;
139}
140
141#[cfg(not(test))]
142impl f128 {
143 // FIXME(f16_f128): almost all methods in this `impl` are missing examples and a const
144 // implementation. Add these once we can run code on all platforms and have f16/f128 in CTFE.
145
146 /// The radix or base of the internal representation of `f128`.
147 #[unstable(feature = "f128", issue = "116909")]
148 pub const RADIX: u32 = 2;
149
150 /// Number of significant digits in base 2.
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 ///
202 /// If <i>x</i> = `MIN_EXP`, then normal numbers
203 /// ≥ 0.5 × 2<sup><i>x</i></sup>.
204 #[unstable(feature = "f128", issue = "116909")]
205 pub const MIN_EXP: i32 = -16_381;
206 /// Maximum possible power of 2 exponent.
207 ///
208 /// If <i>x</i> = `MAX_EXP`, then normal numbers
209 /// < 1 × 2<sup><i>x</i></sup>.
210 #[unstable(feature = "f128", issue = "116909")]
211 pub const MAX_EXP: i32 = 16_384;
212
213 /// Minimum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
214 ///
215 /// Equal to ceil(log<sub>10</sub> [`MIN_POSITIVE`]).
216 ///
217 /// [`MIN_POSITIVE`]: f128::MIN_POSITIVE
218 #[unstable(feature = "f128", issue = "116909")]
219 pub const MIN_10_EXP: i32 = -4_931;
220 /// Maximum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
221 ///
222 /// Equal to floor(log<sub>10</sub> [`MAX`]).
223 ///
224 /// [`MAX`]: f128::MAX
225 #[unstable(feature = "f128", issue = "116909")]
226 pub const MAX_10_EXP: i32 = 4_932;
227
228 /// Not a Number (NaN).
229 ///
230 /// Note that IEEE 754 doesn't define just a single NaN value;
231 /// a plethora of bit patterns are considered to be NaN.
232 /// Furthermore, the standard makes a difference
233 /// between a "signaling" and a "quiet" NaN,
234 /// and allows inspecting its "payload" (the unspecified bits in the bit pattern).
235 /// This constant isn't guaranteed to equal to any specific NaN bitpattern,
236 /// and the stability of its representation over Rust versions
237 /// and target platforms isn't guaranteed.
238 #[allow(clippy::eq_op)]
239 #[rustc_diagnostic_item = "f128_nan"]
240 #[unstable(feature = "f128", issue = "116909")]
241 pub const NAN: f128 = 0.0_f128 / 0.0_f128;
242
243 /// Infinity (∞).
244 #[unstable(feature = "f128", issue = "116909")]
245 pub const INFINITY: f128 = 1.0_f128 / 0.0_f128;
246
247 /// Negative infinity (−∞).
248 #[unstable(feature = "f128", issue = "116909")]
249 pub const NEG_INFINITY: f128 = -1.0_f128 / 0.0_f128;
250
251 /// Sign bit
252 pub(crate) const SIGN_MASK: u128 = 0x8000_0000_0000_0000_0000_0000_0000_0000;
253
254 /// Exponent mask
255 pub(crate) const EXP_MASK: u128 = 0x7fff_0000_0000_0000_0000_0000_0000_0000;
256
257 /// Mantissa mask
258 pub(crate) const MAN_MASK: u128 = 0x0000_ffff_ffff_ffff_ffff_ffff_ffff_ffff;
259
260 /// Minimum representable positive value (min subnormal)
261 const TINY_BITS: u128 = 0x1;
262
263 /// Minimum representable negative value (min negative subnormal)
264 const NEG_TINY_BITS: u128 = Self::TINY_BITS | Self::SIGN_MASK;
265
266 /// Returns `true` if this value is NaN.
267 ///
268 /// ```
269 /// #![feature(f128)]
270 /// # // FIXME(f16_f128): remove when `unordtf2` is available
271 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
272 ///
273 /// let nan = f128::NAN;
274 /// let f = 7.0_f128;
275 ///
276 /// assert!(nan.is_nan());
277 /// assert!(!f.is_nan());
278 /// # }
279 /// ```
280 #[inline]
281 #[must_use]
282 #[unstable(feature = "f128", issue = "116909")]
283 #[allow(clippy::eq_op)] // > if you intended to check if the operand is NaN, use `.is_nan()` instead :)
284 pub const fn is_nan(self) -> bool {
285 self != self
286 }
287
288 /// Returns `true` if this value is positive infinity or negative infinity, and
289 /// `false` otherwise.
290 ///
291 /// ```
292 /// #![feature(f128)]
293 /// # // FIXME(f16_f128): remove when `eqtf2` is available
294 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
295 ///
296 /// let f = 7.0f128;
297 /// let inf = f128::INFINITY;
298 /// let neg_inf = f128::NEG_INFINITY;
299 /// let nan = f128::NAN;
300 ///
301 /// assert!(!f.is_infinite());
302 /// assert!(!nan.is_infinite());
303 ///
304 /// assert!(inf.is_infinite());
305 /// assert!(neg_inf.is_infinite());
306 /// # }
307 /// ```
308 #[inline]
309 #[must_use]
310 #[unstable(feature = "f128", issue = "116909")]
311 pub const fn is_infinite(self) -> bool {
312 (self == f128::INFINITY) | (self == f128::NEG_INFINITY)
313 }
314
315 /// Returns `true` if this number is neither infinite nor NaN.
316 ///
317 /// ```
318 /// #![feature(f128)]
319 /// # // FIXME(f16_f128): remove when `lttf2` is available
320 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
321 ///
322 /// let f = 7.0f128;
323 /// let inf: f128 = f128::INFINITY;
324 /// let neg_inf: f128 = f128::NEG_INFINITY;
325 /// let nan: f128 = f128::NAN;
326 ///
327 /// assert!(f.is_finite());
328 ///
329 /// assert!(!nan.is_finite());
330 /// assert!(!inf.is_finite());
331 /// assert!(!neg_inf.is_finite());
332 /// # }
333 /// ```
334 #[inline]
335 #[must_use]
336 #[unstable(feature = "f128", issue = "116909")]
337 #[rustc_const_unstable(feature = "f128", issue = "116909")]
338 pub const fn is_finite(self) -> bool {
339 // There's no need to handle NaN separately: if self is NaN,
340 // the comparison is not true, exactly as desired.
341 self.abs() < Self::INFINITY
342 }
343
344 /// Returns `true` if the number is [subnormal].
345 ///
346 /// ```
347 /// #![feature(f128)]
348 /// # // FIXME(f16_f128): remove when `eqtf2` is available
349 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
350 ///
351 /// let min = f128::MIN_POSITIVE; // 3.362103143e-4932f128
352 /// let max = f128::MAX;
353 /// let lower_than_min = 1.0e-4960_f128;
354 /// let zero = 0.0_f128;
355 ///
356 /// assert!(!min.is_subnormal());
357 /// assert!(!max.is_subnormal());
358 ///
359 /// assert!(!zero.is_subnormal());
360 /// assert!(!f128::NAN.is_subnormal());
361 /// assert!(!f128::INFINITY.is_subnormal());
362 /// // Values between `0` and `min` are Subnormal.
363 /// assert!(lower_than_min.is_subnormal());
364 /// # }
365 /// ```
366 ///
367 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
368 #[inline]
369 #[must_use]
370 #[unstable(feature = "f128", issue = "116909")]
371 pub const fn is_subnormal(self) -> bool {
372 matches!(self.classify(), FpCategory::Subnormal)
373 }
374
375 /// Returns `true` if the number is neither zero, infinite, [subnormal], or NaN.
376 ///
377 /// ```
378 /// #![feature(f128)]
379 /// # // FIXME(f16_f128): remove when `eqtf2` is available
380 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
381 ///
382 /// let min = f128::MIN_POSITIVE; // 3.362103143e-4932f128
383 /// let max = f128::MAX;
384 /// let lower_than_min = 1.0e-4960_f128;
385 /// let zero = 0.0_f128;
386 ///
387 /// assert!(min.is_normal());
388 /// assert!(max.is_normal());
389 ///
390 /// assert!(!zero.is_normal());
391 /// assert!(!f128::NAN.is_normal());
392 /// assert!(!f128::INFINITY.is_normal());
393 /// // Values between `0` and `min` are Subnormal.
394 /// assert!(!lower_than_min.is_normal());
395 /// # }
396 /// ```
397 ///
398 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
399 #[inline]
400 #[must_use]
401 #[unstable(feature = "f128", issue = "116909")]
402 pub const fn is_normal(self) -> bool {
403 matches!(self.classify(), FpCategory::Normal)
404 }
405
406 /// Returns the floating point category of the number. If only one property
407 /// is going to be tested, it is generally faster to use the specific
408 /// predicate instead.
409 ///
410 /// ```
411 /// #![feature(f128)]
412 /// # // FIXME(f16_f128): remove when `eqtf2` is available
413 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
414 ///
415 /// use std::num::FpCategory;
416 ///
417 /// let num = 12.4_f128;
418 /// let inf = f128::INFINITY;
419 ///
420 /// assert_eq!(num.classify(), FpCategory::Normal);
421 /// assert_eq!(inf.classify(), FpCategory::Infinite);
422 /// # }
423 /// ```
424 #[inline]
425 #[unstable(feature = "f128", issue = "116909")]
426 pub const fn classify(self) -> FpCategory {
427 let bits = self.to_bits();
428 match (bits & Self::MAN_MASK, bits & Self::EXP_MASK) {
429 (0, Self::EXP_MASK) => FpCategory::Infinite,
430 (_, Self::EXP_MASK) => FpCategory::Nan,
431 (0, 0) => FpCategory::Zero,
432 (_, 0) => FpCategory::Subnormal,
433 _ => FpCategory::Normal,
434 }
435 }
436
437 /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with
438 /// positive sign bit and positive infinity.
439 ///
440 /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
441 /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
442 /// conserved over arithmetic operations, the result of `is_sign_positive` on
443 /// a NaN might produce an unexpected or non-portable result. See the [specification
444 /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == 1.0`
445 /// if you need fully portable behavior (will return `false` for all NaNs).
446 ///
447 /// ```
448 /// #![feature(f128)]
449 ///
450 /// let f = 7.0_f128;
451 /// let g = -7.0_f128;
452 ///
453 /// assert!(f.is_sign_positive());
454 /// assert!(!g.is_sign_positive());
455 /// ```
456 #[inline]
457 #[must_use]
458 #[unstable(feature = "f128", issue = "116909")]
459 pub const fn is_sign_positive(self) -> bool {
460 !self.is_sign_negative()
461 }
462
463 /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with
464 /// negative sign bit and negative infinity.
465 ///
466 /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
467 /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
468 /// conserved over arithmetic operations, the result of `is_sign_negative` on
469 /// a NaN might produce an unexpected or non-portable result. See the [specification
470 /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == -1.0`
471 /// if you need fully portable behavior (will return `false` for all NaNs).
472 ///
473 /// ```
474 /// #![feature(f128)]
475 ///
476 /// let f = 7.0_f128;
477 /// let g = -7.0_f128;
478 ///
479 /// assert!(!f.is_sign_negative());
480 /// assert!(g.is_sign_negative());
481 /// ```
482 #[inline]
483 #[must_use]
484 #[unstable(feature = "f128", issue = "116909")]
485 pub const fn is_sign_negative(self) -> bool {
486 // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
487 // applies to zeros and NaNs as well.
488 // SAFETY: This is just transmuting to get the sign bit, it's fine.
489 (self.to_bits() & (1 << 127)) != 0
490 }
491
492 /// Returns the least number greater than `self`.
493 ///
494 /// Let `TINY` be the smallest representable positive `f128`. Then,
495 /// - if `self.is_nan()`, this returns `self`;
496 /// - if `self` is [`NEG_INFINITY`], this returns [`MIN`];
497 /// - if `self` is `-TINY`, this returns -0.0;
498 /// - if `self` is -0.0 or +0.0, this returns `TINY`;
499 /// - if `self` is [`MAX`] or [`INFINITY`], this returns [`INFINITY`];
500 /// - otherwise the unique least value greater than `self` is returned.
501 ///
502 /// The identity `x.next_up() == -(-x).next_down()` holds for all non-NaN `x`. When `x`
503 /// is finite `x == x.next_up().next_down()` also holds.
504 ///
505 /// ```rust
506 /// #![feature(f128)]
507 /// # // FIXME(f16_f128): remove when `eqtf2` is available
508 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
509 ///
510 /// // f128::EPSILON is the difference between 1.0 and the next number up.
511 /// assert_eq!(1.0f128.next_up(), 1.0 + f128::EPSILON);
512 /// // But not for most numbers.
513 /// assert!(0.1f128.next_up() < 0.1 + f128::EPSILON);
514 /// assert_eq!(4611686018427387904f128.next_up(), 4611686018427387904.000000000000001);
515 /// # }
516 /// ```
517 ///
518 /// This operation corresponds to IEEE-754 `nextUp`.
519 ///
520 /// [`NEG_INFINITY`]: Self::NEG_INFINITY
521 /// [`INFINITY`]: Self::INFINITY
522 /// [`MIN`]: Self::MIN
523 /// [`MAX`]: Self::MAX
524 #[inline]
525 #[doc(alias = "nextUp")]
526 #[unstable(feature = "f128", issue = "116909")]
527 pub const fn next_up(self) -> Self {
528 // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
529 // denormals to zero. This is in general unsound and unsupported, but here
530 // we do our best to still produce the correct result on such targets.
531 let bits = self.to_bits();
532 if self.is_nan() || bits == Self::INFINITY.to_bits() {
533 return self;
534 }
535
536 let abs = bits & !Self::SIGN_MASK;
537 let next_bits = if abs == 0 {
538 Self::TINY_BITS
539 } else if bits == abs {
540 bits + 1
541 } else {
542 bits - 1
543 };
544 Self::from_bits(next_bits)
545 }
546
547 /// Returns the greatest number less than `self`.
548 ///
549 /// Let `TINY` be the smallest representable positive `f128`. Then,
550 /// - if `self.is_nan()`, this returns `self`;
551 /// - if `self` is [`INFINITY`], this returns [`MAX`];
552 /// - if `self` is `TINY`, this returns 0.0;
553 /// - if `self` is -0.0 or +0.0, this returns `-TINY`;
554 /// - if `self` is [`MIN`] or [`NEG_INFINITY`], this returns [`NEG_INFINITY`];
555 /// - otherwise the unique greatest value less than `self` is returned.
556 ///
557 /// The identity `x.next_down() == -(-x).next_up()` holds for all non-NaN `x`. When `x`
558 /// is finite `x == x.next_down().next_up()` also holds.
559 ///
560 /// ```rust
561 /// #![feature(f128)]
562 /// # // FIXME(f16_f128): remove when `eqtf2` is available
563 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
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 /// # // FIXME(f16_f128): remove when `eqtf2` is available
607 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
608 ///
609 /// let x = 2.0_f128;
610 /// let abs_difference = (x.recip() - (1.0 / x)).abs();
611 ///
612 /// assert!(abs_difference <= f128::EPSILON);
613 /// # }
614 /// ```
615 #[inline]
616 #[unstable(feature = "f128", issue = "116909")]
617 #[must_use = "this returns the result of the operation, without modifying the original"]
618 pub const fn recip(self) -> Self {
619 1.0 / self
620 }
621
622 /// Converts radians to degrees.
623 ///
624 /// ```
625 /// #![feature(f128)]
626 /// # // FIXME(f16_f128): remove when `eqtf2` is available
627 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
628 ///
629 /// let angle = std::f128::consts::PI;
630 ///
631 /// let abs_difference = (angle.to_degrees() - 180.0).abs();
632 /// assert!(abs_difference <= f128::EPSILON);
633 /// # }
634 /// ```
635 #[inline]
636 #[unstable(feature = "f128", issue = "116909")]
637 #[must_use = "this returns the result of the operation, without modifying the original"]
638 pub const fn to_degrees(self) -> Self {
639 // Use a literal for better precision.
640 const PIS_IN_180: f128 = 57.2957795130823208767981548141051703324054724665643215491602_f128;
641 self * PIS_IN_180
642 }
643
644 /// Converts degrees to radians.
645 ///
646 /// ```
647 /// #![feature(f128)]
648 /// # // FIXME(f16_f128): remove when `eqtf2` is available
649 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
650 ///
651 /// let angle = 180.0f128;
652 ///
653 /// let abs_difference = (angle.to_radians() - std::f128::consts::PI).abs();
654 ///
655 /// assert!(abs_difference <= 1e-30);
656 /// # }
657 /// ```
658 #[inline]
659 #[unstable(feature = "f128", issue = "116909")]
660 #[must_use = "this returns the result of the operation, without modifying the original"]
661 pub const fn to_radians(self) -> f128 {
662 // Use a literal for better precision.
663 const RADS_PER_DEG: f128 =
664 0.0174532925199432957692369076848861271344287188854172545609719_f128;
665 self * RADS_PER_DEG
666 }
667
668 /// Returns the maximum of the two numbers, ignoring NaN.
669 ///
670 /// If one of the arguments is NaN, then the other argument is returned.
671 /// This follows the IEEE 754-2008 semantics for maxNum, except for handling of signaling NaNs;
672 /// this function handles all NaNs the same way and avoids maxNum's problems with associativity.
673 /// This also matches the behavior of libm’s fmax. In particular, if the inputs compare equal
674 /// (such as for the case of `+0.0` and `-0.0`), either input may be returned non-deterministically.
675 ///
676 /// ```
677 /// #![feature(f128)]
678 /// # // Using aarch64 because `reliable_f128_math` is needed
679 /// # #[cfg(all(target_arch = "aarch64", target_os = "linux"))] {
680 ///
681 /// let x = 1.0f128;
682 /// let y = 2.0f128;
683 ///
684 /// assert_eq!(x.max(y), y);
685 /// # }
686 /// ```
687 #[inline]
688 #[unstable(feature = "f128", issue = "116909")]
689 #[rustc_const_unstable(feature = "f128", issue = "116909")]
690 #[must_use = "this returns the result of the comparison, without modifying either input"]
691 pub const fn max(self, other: f128) -> f128 {
692 intrinsics::maxnumf128(self, other)
693 }
694
695 /// Returns the minimum of the two numbers, ignoring NaN.
696 ///
697 /// If one of the arguments is NaN, then the other argument is returned.
698 /// This follows the IEEE 754-2008 semantics for minNum, except for handling of signaling NaNs;
699 /// this function handles all NaNs the same way and avoids minNum's problems with associativity.
700 /// This also matches the behavior of libm’s fmin. In particular, if the inputs compare equal
701 /// (such as for the case of `+0.0` and `-0.0`), either input may be returned non-deterministically.
702 ///
703 /// ```
704 /// #![feature(f128)]
705 /// # // Using aarch64 because `reliable_f128_math` is needed
706 /// # #[cfg(all(target_arch = "aarch64", target_os = "linux"))] {
707 ///
708 /// let x = 1.0f128;
709 /// let y = 2.0f128;
710 ///
711 /// assert_eq!(x.min(y), x);
712 /// # }
713 /// ```
714 #[inline]
715 #[unstable(feature = "f128", issue = "116909")]
716 #[rustc_const_unstable(feature = "f128", issue = "116909")]
717 #[must_use = "this returns the result of the comparison, without modifying either input"]
718 pub const fn min(self, other: f128) -> f128 {
719 intrinsics::minnumf128(self, other)
720 }
721
722 /// Returns the maximum of the two numbers, propagating NaN.
723 ///
724 /// This returns NaN when *either* argument is NaN, as opposed to
725 /// [`f128::max`] which only returns NaN when *both* arguments are NaN.
726 ///
727 /// ```
728 /// #![feature(f128)]
729 /// #![feature(float_minimum_maximum)]
730 /// # // Using aarch64 because `reliable_f128_math` is needed
731 /// # #[cfg(all(target_arch = "aarch64", target_os = "linux"))] {
732 ///
733 /// let x = 1.0f128;
734 /// let y = 2.0f128;
735 ///
736 /// assert_eq!(x.maximum(y), y);
737 /// assert!(x.maximum(f128::NAN).is_nan());
738 /// # }
739 /// ```
740 ///
741 /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the greater
742 /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
743 /// Note that this follows the semantics specified in IEEE 754-2019.
744 ///
745 /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
746 /// operand is conserved; see the [specification of NaN bit patterns](f32#nan-bit-patterns) for more info.
747 #[inline]
748 #[unstable(feature = "f128", issue = "116909")]
749 // #[unstable(feature = "float_minimum_maximum", issue = "91079")]
750 #[must_use = "this returns the result of the comparison, without modifying either input"]
751 pub const fn maximum(self, other: f128) -> f128 {
752 if self > other {
753 self
754 } else if other > self {
755 other
756 } else if self == other {
757 if self.is_sign_positive() && other.is_sign_negative() { self } else { other }
758 } else {
759 self + other
760 }
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 if self < other {
794 self
795 } else if other < self {
796 other
797 } else if self == other {
798 if self.is_sign_negative() && other.is_sign_positive() { self } else { other }
799 } else {
800 // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
801 self + other
802 }
803 }
804
805 /// Calculates the middle point of `self` and `rhs`.
806 ///
807 /// This returns NaN when *either* argument is NaN or if a combination of
808 /// +inf and -inf is provided as arguments.
809 ///
810 /// # Examples
811 ///
812 /// ```
813 /// #![feature(f128)]
814 /// # // Using aarch64 because `reliable_f128_math` is needed
815 /// # #[cfg(all(target_arch = "aarch64", target_os = "linux"))] {
816 ///
817 /// assert_eq!(1f128.midpoint(4.0), 2.5);
818 /// assert_eq!((-5.5f128).midpoint(8.0), 1.25);
819 /// # }
820 /// ```
821 #[inline]
822 #[unstable(feature = "f128", issue = "116909")]
823 #[rustc_const_unstable(feature = "f128", issue = "116909")]
824 pub const fn midpoint(self, other: f128) -> f128 {
825 const LO: f128 = f128::MIN_POSITIVE * 2.;
826 const HI: f128 = f128::MAX / 2.;
827
828 let (a, b) = (self, other);
829 let abs_a = a.abs();
830 let abs_b = b.abs();
831
832 if abs_a <= HI && abs_b <= HI {
833 // Overflow is impossible
834 (a + b) / 2.
835 } else if abs_a < LO {
836 // Not safe to halve `a` (would underflow)
837 a + (b / 2.)
838 } else if abs_b < LO {
839 // Not safe to halve `b` (would underflow)
840 (a / 2.) + b
841 } else {
842 // Safe to halve `a` and `b`
843 (a / 2.) + (b / 2.)
844 }
845 }
846
847 /// Rounds toward zero and converts to any primitive integer type,
848 /// assuming that the value is finite and fits in that type.
849 ///
850 /// ```
851 /// #![feature(f128)]
852 /// # // FIXME(f16_f128): remove when `float*itf` is available
853 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
854 ///
855 /// let value = 4.6_f128;
856 /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
857 /// assert_eq!(rounded, 4);
858 ///
859 /// let value = -128.9_f128;
860 /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
861 /// assert_eq!(rounded, i8::MIN);
862 /// # }
863 /// ```
864 ///
865 /// # Safety
866 ///
867 /// The value must:
868 ///
869 /// * Not be `NaN`
870 /// * Not be infinite
871 /// * Be representable in the return type `Int`, after truncating off its fractional part
872 #[inline]
873 #[unstable(feature = "f128", issue = "116909")]
874 #[must_use = "this returns the result of the operation, without modifying the original"]
875 pub unsafe fn to_int_unchecked<Int>(self) -> Int
876 where
877 Self: FloatToInt<Int>,
878 {
879 // SAFETY: the caller must uphold the safety contract for
880 // `FloatToInt::to_int_unchecked`.
881 unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
882 }
883
884 /// Raw transmutation to `u128`.
885 ///
886 /// This is currently identical to `transmute::<f128, u128>(self)` on all platforms.
887 ///
888 /// See [`from_bits`](#method.from_bits) for some discussion of the
889 /// portability of this operation (there are almost no issues).
890 ///
891 /// Note that this function is distinct from `as` casting, which attempts to
892 /// preserve the *numeric* value, and not the bitwise value.
893 ///
894 /// ```
895 /// #![feature(f128)]
896 ///
897 /// # // FIXME(f16_f128): enable this once const casting works
898 /// # // assert_ne!((1f128).to_bits(), 1f128 as u128); // to_bits() is not casting!
899 /// assert_eq!((12.5f128).to_bits(), 0x40029000000000000000000000000000);
900 /// ```
901 #[inline]
902 #[unstable(feature = "f128", issue = "116909")]
903 #[must_use = "this returns the result of the operation, without modifying the original"]
904 pub const fn to_bits(self) -> u128 {
905 // SAFETY: `u128` is a plain old datatype so we can always transmute to it.
906 unsafe { mem::transmute(self) }
907 }
908
909 /// Raw transmutation from `u128`.
910 ///
911 /// This is currently identical to `transmute::<u128, f128>(v)` on all platforms.
912 /// It turns out this is incredibly portable, for two reasons:
913 ///
914 /// * Floats and Ints have the same endianness on all supported platforms.
915 /// * IEEE 754 very precisely specifies the bit layout of floats.
916 ///
917 /// However there is one caveat: prior to the 2008 version of IEEE 754, how
918 /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
919 /// (notably x86 and ARM) picked the interpretation that was ultimately
920 /// standardized in 2008, but some didn't (notably MIPS). As a result, all
921 /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
922 ///
923 /// Rather than trying to preserve signaling-ness cross-platform, this
924 /// implementation favors preserving the exact bits. This means that
925 /// any payloads encoded in NaNs will be preserved even if the result of
926 /// this method is sent over the network from an x86 machine to a MIPS one.
927 ///
928 /// If the results of this method are only manipulated by the same
929 /// architecture that produced them, then there is no portability concern.
930 ///
931 /// If the input isn't NaN, then there is no portability concern.
932 ///
933 /// If you don't care about signalingness (very likely), then there is no
934 /// portability concern.
935 ///
936 /// Note that this function is distinct from `as` casting, which attempts to
937 /// preserve the *numeric* value, and not the bitwise value.
938 ///
939 /// ```
940 /// #![feature(f128)]
941 /// # // FIXME(f16_f128): remove when `eqtf2` is available
942 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
943 ///
944 /// let v = f128::from_bits(0x40029000000000000000000000000000);
945 /// assert_eq!(v, 12.5);
946 /// # }
947 /// ```
948 #[inline]
949 #[must_use]
950 #[unstable(feature = "f128", issue = "116909")]
951 pub const fn from_bits(v: u128) -> Self {
952 // It turns out the safety issues with sNaN were overblown! Hooray!
953 // SAFETY: `u128` is a plain old datatype so we can always transmute from it.
954 unsafe { mem::transmute(v) }
955 }
956
957 /// Returns the memory representation of this floating point number as a byte array in
958 /// big-endian (network) byte order.
959 ///
960 /// See [`from_bits`](Self::from_bits) for some discussion of the
961 /// portability of this operation (there are almost no issues).
962 ///
963 /// # Examples
964 ///
965 /// ```
966 /// #![feature(f128)]
967 ///
968 /// let bytes = 12.5f128.to_be_bytes();
969 /// assert_eq!(
970 /// bytes,
971 /// [0x40, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,
972 /// 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
973 /// );
974 /// ```
975 #[inline]
976 #[unstable(feature = "f128", issue = "116909")]
977 #[must_use = "this returns the result of the operation, without modifying the original"]
978 pub const fn to_be_bytes(self) -> [u8; 16] {
979 self.to_bits().to_be_bytes()
980 }
981
982 /// Returns the memory representation of this floating point number as a byte array in
983 /// little-endian byte order.
984 ///
985 /// See [`from_bits`](Self::from_bits) for some discussion of the
986 /// portability of this operation (there are almost no issues).
987 ///
988 /// # Examples
989 ///
990 /// ```
991 /// #![feature(f128)]
992 ///
993 /// let bytes = 12.5f128.to_le_bytes();
994 /// assert_eq!(
995 /// bytes,
996 /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
997 /// 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x02, 0x40]
998 /// );
999 /// ```
1000 #[inline]
1001 #[unstable(feature = "f128", issue = "116909")]
1002 #[must_use = "this returns the result of the operation, without modifying the original"]
1003 pub const fn to_le_bytes(self) -> [u8; 16] {
1004 self.to_bits().to_le_bytes()
1005 }
1006
1007 /// Returns the memory representation of this floating point number as a byte array in
1008 /// native byte order.
1009 ///
1010 /// As the target platform's native endianness is used, portable code
1011 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1012 ///
1013 /// [`to_be_bytes`]: f128::to_be_bytes
1014 /// [`to_le_bytes`]: f128::to_le_bytes
1015 ///
1016 /// See [`from_bits`](Self::from_bits) for some discussion of the
1017 /// portability of this operation (there are almost no issues).
1018 ///
1019 /// # Examples
1020 ///
1021 /// ```
1022 /// #![feature(f128)]
1023 ///
1024 /// let bytes = 12.5f128.to_ne_bytes();
1025 /// assert_eq!(
1026 /// bytes,
1027 /// if cfg!(target_endian = "big") {
1028 /// [0x40, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,
1029 /// 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1030 /// } else {
1031 /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1032 /// 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x02, 0x40]
1033 /// }
1034 /// );
1035 /// ```
1036 #[inline]
1037 #[unstable(feature = "f128", issue = "116909")]
1038 #[must_use = "this returns the result of the operation, without modifying the original"]
1039 pub const fn to_ne_bytes(self) -> [u8; 16] {
1040 self.to_bits().to_ne_bytes()
1041 }
1042
1043 /// Creates a floating point value from its representation as a byte array in big endian.
1044 ///
1045 /// See [`from_bits`](Self::from_bits) for some discussion of the
1046 /// portability of this operation (there are almost no issues).
1047 ///
1048 /// # Examples
1049 ///
1050 /// ```
1051 /// #![feature(f128)]
1052 /// # // FIXME(f16_f128): remove when `eqtf2` is available
1053 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1054 ///
1055 /// let value = f128::from_be_bytes(
1056 /// [0x40, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,
1057 /// 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1058 /// );
1059 /// assert_eq!(value, 12.5);
1060 /// # }
1061 /// ```
1062 #[inline]
1063 #[must_use]
1064 #[unstable(feature = "f128", issue = "116909")]
1065 pub const fn from_be_bytes(bytes: [u8; 16]) -> Self {
1066 Self::from_bits(u128::from_be_bytes(bytes))
1067 }
1068
1069 /// Creates a floating point value from its representation as a byte array in little endian.
1070 ///
1071 /// See [`from_bits`](Self::from_bits) for some discussion of the
1072 /// portability of this operation (there are almost no issues).
1073 ///
1074 /// # Examples
1075 ///
1076 /// ```
1077 /// #![feature(f128)]
1078 /// # // FIXME(f16_f128): remove when `eqtf2` is available
1079 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1080 ///
1081 /// let value = f128::from_le_bytes(
1082 /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1083 /// 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x02, 0x40]
1084 /// );
1085 /// assert_eq!(value, 12.5);
1086 /// # }
1087 /// ```
1088 #[inline]
1089 #[must_use]
1090 #[unstable(feature = "f128", issue = "116909")]
1091 pub const fn from_le_bytes(bytes: [u8; 16]) -> Self {
1092 Self::from_bits(u128::from_le_bytes(bytes))
1093 }
1094
1095 /// Creates a floating point value from its representation as a byte array in native endian.
1096 ///
1097 /// As the target platform's native endianness is used, portable code
1098 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1099 /// appropriate instead.
1100 ///
1101 /// [`from_be_bytes`]: f128::from_be_bytes
1102 /// [`from_le_bytes`]: f128::from_le_bytes
1103 ///
1104 /// See [`from_bits`](Self::from_bits) for some discussion of the
1105 /// portability of this operation (there are almost no issues).
1106 ///
1107 /// # Examples
1108 ///
1109 /// ```
1110 /// #![feature(f128)]
1111 /// # // FIXME(f16_f128): remove when `eqtf2` is available
1112 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1113 ///
1114 /// let value = f128::from_ne_bytes(if cfg!(target_endian = "big") {
1115 /// [0x40, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,
1116 /// 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1117 /// } else {
1118 /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1119 /// 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x02, 0x40]
1120 /// });
1121 /// assert_eq!(value, 12.5);
1122 /// # }
1123 /// ```
1124 #[inline]
1125 #[must_use]
1126 #[unstable(feature = "f128", issue = "116909")]
1127 pub const fn from_ne_bytes(bytes: [u8; 16]) -> Self {
1128 Self::from_bits(u128::from_ne_bytes(bytes))
1129 }
1130
1131 /// Returns the ordering between `self` and `other`.
1132 ///
1133 /// Unlike the standard partial comparison between floating point numbers,
1134 /// this comparison always produces an ordering in accordance to
1135 /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1136 /// floating point standard. The values are ordered in the following sequence:
1137 ///
1138 /// - negative quiet NaN
1139 /// - negative signaling NaN
1140 /// - negative infinity
1141 /// - negative numbers
1142 /// - negative subnormal numbers
1143 /// - negative zero
1144 /// - positive zero
1145 /// - positive subnormal numbers
1146 /// - positive numbers
1147 /// - positive infinity
1148 /// - positive signaling NaN
1149 /// - positive quiet NaN.
1150 ///
1151 /// The ordering established by this function does not always agree with the
1152 /// [`PartialOrd`] and [`PartialEq`] implementations of `f128`. For example,
1153 /// they consider negative and positive zero equal, while `total_cmp`
1154 /// doesn't.
1155 ///
1156 /// The interpretation of the signaling NaN bit follows the definition in
1157 /// the IEEE 754 standard, which may not match the interpretation by some of
1158 /// the older, non-conformant (e.g. MIPS) hardware implementations.
1159 ///
1160 /// # Example
1161 ///
1162 /// ```
1163 /// #![feature(f128)]
1164 ///
1165 /// struct GoodBoy {
1166 /// name: &'static str,
1167 /// weight: f128,
1168 /// }
1169 ///
1170 /// let mut bois = vec![
1171 /// GoodBoy { name: "Pucci", weight: 0.1 },
1172 /// GoodBoy { name: "Woofer", weight: 99.0 },
1173 /// GoodBoy { name: "Yapper", weight: 10.0 },
1174 /// GoodBoy { name: "Chonk", weight: f128::INFINITY },
1175 /// GoodBoy { name: "Abs. Unit", weight: f128::NAN },
1176 /// GoodBoy { name: "Floaty", weight: -5.0 },
1177 /// ];
1178 ///
1179 /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1180 ///
1181 /// // `f128::NAN` could be positive or negative, which will affect the sort order.
1182 /// if f128::NAN.is_sign_negative() {
1183 /// bois.into_iter().map(|b| b.weight)
1184 /// .zip([f128::NAN, -5.0, 0.1, 10.0, 99.0, f128::INFINITY].iter())
1185 /// .for_each(|(a, b)| assert_eq!(a.to_bits(), b.to_bits()))
1186 /// } else {
1187 /// bois.into_iter().map(|b| b.weight)
1188 /// .zip([-5.0, 0.1, 10.0, 99.0, f128::INFINITY, f128::NAN].iter())
1189 /// .for_each(|(a, b)| assert_eq!(a.to_bits(), b.to_bits()))
1190 /// }
1191 /// ```
1192 #[inline]
1193 #[must_use]
1194 #[unstable(feature = "f128", issue = "116909")]
1195 pub fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1196 let mut left = self.to_bits() as i128;
1197 let mut right = other.to_bits() as i128;
1198
1199 // In case of negatives, flip all the bits except the sign
1200 // to achieve a similar layout as two's complement integers
1201 //
1202 // Why does this work? IEEE 754 floats consist of three fields:
1203 // Sign bit, exponent and mantissa. The set of exponent and mantissa
1204 // fields as a whole have the property that their bitwise order is
1205 // equal to the numeric magnitude where the magnitude is defined.
1206 // The magnitude is not normally defined on NaN values, but
1207 // IEEE 754 totalOrder defines the NaN values also to follow the
1208 // bitwise order. This leads to order explained in the doc comment.
1209 // However, the representation of magnitude is the same for negative
1210 // and positive numbers – only the sign bit is different.
1211 // To easily compare the floats as signed integers, we need to
1212 // flip the exponent and mantissa bits in case of negative numbers.
1213 // We effectively convert the numbers to "two's complement" form.
1214 //
1215 // To do the flipping, we construct a mask and XOR against it.
1216 // We branchlessly calculate an "all-ones except for the sign bit"
1217 // mask from negative-signed values: right shifting sign-extends
1218 // the integer, so we "fill" the mask with sign bits, and then
1219 // convert to unsigned to push one more zero bit.
1220 // On positive values, the mask is all zeros, so it's a no-op.
1221 left ^= (((left >> 127) as u128) >> 1) as i128;
1222 right ^= (((right >> 127) as u128) >> 1) as i128;
1223
1224 left.cmp(&right)
1225 }
1226
1227 /// Restrict a value to a certain interval unless it is NaN.
1228 ///
1229 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1230 /// less than `min`. Otherwise this returns `self`.
1231 ///
1232 /// Note that this function returns NaN if the initial value was NaN as
1233 /// well.
1234 ///
1235 /// # Panics
1236 ///
1237 /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1238 ///
1239 /// # Examples
1240 ///
1241 /// ```
1242 /// #![feature(f128)]
1243 /// # // FIXME(f16_f128): remove when `{eq,gt,unord}tf` are available
1244 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1245 ///
1246 /// assert!((-3.0f128).clamp(-2.0, 1.0) == -2.0);
1247 /// assert!((0.0f128).clamp(-2.0, 1.0) == 0.0);
1248 /// assert!((2.0f128).clamp(-2.0, 1.0) == 1.0);
1249 /// assert!((f128::NAN).clamp(-2.0, 1.0).is_nan());
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 /// Computes the absolute value of `self`.
1274 ///
1275 /// This function always returns the precise result.
1276 ///
1277 /// # Examples
1278 ///
1279 /// ```
1280 /// #![feature(f128)]
1281 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1282 ///
1283 /// let x = 3.5_f128;
1284 /// let y = -3.5_f128;
1285 ///
1286 /// assert_eq!(x.abs(), x);
1287 /// assert_eq!(y.abs(), -y);
1288 ///
1289 /// assert!(f128::NAN.abs().is_nan());
1290 /// # }
1291 /// ```
1292 #[inline]
1293 #[unstable(feature = "f128", issue = "116909")]
1294 #[rustc_const_unstable(feature = "f128", issue = "116909")]
1295 #[must_use = "method returns a new number and does not mutate the original value"]
1296 pub const fn abs(self) -> Self {
1297 // FIXME(f16_f128): replace with `intrinsics::fabsf128` when available
1298 // We don't do this now because LLVM has lowering bugs for f128 math.
1299 Self::from_bits(self.to_bits() & !(1 << 127))
1300 }
1301
1302 /// Returns a number that represents the sign of `self`.
1303 ///
1304 /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
1305 /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
1306 /// - NaN if the number is NaN
1307 ///
1308 /// # Examples
1309 ///
1310 /// ```
1311 /// #![feature(f128)]
1312 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1313 ///
1314 /// let f = 3.5_f128;
1315 ///
1316 /// assert_eq!(f.signum(), 1.0);
1317 /// assert_eq!(f128::NEG_INFINITY.signum(), -1.0);
1318 ///
1319 /// assert!(f128::NAN.signum().is_nan());
1320 /// # }
1321 /// ```
1322 #[inline]
1323 #[unstable(feature = "f128", issue = "116909")]
1324 #[rustc_const_unstable(feature = "f128", issue = "116909")]
1325 #[must_use = "method returns a new number and does not mutate the original value"]
1326 pub const fn signum(self) -> f128 {
1327 if self.is_nan() { Self::NAN } else { 1.0_f128.copysign(self) }
1328 }
1329
1330 /// Returns a number composed of the magnitude of `self` and the sign of
1331 /// `sign`.
1332 ///
1333 /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`.
1334 /// If `self` is a NaN, then a NaN with the same payload as `self` and the sign bit of `sign` is
1335 /// returned.
1336 ///
1337 /// If `sign` is a NaN, then this operation will still carry over its sign into the result. Note
1338 /// that IEEE 754 doesn't assign any meaning to the sign bit in case of a NaN, and as Rust
1339 /// doesn't guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the
1340 /// result of `copysign` with `sign` being a NaN might produce an unexpected or non-portable
1341 /// result. See the [specification of NaN bit patterns](primitive@f32#nan-bit-patterns) for more
1342 /// info.
1343 ///
1344 /// # Examples
1345 ///
1346 /// ```
1347 /// #![feature(f128)]
1348 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1349 ///
1350 /// let f = 3.5_f128;
1351 ///
1352 /// assert_eq!(f.copysign(0.42), 3.5_f128);
1353 /// assert_eq!(f.copysign(-0.42), -3.5_f128);
1354 /// assert_eq!((-f).copysign(0.42), 3.5_f128);
1355 /// assert_eq!((-f).copysign(-0.42), -3.5_f128);
1356 ///
1357 /// assert!(f128::NAN.copysign(1.0).is_nan());
1358 /// # }
1359 /// ```
1360 #[inline]
1361 #[unstable(feature = "f128", issue = "116909")]
1362 #[rustc_const_unstable(feature = "f128", issue = "116909")]
1363 #[must_use = "method returns a new number and does not mutate the original value"]
1364 pub const fn copysign(self, sign: f128) -> f128 {
1365 // SAFETY: this is actually a safe intrinsic
1366 unsafe { intrinsics::copysignf128(self, sign) }
1367 }
1368}