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