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 exactly one of the arguments is NaN, then the other argument is returned. If both
698 /// arguments are NaN, the return value is NaN, with the bit pattern picked using the usual
699 /// [rules for arithmetic operations](f32#nan-bit-patterns). If the inputs compare equal (such
700 /// as for the case of `+0.0` and `-0.0`), either input may be returned non-deterministically.
701 ///
702 /// This follows the IEEE 754-2008 semantics for `maxNum`, except for handling of signaling NaNs;
703 /// this function handles all NaNs the same way and avoids `maxNum`'s problems with associativity.
704 /// This also matches the behavior of libm’s `fmax`.
705 ///
706 /// ```
707 /// #![feature(f128)]
708 /// # // Using aarch64 because `reliable_f128_math` is needed
709 /// # #[cfg(all(target_arch = "aarch64", target_os = "linux"))] {
710 ///
711 /// let x = 1.0f128;
712 /// let y = 2.0f128;
713 ///
714 /// assert_eq!(x.max(y), y);
715 /// assert_eq!(x.max(f128::NAN), x);
716 /// # }
717 /// ```
718 #[inline]
719 #[unstable(feature = "f128", issue = "116909")]
720 #[rustc_const_unstable(feature = "f128", issue = "116909")]
721 #[must_use = "this returns the result of the comparison, without modifying either input"]
722 pub const fn max(self, other: f128) -> f128 {
723 intrinsics::maxnumf128(self, other)
724 }
725
726 /// Returns the minimum of the two numbers, ignoring NaN.
727 ///
728 /// If exactly one of the arguments is NaN, then the other argument is returned. If both
729 /// arguments are NaN, the return value is NaN, with the bit pattern picked using the usual
730 /// [rules for arithmetic operations](f32#nan-bit-patterns). If the inputs compare equal (such
731 /// as for the case of `+0.0` and `-0.0`), either input may be returned non-deterministically.
732 ///
733 /// This follows the IEEE 754-2008 semantics for `minNum`, except for handling of signaling NaNs;
734 /// this function handles all NaNs the same way and avoids `minNum`'s problems with associativity.
735 /// This also matches the behavior of libm’s `fmin`.
736 ///
737 /// ```
738 /// #![feature(f128)]
739 /// # // Using aarch64 because `reliable_f128_math` is needed
740 /// # #[cfg(all(target_arch = "aarch64", target_os = "linux"))] {
741 ///
742 /// let x = 1.0f128;
743 /// let y = 2.0f128;
744 ///
745 /// assert_eq!(x.min(y), x);
746 /// assert_eq!(x.min(f128::NAN), x);
747 /// # }
748 /// ```
749 #[inline]
750 #[unstable(feature = "f128", issue = "116909")]
751 #[rustc_const_unstable(feature = "f128", issue = "116909")]
752 #[must_use = "this returns the result of the comparison, without modifying either input"]
753 pub const fn min(self, other: f128) -> f128 {
754 intrinsics::minnumf128(self, other)
755 }
756
757 /// Returns the maximum of the two numbers, propagating NaN.
758 ///
759 /// This returns NaN when *either* argument is NaN, as opposed to
760 /// [`f128::max`] which only returns NaN when *both* arguments are NaN.
761 ///
762 /// ```
763 /// #![feature(f128)]
764 /// #![feature(float_minimum_maximum)]
765 /// # // Using aarch64 because `reliable_f128_math` is needed
766 /// # #[cfg(all(target_arch = "aarch64", target_os = "linux"))] {
767 ///
768 /// let x = 1.0f128;
769 /// let y = 2.0f128;
770 ///
771 /// assert_eq!(x.maximum(y), y);
772 /// assert!(x.maximum(f128::NAN).is_nan());
773 /// # }
774 /// ```
775 ///
776 /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the greater
777 /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
778 /// Note that this follows the IEEE 754-2019 semantics for `maximum`.
779 ///
780 /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
781 /// operand is conserved; see the [specification of NaN bit patterns](f32#nan-bit-patterns) for more info.
782 #[inline]
783 #[unstable(feature = "f128", issue = "116909")]
784 // #[unstable(feature = "float_minimum_maximum", issue = "91079")]
785 #[must_use = "this returns the result of the comparison, without modifying either input"]
786 pub const fn maximum(self, other: f128) -> f128 {
787 intrinsics::maximumf128(self, other)
788 }
789
790 /// Returns the minimum of the two numbers, propagating NaN.
791 ///
792 /// This returns NaN when *either* argument is NaN, as opposed to
793 /// [`f128::min`] which only returns NaN when *both* arguments are NaN.
794 ///
795 /// ```
796 /// #![feature(f128)]
797 /// #![feature(float_minimum_maximum)]
798 /// # // Using aarch64 because `reliable_f128_math` is needed
799 /// # #[cfg(all(target_arch = "aarch64", target_os = "linux"))] {
800 ///
801 /// let x = 1.0f128;
802 /// let y = 2.0f128;
803 ///
804 /// assert_eq!(x.minimum(y), x);
805 /// assert!(x.minimum(f128::NAN).is_nan());
806 /// # }
807 /// ```
808 ///
809 /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the lesser
810 /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
811 /// Note that this follows the IEEE 754-2019 semantics for `minimum`.
812 ///
813 /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
814 /// operand is conserved; see the [specification of NaN bit patterns](f32#nan-bit-patterns) for more info.
815 #[inline]
816 #[unstable(feature = "f128", issue = "116909")]
817 // #[unstable(feature = "float_minimum_maximum", issue = "91079")]
818 #[must_use = "this returns the result of the comparison, without modifying either input"]
819 pub const fn minimum(self, other: f128) -> f128 {
820 intrinsics::minimumf128(self, other)
821 }
822
823 /// Calculates the midpoint (average) between `self` and `rhs`.
824 ///
825 /// This returns NaN when *either* argument is NaN or if a combination of
826 /// +inf and -inf is provided as arguments.
827 ///
828 /// # Examples
829 ///
830 /// ```
831 /// #![feature(f128)]
832 /// # // Using aarch64 because `reliable_f128_math` is needed
833 /// # #[cfg(all(target_arch = "aarch64", target_os = "linux"))] {
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 /// # // FIXME(f16_f128): remove when `float*itf` is available
864 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
865 ///
866 /// let value = 4.6_f128;
867 /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
868 /// assert_eq!(rounded, 4);
869 ///
870 /// let value = -128.9_f128;
871 /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
872 /// assert_eq!(rounded, i8::MIN);
873 /// # }
874 /// ```
875 ///
876 /// # Safety
877 ///
878 /// The value must:
879 ///
880 /// * Not be `NaN`
881 /// * Not be infinite
882 /// * Be representable in the return type `Int`, after truncating off its fractional part
883 #[inline]
884 #[unstable(feature = "f128", issue = "116909")]
885 #[must_use = "this returns the result of the operation, without modifying the original"]
886 pub unsafe fn to_int_unchecked<Int>(self) -> Int
887 where
888 Self: FloatToInt<Int>,
889 {
890 // SAFETY: the caller must uphold the safety contract for
891 // `FloatToInt::to_int_unchecked`.
892 unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
893 }
894
895 /// Raw transmutation to `u128`.
896 ///
897 /// This is currently identical to `transmute::<f128, u128>(self)` on all platforms.
898 ///
899 /// See [`from_bits`](#method.from_bits) for some discussion of the
900 /// portability of this operation (there are almost no issues).
901 ///
902 /// Note that this function is distinct from `as` casting, which attempts to
903 /// preserve the *numeric* value, and not the bitwise value.
904 ///
905 /// ```
906 /// #![feature(f128)]
907 ///
908 /// # // FIXME(f16_f128): enable this once const casting works
909 /// # // assert_ne!((1f128).to_bits(), 1f128 as u128); // to_bits() is not casting!
910 /// assert_eq!((12.5f128).to_bits(), 0x40029000000000000000000000000000);
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 /// # // FIXME(f16_f128): remove when `eqtf2` is available
954 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
955 ///
956 /// let v = f128::from_bits(0x40029000000000000000000000000000);
957 /// assert_eq!(v, 12.5);
958 /// # }
959 /// ```
960 #[inline]
961 #[must_use]
962 #[unstable(feature = "f128", issue = "116909")]
963 #[allow(unnecessary_transmutes)]
964 pub const fn from_bits(v: u128) -> Self {
965 // It turns out the safety issues with sNaN were overblown! Hooray!
966 // SAFETY: `u128` is a plain old datatype so we can always transmute from it.
967 unsafe { mem::transmute(v) }
968 }
969
970 /// Returns the memory representation of this floating point number as a byte array in
971 /// big-endian (network) byte order.
972 ///
973 /// See [`from_bits`](Self::from_bits) for some discussion of the
974 /// portability of this operation (there are almost no issues).
975 ///
976 /// # Examples
977 ///
978 /// ```
979 /// #![feature(f128)]
980 ///
981 /// let bytes = 12.5f128.to_be_bytes();
982 /// assert_eq!(
983 /// bytes,
984 /// [0x40, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,
985 /// 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
986 /// );
987 /// ```
988 #[inline]
989 #[unstable(feature = "f128", issue = "116909")]
990 #[must_use = "this returns the result of the operation, without modifying the original"]
991 pub const fn to_be_bytes(self) -> [u8; 16] {
992 self.to_bits().to_be_bytes()
993 }
994
995 /// Returns the memory representation of this floating point number as a byte array in
996 /// little-endian byte order.
997 ///
998 /// See [`from_bits`](Self::from_bits) for some discussion of the
999 /// portability of this operation (there are almost no issues).
1000 ///
1001 /// # Examples
1002 ///
1003 /// ```
1004 /// #![feature(f128)]
1005 ///
1006 /// let bytes = 12.5f128.to_le_bytes();
1007 /// assert_eq!(
1008 /// bytes,
1009 /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1010 /// 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x02, 0x40]
1011 /// );
1012 /// ```
1013 #[inline]
1014 #[unstable(feature = "f128", issue = "116909")]
1015 #[must_use = "this returns the result of the operation, without modifying the original"]
1016 pub const fn to_le_bytes(self) -> [u8; 16] {
1017 self.to_bits().to_le_bytes()
1018 }
1019
1020 /// Returns the memory representation of this floating point number as a byte array in
1021 /// native byte order.
1022 ///
1023 /// As the target platform's native endianness is used, portable code
1024 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1025 ///
1026 /// [`to_be_bytes`]: f128::to_be_bytes
1027 /// [`to_le_bytes`]: f128::to_le_bytes
1028 ///
1029 /// See [`from_bits`](Self::from_bits) for some discussion of the
1030 /// portability of this operation (there are almost no issues).
1031 ///
1032 /// # Examples
1033 ///
1034 /// ```
1035 /// #![feature(f128)]
1036 ///
1037 /// let bytes = 12.5f128.to_ne_bytes();
1038 /// assert_eq!(
1039 /// bytes,
1040 /// if cfg!(target_endian = "big") {
1041 /// [0x40, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,
1042 /// 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1043 /// } else {
1044 /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1045 /// 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x02, 0x40]
1046 /// }
1047 /// );
1048 /// ```
1049 #[inline]
1050 #[unstable(feature = "f128", issue = "116909")]
1051 #[must_use = "this returns the result of the operation, without modifying the original"]
1052 pub const fn to_ne_bytes(self) -> [u8; 16] {
1053 self.to_bits().to_ne_bytes()
1054 }
1055
1056 /// Creates a floating point value from its representation as a byte array in big endian.
1057 ///
1058 /// See [`from_bits`](Self::from_bits) for some discussion of the
1059 /// portability of this operation (there are almost no issues).
1060 ///
1061 /// # Examples
1062 ///
1063 /// ```
1064 /// #![feature(f128)]
1065 /// # // FIXME(f16_f128): remove when `eqtf2` is available
1066 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1067 ///
1068 /// let value = f128::from_be_bytes(
1069 /// [0x40, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,
1070 /// 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1071 /// );
1072 /// assert_eq!(value, 12.5);
1073 /// # }
1074 /// ```
1075 #[inline]
1076 #[must_use]
1077 #[unstable(feature = "f128", issue = "116909")]
1078 pub const fn from_be_bytes(bytes: [u8; 16]) -> Self {
1079 Self::from_bits(u128::from_be_bytes(bytes))
1080 }
1081
1082 /// Creates a floating point value from its representation as a byte array in little endian.
1083 ///
1084 /// See [`from_bits`](Self::from_bits) for some discussion of the
1085 /// portability of this operation (there are almost no issues).
1086 ///
1087 /// # Examples
1088 ///
1089 /// ```
1090 /// #![feature(f128)]
1091 /// # // FIXME(f16_f128): remove when `eqtf2` is available
1092 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1093 ///
1094 /// let value = f128::from_le_bytes(
1095 /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1096 /// 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x02, 0x40]
1097 /// );
1098 /// assert_eq!(value, 12.5);
1099 /// # }
1100 /// ```
1101 #[inline]
1102 #[must_use]
1103 #[unstable(feature = "f128", issue = "116909")]
1104 pub const fn from_le_bytes(bytes: [u8; 16]) -> Self {
1105 Self::from_bits(u128::from_le_bytes(bytes))
1106 }
1107
1108 /// Creates a floating point value from its representation as a byte array in native endian.
1109 ///
1110 /// As the target platform's native endianness is used, portable code
1111 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1112 /// appropriate instead.
1113 ///
1114 /// [`from_be_bytes`]: f128::from_be_bytes
1115 /// [`from_le_bytes`]: f128::from_le_bytes
1116 ///
1117 /// See [`from_bits`](Self::from_bits) for some discussion of the
1118 /// portability of this operation (there are almost no issues).
1119 ///
1120 /// # Examples
1121 ///
1122 /// ```
1123 /// #![feature(f128)]
1124 /// # // FIXME(f16_f128): remove when `eqtf2` is available
1125 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1126 ///
1127 /// let value = f128::from_ne_bytes(if cfg!(target_endian = "big") {
1128 /// [0x40, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,
1129 /// 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1130 /// } else {
1131 /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1132 /// 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x02, 0x40]
1133 /// });
1134 /// assert_eq!(value, 12.5);
1135 /// # }
1136 /// ```
1137 #[inline]
1138 #[must_use]
1139 #[unstable(feature = "f128", issue = "116909")]
1140 pub const fn from_ne_bytes(bytes: [u8; 16]) -> Self {
1141 Self::from_bits(u128::from_ne_bytes(bytes))
1142 }
1143
1144 /// Returns the ordering between `self` and `other`.
1145 ///
1146 /// Unlike the standard partial comparison between floating point numbers,
1147 /// this comparison always produces an ordering in accordance to
1148 /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1149 /// floating point standard. The values are ordered in the following sequence:
1150 ///
1151 /// - negative quiet NaN
1152 /// - negative signaling NaN
1153 /// - negative infinity
1154 /// - negative numbers
1155 /// - negative subnormal numbers
1156 /// - negative zero
1157 /// - positive zero
1158 /// - positive subnormal numbers
1159 /// - positive numbers
1160 /// - positive infinity
1161 /// - positive signaling NaN
1162 /// - positive quiet NaN.
1163 ///
1164 /// The ordering established by this function does not always agree with the
1165 /// [`PartialOrd`] and [`PartialEq`] implementations of `f128`. For example,
1166 /// they consider negative and positive zero equal, while `total_cmp`
1167 /// doesn't.
1168 ///
1169 /// The interpretation of the signaling NaN bit follows the definition in
1170 /// the IEEE 754 standard, which may not match the interpretation by some of
1171 /// the older, non-conformant (e.g. MIPS) hardware implementations.
1172 ///
1173 /// # Example
1174 ///
1175 /// ```
1176 /// #![feature(f128)]
1177 ///
1178 /// struct GoodBoy {
1179 /// name: &'static str,
1180 /// weight: f128,
1181 /// }
1182 ///
1183 /// let mut bois = vec![
1184 /// GoodBoy { name: "Pucci", weight: 0.1 },
1185 /// GoodBoy { name: "Woofer", weight: 99.0 },
1186 /// GoodBoy { name: "Yapper", weight: 10.0 },
1187 /// GoodBoy { name: "Chonk", weight: f128::INFINITY },
1188 /// GoodBoy { name: "Abs. Unit", weight: f128::NAN },
1189 /// GoodBoy { name: "Floaty", weight: -5.0 },
1190 /// ];
1191 ///
1192 /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1193 ///
1194 /// // `f128::NAN` could be positive or negative, which will affect the sort order.
1195 /// if f128::NAN.is_sign_negative() {
1196 /// bois.into_iter().map(|b| b.weight)
1197 /// .zip([f128::NAN, -5.0, 0.1, 10.0, 99.0, f128::INFINITY].iter())
1198 /// .for_each(|(a, b)| assert_eq!(a.to_bits(), b.to_bits()))
1199 /// } else {
1200 /// bois.into_iter().map(|b| b.weight)
1201 /// .zip([-5.0, 0.1, 10.0, 99.0, f128::INFINITY, f128::NAN].iter())
1202 /// .for_each(|(a, b)| assert_eq!(a.to_bits(), b.to_bits()))
1203 /// }
1204 /// ```
1205 #[inline]
1206 #[must_use]
1207 #[unstable(feature = "f128", issue = "116909")]
1208 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1209 pub const fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1210 let mut left = self.to_bits() as i128;
1211 let mut right = other.to_bits() as i128;
1212
1213 // In case of negatives, flip all the bits except the sign
1214 // to achieve a similar layout as two's complement integers
1215 //
1216 // Why does this work? IEEE 754 floats consist of three fields:
1217 // Sign bit, exponent and mantissa. The set of exponent and mantissa
1218 // fields as a whole have the property that their bitwise order is
1219 // equal to the numeric magnitude where the magnitude is defined.
1220 // The magnitude is not normally defined on NaN values, but
1221 // IEEE 754 totalOrder defines the NaN values also to follow the
1222 // bitwise order. This leads to order explained in the doc comment.
1223 // However, the representation of magnitude is the same for negative
1224 // and positive numbers – only the sign bit is different.
1225 // To easily compare the floats as signed integers, we need to
1226 // flip the exponent and mantissa bits in case of negative numbers.
1227 // We effectively convert the numbers to "two's complement" form.
1228 //
1229 // To do the flipping, we construct a mask and XOR against it.
1230 // We branchlessly calculate an "all-ones except for the sign bit"
1231 // mask from negative-signed values: right shifting sign-extends
1232 // the integer, so we "fill" the mask with sign bits, and then
1233 // convert to unsigned to push one more zero bit.
1234 // On positive values, the mask is all zeros, so it's a no-op.
1235 left ^= (((left >> 127) as u128) >> 1) as i128;
1236 right ^= (((right >> 127) as u128) >> 1) as i128;
1237
1238 left.cmp(&right)
1239 }
1240
1241 /// Restrict a value to a certain interval unless it is NaN.
1242 ///
1243 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1244 /// less than `min`. Otherwise this returns `self`.
1245 ///
1246 /// Note that this function returns NaN if the initial value was NaN as
1247 /// well. If the result is zero and among the three inputs `self`, `min`, and `max` there are
1248 /// zeros with different sign, either `0.0` or `-0.0` is returned non-deterministically.
1249 ///
1250 /// # Panics
1251 ///
1252 /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1253 ///
1254 /// # Examples
1255 ///
1256 /// ```
1257 /// #![feature(f128)]
1258 /// # // FIXME(f16_f128): remove when `{eq,gt,unord}tf` are available
1259 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1260 ///
1261 /// assert!((-3.0f128).clamp(-2.0, 1.0) == -2.0);
1262 /// assert!((0.0f128).clamp(-2.0, 1.0) == 0.0);
1263 /// assert!((2.0f128).clamp(-2.0, 1.0) == 1.0);
1264 /// assert!((f128::NAN).clamp(-2.0, 1.0).is_nan());
1265 ///
1266 /// // These always returns zero, but the sign (which is ignored by `==`) is non-deterministic.
1267 /// assert!((0.0f128).clamp(-0.0, -0.0) == 0.0);
1268 /// assert!((1.0f128).clamp(-0.0, 0.0) == 0.0);
1269 /// // This is definitely a negative zero.
1270 /// assert!((-1.0f128).clamp(-0.0, 1.0).is_sign_negative());
1271 /// # }
1272 /// ```
1273 #[inline]
1274 #[unstable(feature = "f128", issue = "116909")]
1275 #[must_use = "method returns a new number and does not mutate the original value"]
1276 pub const fn clamp(mut self, min: f128, max: f128) -> f128 {
1277 const_assert!(
1278 min <= max,
1279 "min > max, or either was NaN",
1280 "min > max, or either was NaN. min = {min:?}, max = {max:?}",
1281 min: f128,
1282 max: f128,
1283 );
1284
1285 if self < min {
1286 self = min;
1287 }
1288 if self > max {
1289 self = max;
1290 }
1291 self
1292 }
1293
1294 /// Computes the absolute value of `self`.
1295 ///
1296 /// This function always returns the precise result.
1297 ///
1298 /// # Examples
1299 ///
1300 /// ```
1301 /// #![feature(f128)]
1302 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1303 ///
1304 /// let x = 3.5_f128;
1305 /// let y = -3.5_f128;
1306 ///
1307 /// assert_eq!(x.abs(), x);
1308 /// assert_eq!(y.abs(), -y);
1309 ///
1310 /// assert!(f128::NAN.abs().is_nan());
1311 /// # }
1312 /// ```
1313 #[inline]
1314 #[unstable(feature = "f128", issue = "116909")]
1315 #[rustc_const_unstable(feature = "f128", issue = "116909")]
1316 #[must_use = "method returns a new number and does not mutate the original value"]
1317 pub const fn abs(self) -> Self {
1318 // FIXME(f16_f128): replace with `intrinsics::fabsf128` when available
1319 // We don't do this now because LLVM has lowering bugs for f128 math.
1320 Self::from_bits(self.to_bits() & !(1 << 127))
1321 }
1322
1323 /// Returns a number that represents the sign of `self`.
1324 ///
1325 /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
1326 /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
1327 /// - NaN if the number is NaN
1328 ///
1329 /// # Examples
1330 ///
1331 /// ```
1332 /// #![feature(f128)]
1333 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1334 ///
1335 /// let f = 3.5_f128;
1336 ///
1337 /// assert_eq!(f.signum(), 1.0);
1338 /// assert_eq!(f128::NEG_INFINITY.signum(), -1.0);
1339 ///
1340 /// assert!(f128::NAN.signum().is_nan());
1341 /// # }
1342 /// ```
1343 #[inline]
1344 #[unstable(feature = "f128", issue = "116909")]
1345 #[rustc_const_unstable(feature = "f128", issue = "116909")]
1346 #[must_use = "method returns a new number and does not mutate the original value"]
1347 pub const fn signum(self) -> f128 {
1348 if self.is_nan() { Self::NAN } else { 1.0_f128.copysign(self) }
1349 }
1350
1351 /// Returns a number composed of the magnitude of `self` and the sign of
1352 /// `sign`.
1353 ///
1354 /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`.
1355 /// If `self` is a NaN, then a NaN with the same payload as `self` and the sign bit of `sign` is
1356 /// returned.
1357 ///
1358 /// If `sign` is a NaN, then this operation will still carry over its sign into the result. Note
1359 /// that IEEE 754 doesn't assign any meaning to the sign bit in case of a NaN, and as Rust
1360 /// doesn't guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the
1361 /// result of `copysign` with `sign` being a NaN might produce an unexpected or non-portable
1362 /// result. See the [specification of NaN bit patterns](primitive@f32#nan-bit-patterns) for more
1363 /// info.
1364 ///
1365 /// # Examples
1366 ///
1367 /// ```
1368 /// #![feature(f128)]
1369 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1370 ///
1371 /// let f = 3.5_f128;
1372 ///
1373 /// assert_eq!(f.copysign(0.42), 3.5_f128);
1374 /// assert_eq!(f.copysign(-0.42), -3.5_f128);
1375 /// assert_eq!((-f).copysign(0.42), 3.5_f128);
1376 /// assert_eq!((-f).copysign(-0.42), -3.5_f128);
1377 ///
1378 /// assert!(f128::NAN.copysign(1.0).is_nan());
1379 /// # }
1380 /// ```
1381 #[inline]
1382 #[unstable(feature = "f128", issue = "116909")]
1383 #[rustc_const_unstable(feature = "f128", issue = "116909")]
1384 #[must_use = "method returns a new number and does not mutate the original value"]
1385 pub const fn copysign(self, sign: f128) -> f128 {
1386 intrinsics::copysignf128(self, sign)
1387 }
1388
1389 /// Float addition that allows optimizations based on algebraic rules.
1390 ///
1391 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1392 #[must_use = "method returns a new number and does not mutate the original value"]
1393 #[unstable(feature = "float_algebraic", issue = "136469")]
1394 #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1395 #[inline]
1396 pub const fn algebraic_add(self, rhs: f128) -> f128 {
1397 intrinsics::fadd_algebraic(self, rhs)
1398 }
1399
1400 /// Float subtraction that allows optimizations based on algebraic rules.
1401 ///
1402 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1403 #[must_use = "method returns a new number and does not mutate the original value"]
1404 #[unstable(feature = "float_algebraic", issue = "136469")]
1405 #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1406 #[inline]
1407 pub const fn algebraic_sub(self, rhs: f128) -> f128 {
1408 intrinsics::fsub_algebraic(self, rhs)
1409 }
1410
1411 /// Float multiplication that allows optimizations based on algebraic rules.
1412 ///
1413 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1414 #[must_use = "method returns a new number and does not mutate the original value"]
1415 #[unstable(feature = "float_algebraic", issue = "136469")]
1416 #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1417 #[inline]
1418 pub const fn algebraic_mul(self, rhs: f128) -> f128 {
1419 intrinsics::fmul_algebraic(self, rhs)
1420 }
1421
1422 /// Float division that allows optimizations based on algebraic rules.
1423 ///
1424 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1425 #[must_use = "method returns a new number and does not mutate the original value"]
1426 #[unstable(feature = "float_algebraic", issue = "136469")]
1427 #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1428 #[inline]
1429 pub const fn algebraic_div(self, rhs: f128) -> f128 {
1430 intrinsics::fdiv_algebraic(self, rhs)
1431 }
1432
1433 /// Float remainder that allows optimizations based on algebraic rules.
1434 ///
1435 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1436 #[must_use = "method returns a new number and does not mutate the original value"]
1437 #[unstable(feature = "float_algebraic", issue = "136469")]
1438 #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1439 #[inline]
1440 pub const fn algebraic_rem(self, rhs: f128) -> f128 {
1441 intrinsics::frem_algebraic(self, rhs)
1442 }
1443}
1444
1445// Functions in this module fall into `core_float_math`
1446// FIXME(f16_f128): all doctests must be gated to platforms that have `long double` === `_Float128`
1447// due to https://github.com/llvm/llvm-project/issues/44744. aarch64 linux matches this.
1448// #[unstable(feature = "core_float_math", issue = "137578")]
1449#[cfg(not(test))]
1450#[doc(test(attr(feature(cfg_target_has_reliable_f16_f128), expect(internal_features))))]
1451impl f128 {
1452 /// Returns the largest integer less than or equal to `self`.
1453 ///
1454 /// This function always returns the precise result.
1455 ///
1456 /// # Examples
1457 ///
1458 /// ```
1459 /// #![feature(f128)]
1460 /// # #[cfg(not(miri))]
1461 /// # #[cfg(target_has_reliable_f128_math)] {
1462 ///
1463 /// let f = 3.7_f128;
1464 /// let g = 3.0_f128;
1465 /// let h = -3.7_f128;
1466 ///
1467 /// assert_eq!(f.floor(), 3.0);
1468 /// assert_eq!(g.floor(), 3.0);
1469 /// assert_eq!(h.floor(), -4.0);
1470 /// # }
1471 /// ```
1472 #[inline]
1473 #[rustc_allow_incoherent_impl]
1474 #[unstable(feature = "f128", issue = "116909")]
1475 #[rustc_const_unstable(feature = "f128", issue = "116909")]
1476 #[must_use = "method returns a new number and does not mutate the original value"]
1477 pub const fn floor(self) -> f128 {
1478 intrinsics::floorf128(self)
1479 }
1480
1481 /// Returns the smallest integer greater than or equal to `self`.
1482 ///
1483 /// This function always returns the precise result.
1484 ///
1485 /// # Examples
1486 ///
1487 /// ```
1488 /// #![feature(f128)]
1489 /// # #[cfg(not(miri))]
1490 /// # #[cfg(target_has_reliable_f128_math)] {
1491 ///
1492 /// let f = 3.01_f128;
1493 /// let g = 4.0_f128;
1494 ///
1495 /// assert_eq!(f.ceil(), 4.0);
1496 /// assert_eq!(g.ceil(), 4.0);
1497 /// # }
1498 /// ```
1499 #[inline]
1500 #[doc(alias = "ceiling")]
1501 #[rustc_allow_incoherent_impl]
1502 #[unstable(feature = "f128", issue = "116909")]
1503 #[rustc_const_unstable(feature = "f128", issue = "116909")]
1504 #[must_use = "method returns a new number and does not mutate the original value"]
1505 pub const fn ceil(self) -> f128 {
1506 intrinsics::ceilf128(self)
1507 }
1508
1509 /// Returns the nearest integer to `self`. If a value is half-way between two
1510 /// integers, round away from `0.0`.
1511 ///
1512 /// This function always returns the precise result.
1513 ///
1514 /// # Examples
1515 ///
1516 /// ```
1517 /// #![feature(f128)]
1518 /// # #[cfg(not(miri))]
1519 /// # #[cfg(target_has_reliable_f128_math)] {
1520 ///
1521 /// let f = 3.3_f128;
1522 /// let g = -3.3_f128;
1523 /// let h = -3.7_f128;
1524 /// let i = 3.5_f128;
1525 /// let j = 4.5_f128;
1526 ///
1527 /// assert_eq!(f.round(), 3.0);
1528 /// assert_eq!(g.round(), -3.0);
1529 /// assert_eq!(h.round(), -4.0);
1530 /// assert_eq!(i.round(), 4.0);
1531 /// assert_eq!(j.round(), 5.0);
1532 /// # }
1533 /// ```
1534 #[inline]
1535 #[rustc_allow_incoherent_impl]
1536 #[unstable(feature = "f128", issue = "116909")]
1537 #[rustc_const_unstable(feature = "f128", issue = "116909")]
1538 #[must_use = "method returns a new number and does not mutate the original value"]
1539 pub const fn round(self) -> f128 {
1540 intrinsics::roundf128(self)
1541 }
1542
1543 /// Returns the nearest integer to a number. Rounds half-way cases to the number
1544 /// with an even least significant digit.
1545 ///
1546 /// This function always returns the precise result.
1547 ///
1548 /// # Examples
1549 ///
1550 /// ```
1551 /// #![feature(f128)]
1552 /// # #[cfg(not(miri))]
1553 /// # #[cfg(target_has_reliable_f128_math)] {
1554 ///
1555 /// let f = 3.3_f128;
1556 /// let g = -3.3_f128;
1557 /// let h = 3.5_f128;
1558 /// let i = 4.5_f128;
1559 ///
1560 /// assert_eq!(f.round_ties_even(), 3.0);
1561 /// assert_eq!(g.round_ties_even(), -3.0);
1562 /// assert_eq!(h.round_ties_even(), 4.0);
1563 /// assert_eq!(i.round_ties_even(), 4.0);
1564 /// # }
1565 /// ```
1566 #[inline]
1567 #[rustc_allow_incoherent_impl]
1568 #[unstable(feature = "f128", issue = "116909")]
1569 #[rustc_const_unstable(feature = "f128", issue = "116909")]
1570 #[must_use = "method returns a new number and does not mutate the original value"]
1571 pub const fn round_ties_even(self) -> f128 {
1572 intrinsics::round_ties_even_f128(self)
1573 }
1574
1575 /// Returns the integer part of `self`.
1576 /// This means that non-integer numbers are always truncated towards zero.
1577 ///
1578 /// This function always returns the precise result.
1579 ///
1580 /// # Examples
1581 ///
1582 /// ```
1583 /// #![feature(f128)]
1584 /// # #[cfg(not(miri))]
1585 /// # #[cfg(target_has_reliable_f128_math)] {
1586 ///
1587 /// let f = 3.7_f128;
1588 /// let g = 3.0_f128;
1589 /// let h = -3.7_f128;
1590 ///
1591 /// assert_eq!(f.trunc(), 3.0);
1592 /// assert_eq!(g.trunc(), 3.0);
1593 /// assert_eq!(h.trunc(), -3.0);
1594 /// # }
1595 /// ```
1596 #[inline]
1597 #[doc(alias = "truncate")]
1598 #[rustc_allow_incoherent_impl]
1599 #[unstable(feature = "f128", issue = "116909")]
1600 #[rustc_const_unstable(feature = "f128", issue = "116909")]
1601 #[must_use = "method returns a new number and does not mutate the original value"]
1602 pub const fn trunc(self) -> f128 {
1603 intrinsics::truncf128(self)
1604 }
1605
1606 /// Returns the fractional part of `self`.
1607 ///
1608 /// This function always returns the precise result.
1609 ///
1610 /// # Examples
1611 ///
1612 /// ```
1613 /// #![feature(f128)]
1614 /// # #[cfg(not(miri))]
1615 /// # #[cfg(target_has_reliable_f128_math)] {
1616 ///
1617 /// let x = 3.6_f128;
1618 /// let y = -3.6_f128;
1619 /// let abs_difference_x = (x.fract() - 0.6).abs();
1620 /// let abs_difference_y = (y.fract() - (-0.6)).abs();
1621 ///
1622 /// assert!(abs_difference_x <= f128::EPSILON);
1623 /// assert!(abs_difference_y <= f128::EPSILON);
1624 /// # }
1625 /// ```
1626 #[inline]
1627 #[rustc_allow_incoherent_impl]
1628 #[unstable(feature = "f128", issue = "116909")]
1629 #[rustc_const_unstable(feature = "f128", issue = "116909")]
1630 #[must_use = "method returns a new number and does not mutate the original value"]
1631 pub const fn fract(self) -> f128 {
1632 self - self.trunc()
1633 }
1634
1635 /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
1636 /// error, yielding a more accurate result than an unfused multiply-add.
1637 ///
1638 /// Using `mul_add` *may* be more performant than an unfused multiply-add if
1639 /// the target architecture has a dedicated `fma` CPU instruction. However,
1640 /// this is not always true, and will be heavily dependant on designing
1641 /// algorithms with specific target hardware in mind.
1642 ///
1643 /// # Precision
1644 ///
1645 /// The result of this operation is guaranteed to be the rounded
1646 /// infinite-precision result. It is specified by IEEE 754 as
1647 /// `fusedMultiplyAdd` and guaranteed not to change.
1648 ///
1649 /// # Examples
1650 ///
1651 /// ```
1652 /// #![feature(f128)]
1653 /// # #[cfg(not(miri))]
1654 /// # #[cfg(target_has_reliable_f128_math)] {
1655 ///
1656 /// let m = 10.0_f128;
1657 /// let x = 4.0_f128;
1658 /// let b = 60.0_f128;
1659 ///
1660 /// assert_eq!(m.mul_add(x, b), 100.0);
1661 /// assert_eq!(m * x + b, 100.0);
1662 ///
1663 /// let one_plus_eps = 1.0_f128 + f128::EPSILON;
1664 /// let one_minus_eps = 1.0_f128 - f128::EPSILON;
1665 /// let minus_one = -1.0_f128;
1666 ///
1667 /// // The exact result (1 + eps) * (1 - eps) = 1 - eps * eps.
1668 /// assert_eq!(one_plus_eps.mul_add(one_minus_eps, minus_one), -f128::EPSILON * f128::EPSILON);
1669 /// // Different rounding with the non-fused multiply and add.
1670 /// assert_eq!(one_plus_eps * one_minus_eps + minus_one, 0.0);
1671 /// # }
1672 /// ```
1673 #[inline]
1674 #[rustc_allow_incoherent_impl]
1675 #[doc(alias = "fmaf128", alias = "fusedMultiplyAdd")]
1676 #[unstable(feature = "f128", issue = "116909")]
1677 #[must_use = "method returns a new number and does not mutate the original value"]
1678 #[rustc_const_unstable(feature = "const_mul_add", issue = "146724")]
1679 pub const fn mul_add(self, a: f128, b: f128) -> f128 {
1680 intrinsics::fmaf128(self, a, b)
1681 }
1682
1683 /// Calculates Euclidean division, the matching method for `rem_euclid`.
1684 ///
1685 /// This computes the integer `n` such that
1686 /// `self = n * rhs + self.rem_euclid(rhs)`.
1687 /// In other words, the result is `self / rhs` rounded to the integer `n`
1688 /// such that `self >= n * rhs`.
1689 ///
1690 /// # Precision
1691 ///
1692 /// The result of this operation is guaranteed to be the rounded
1693 /// infinite-precision result.
1694 ///
1695 /// # Examples
1696 ///
1697 /// ```
1698 /// #![feature(f128)]
1699 /// # #[cfg(not(miri))]
1700 /// # #[cfg(target_has_reliable_f128_math)] {
1701 ///
1702 /// let a: f128 = 7.0;
1703 /// let b = 4.0;
1704 /// assert_eq!(a.div_euclid(b), 1.0); // 7.0 > 4.0 * 1.0
1705 /// assert_eq!((-a).div_euclid(b), -2.0); // -7.0 >= 4.0 * -2.0
1706 /// assert_eq!(a.div_euclid(-b), -1.0); // 7.0 >= -4.0 * -1.0
1707 /// assert_eq!((-a).div_euclid(-b), 2.0); // -7.0 >= -4.0 * 2.0
1708 /// # }
1709 /// ```
1710 #[inline]
1711 #[rustc_allow_incoherent_impl]
1712 #[unstable(feature = "f128", issue = "116909")]
1713 #[must_use = "method returns a new number and does not mutate the original value"]
1714 pub fn div_euclid(self, rhs: f128) -> f128 {
1715 let q = (self / rhs).trunc();
1716 if self % rhs < 0.0 {
1717 return if rhs > 0.0 { q - 1.0 } else { q + 1.0 };
1718 }
1719 q
1720 }
1721
1722 /// Calculates the least nonnegative remainder of `self (mod rhs)`.
1723 ///
1724 /// In particular, the return value `r` satisfies `0.0 <= r < rhs.abs()` in
1725 /// most cases. However, due to a floating point round-off error it can
1726 /// result in `r == rhs.abs()`, violating the mathematical definition, if
1727 /// `self` is much smaller than `rhs.abs()` in magnitude and `self < 0.0`.
1728 /// This result is not an element of the function's codomain, but it is the
1729 /// closest floating point number in the real numbers and thus fulfills the
1730 /// property `self == self.div_euclid(rhs) * rhs + self.rem_euclid(rhs)`
1731 /// approximately.
1732 ///
1733 /// # Precision
1734 ///
1735 /// The result of this operation is guaranteed to be the rounded
1736 /// infinite-precision result.
1737 ///
1738 /// # Examples
1739 ///
1740 /// ```
1741 /// #![feature(f128)]
1742 /// # #[cfg(not(miri))]
1743 /// # #[cfg(target_has_reliable_f128_math)] {
1744 ///
1745 /// let a: f128 = 7.0;
1746 /// let b = 4.0;
1747 /// assert_eq!(a.rem_euclid(b), 3.0);
1748 /// assert_eq!((-a).rem_euclid(b), 1.0);
1749 /// assert_eq!(a.rem_euclid(-b), 3.0);
1750 /// assert_eq!((-a).rem_euclid(-b), 1.0);
1751 /// // limitation due to round-off error
1752 /// assert!((-f128::EPSILON).rem_euclid(3.0) != 0.0);
1753 /// # }
1754 /// ```
1755 #[inline]
1756 #[rustc_allow_incoherent_impl]
1757 #[doc(alias = "modulo", alias = "mod")]
1758 #[unstable(feature = "f128", issue = "116909")]
1759 #[must_use = "method returns a new number and does not mutate the original value"]
1760 pub fn rem_euclid(self, rhs: f128) -> f128 {
1761 let r = self % rhs;
1762 if r < 0.0 { r + rhs.abs() } else { r }
1763 }
1764
1765 /// Raises a number to an integer power.
1766 ///
1767 /// Using this function is generally faster than using `powf`.
1768 /// It might have a different sequence of rounding operations than `powf`,
1769 /// so the results are not guaranteed to agree.
1770 ///
1771 /// # Unspecified precision
1772 ///
1773 /// The precision of this function is non-deterministic. This means it varies by platform,
1774 /// Rust version, and can even differ within the same execution from one invocation to the next.
1775 ///
1776 /// # Examples
1777 ///
1778 /// ```
1779 /// #![feature(f128)]
1780 /// # #[cfg(not(miri))]
1781 /// # #[cfg(target_has_reliable_f128_math)] {
1782 ///
1783 /// let x = 2.0_f128;
1784 /// let abs_difference = (x.powi(2) - (x * x)).abs();
1785 /// assert!(abs_difference <= f128::EPSILON);
1786 ///
1787 /// assert_eq!(f128::powi(f128::NAN, 0), 1.0);
1788 /// assert_eq!(f128::powi(0.0, 0), 1.0);
1789 /// # }
1790 /// ```
1791 #[inline]
1792 #[rustc_allow_incoherent_impl]
1793 #[unstable(feature = "f128", issue = "116909")]
1794 #[must_use = "method returns a new number and does not mutate the original value"]
1795 pub fn powi(self, n: i32) -> f128 {
1796 intrinsics::powif128(self, n)
1797 }
1798
1799 /// Returns the square root of a number.
1800 ///
1801 /// Returns NaN if `self` is a negative number other than `-0.0`.
1802 ///
1803 /// # Precision
1804 ///
1805 /// The result of this operation is guaranteed to be the rounded
1806 /// infinite-precision result. It is specified by IEEE 754 as `squareRoot`
1807 /// and guaranteed not to change.
1808 ///
1809 /// # Examples
1810 ///
1811 /// ```
1812 /// #![feature(f128)]
1813 /// # #[cfg(not(miri))]
1814 /// # #[cfg(target_has_reliable_f128_math)] {
1815 ///
1816 /// let positive = 4.0_f128;
1817 /// let negative = -4.0_f128;
1818 /// let negative_zero = -0.0_f128;
1819 ///
1820 /// assert_eq!(positive.sqrt(), 2.0);
1821 /// assert!(negative.sqrt().is_nan());
1822 /// assert!(negative_zero.sqrt() == negative_zero);
1823 /// # }
1824 /// ```
1825 #[inline]
1826 #[doc(alias = "squareRoot")]
1827 #[rustc_allow_incoherent_impl]
1828 #[unstable(feature = "f128", issue = "116909")]
1829 #[must_use = "method returns a new number and does not mutate the original value"]
1830 pub fn sqrt(self) -> f128 {
1831 intrinsics::sqrtf128(self)
1832 }
1833}