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