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