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