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