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 #[inline]
1050 #[unstable(feature = "f128", issue = "116909")]
1051 #[must_use = "this returns the result of the operation, without modifying the original"]
1052 #[allow(unnecessary_transmutes)]
1053 pub const fn to_bits(self) -> u128 {
1054 // SAFETY: `u128` is a plain old datatype so we can always transmute to it.
1055 unsafe { mem::transmute(self) }
1056 }
1057
1058 /// Raw transmutation from `u128`.
1059 ///
1060 /// This is currently identical to `transmute::<u128, f128>(v)` on all platforms.
1061 /// It turns out this is incredibly portable, for two reasons:
1062 ///
1063 /// * Floats and Ints have the same endianness on all supported platforms.
1064 /// * IEEE 754 very precisely specifies the bit layout of floats.
1065 ///
1066 /// However there is one caveat: prior to the 2008 version of IEEE 754, how
1067 /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
1068 /// (notably x86 and ARM) picked the interpretation that was ultimately
1069 /// standardized in 2008, but some didn't (notably MIPS). As a result, all
1070 /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
1071 ///
1072 /// Rather than trying to preserve signaling-ness cross-platform, this
1073 /// implementation favors preserving the exact bits. This means that
1074 /// any payloads encoded in NaNs will be preserved even if the result of
1075 /// this method is sent over the network from an x86 machine to a MIPS one.
1076 ///
1077 /// If the results of this method are only manipulated by the same
1078 /// architecture that produced them, then there is no portability concern.
1079 ///
1080 /// If the input isn't NaN, then there is no portability concern.
1081 ///
1082 /// If you don't care about signalingness (very likely), then there is no
1083 /// portability concern.
1084 ///
1085 /// Note that this function is distinct from `as` casting, which attempts to
1086 /// preserve the *numeric* value, and not the bitwise value.
1087 ///
1088 /// ```
1089 /// #![feature(f128)]
1090 /// # #[cfg(target_has_reliable_f128)] {
1091 ///
1092 /// let v = f128::from_bits(0x40029000000000000000000000000000);
1093 /// assert_eq!(v, 12.5);
1094 /// # }
1095 /// ```
1096 #[inline]
1097 #[must_use]
1098 #[unstable(feature = "f128", issue = "116909")]
1099 #[allow(unnecessary_transmutes)]
1100 pub const fn from_bits(v: u128) -> Self {
1101 // It turns out the safety issues with sNaN were overblown! Hooray!
1102 // SAFETY: `u128` is a plain old datatype so we can always transmute from it.
1103 unsafe { mem::transmute(v) }
1104 }
1105
1106 /// Returns the memory representation of this floating point number as a byte array in
1107 /// big-endian (network) byte order.
1108 ///
1109 /// See [`from_bits`](Self::from_bits) for some discussion of the
1110 /// portability of this operation (there are almost no issues).
1111 ///
1112 /// # Examples
1113 ///
1114 /// ```
1115 /// #![feature(f128)]
1116 ///
1117 /// let bytes = 12.5f128.to_be_bytes();
1118 /// assert_eq!(
1119 /// bytes,
1120 /// [0x40, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,
1121 /// 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1122 /// );
1123 /// ```
1124 #[inline]
1125 #[unstable(feature = "f128", issue = "116909")]
1126 #[must_use = "this returns the result of the operation, without modifying the original"]
1127 pub const fn to_be_bytes(self) -> [u8; 16] {
1128 self.to_bits().to_be_bytes()
1129 }
1130
1131 /// Returns the memory representation of this floating point number as a byte array in
1132 /// little-endian byte order.
1133 ///
1134 /// See [`from_bits`](Self::from_bits) for some discussion of the
1135 /// portability of this operation (there are almost no issues).
1136 ///
1137 /// # Examples
1138 ///
1139 /// ```
1140 /// #![feature(f128)]
1141 ///
1142 /// let bytes = 12.5f128.to_le_bytes();
1143 /// assert_eq!(
1144 /// bytes,
1145 /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1146 /// 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x02, 0x40]
1147 /// );
1148 /// ```
1149 #[inline]
1150 #[unstable(feature = "f128", issue = "116909")]
1151 #[must_use = "this returns the result of the operation, without modifying the original"]
1152 pub const fn to_le_bytes(self) -> [u8; 16] {
1153 self.to_bits().to_le_bytes()
1154 }
1155
1156 /// Returns the memory representation of this floating point number as a byte array in
1157 /// native byte order.
1158 ///
1159 /// As the target platform's native endianness is used, portable code
1160 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1161 ///
1162 /// [`to_be_bytes`]: f128::to_be_bytes
1163 /// [`to_le_bytes`]: f128::to_le_bytes
1164 ///
1165 /// See [`from_bits`](Self::from_bits) for some discussion of the
1166 /// portability of this operation (there are almost no issues).
1167 ///
1168 /// # Examples
1169 ///
1170 /// ```
1171 /// #![feature(f128)]
1172 ///
1173 /// let bytes = 12.5f128.to_ne_bytes();
1174 /// assert_eq!(
1175 /// bytes,
1176 /// if cfg!(target_endian = "big") {
1177 /// [0x40, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,
1178 /// 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1179 /// } else {
1180 /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1181 /// 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x02, 0x40]
1182 /// }
1183 /// );
1184 /// ```
1185 #[inline]
1186 #[unstable(feature = "f128", issue = "116909")]
1187 #[must_use = "this returns the result of the operation, without modifying the original"]
1188 pub const fn to_ne_bytes(self) -> [u8; 16] {
1189 self.to_bits().to_ne_bytes()
1190 }
1191
1192 /// Creates a floating point value from its representation as a byte array in big endian.
1193 ///
1194 /// See [`from_bits`](Self::from_bits) for some discussion of the
1195 /// portability of this operation (there are almost no issues).
1196 ///
1197 /// # Examples
1198 ///
1199 /// ```
1200 /// #![feature(f128)]
1201 /// # #[cfg(target_has_reliable_f128)] {
1202 ///
1203 /// let value = f128::from_be_bytes(
1204 /// [0x40, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,
1205 /// 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1206 /// );
1207 /// assert_eq!(value, 12.5);
1208 /// # }
1209 /// ```
1210 #[inline]
1211 #[must_use]
1212 #[unstable(feature = "f128", issue = "116909")]
1213 pub const fn from_be_bytes(bytes: [u8; 16]) -> Self {
1214 Self::from_bits(u128::from_be_bytes(bytes))
1215 }
1216
1217 /// Creates a floating point value from its representation as a byte array in little endian.
1218 ///
1219 /// See [`from_bits`](Self::from_bits) for some discussion of the
1220 /// portability of this operation (there are almost no issues).
1221 ///
1222 /// # Examples
1223 ///
1224 /// ```
1225 /// #![feature(f128)]
1226 /// # #[cfg(target_has_reliable_f128)] {
1227 ///
1228 /// let value = f128::from_le_bytes(
1229 /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1230 /// 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x02, 0x40]
1231 /// );
1232 /// assert_eq!(value, 12.5);
1233 /// # }
1234 /// ```
1235 #[inline]
1236 #[must_use]
1237 #[unstable(feature = "f128", issue = "116909")]
1238 pub const fn from_le_bytes(bytes: [u8; 16]) -> Self {
1239 Self::from_bits(u128::from_le_bytes(bytes))
1240 }
1241
1242 /// Creates a floating point value from its representation as a byte array in native endian.
1243 ///
1244 /// As the target platform's native endianness is used, portable code
1245 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1246 /// appropriate instead.
1247 ///
1248 /// [`from_be_bytes`]: f128::from_be_bytes
1249 /// [`from_le_bytes`]: f128::from_le_bytes
1250 ///
1251 /// See [`from_bits`](Self::from_bits) for some discussion of the
1252 /// portability of this operation (there are almost no issues).
1253 ///
1254 /// # Examples
1255 ///
1256 /// ```
1257 /// #![feature(f128)]
1258 /// # #[cfg(target_has_reliable_f128)] {
1259 ///
1260 /// let value = f128::from_ne_bytes(if cfg!(target_endian = "big") {
1261 /// [0x40, 0x02, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00,
1262 /// 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1263 /// } else {
1264 /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1265 /// 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x02, 0x40]
1266 /// });
1267 /// assert_eq!(value, 12.5);
1268 /// # }
1269 /// ```
1270 #[inline]
1271 #[must_use]
1272 #[unstable(feature = "f128", issue = "116909")]
1273 pub const fn from_ne_bytes(bytes: [u8; 16]) -> Self {
1274 Self::from_bits(u128::from_ne_bytes(bytes))
1275 }
1276
1277 /// Returns the ordering between `self` and `other`.
1278 ///
1279 /// Unlike the standard partial comparison between floating point numbers,
1280 /// this comparison always produces an ordering in accordance to
1281 /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1282 /// floating point standard. The values are ordered in the following sequence:
1283 ///
1284 /// - negative quiet NaN
1285 /// - negative signaling NaN
1286 /// - negative infinity
1287 /// - negative numbers
1288 /// - negative subnormal numbers
1289 /// - negative zero
1290 /// - positive zero
1291 /// - positive subnormal numbers
1292 /// - positive numbers
1293 /// - positive infinity
1294 /// - positive signaling NaN
1295 /// - positive quiet NaN.
1296 ///
1297 /// The ordering established by this function does not always agree with the
1298 /// [`PartialOrd`] and [`PartialEq`] implementations of `f128`. For example,
1299 /// they consider negative and positive zero equal, while `total_cmp`
1300 /// doesn't.
1301 ///
1302 /// The interpretation of the signaling NaN bit follows the definition in
1303 /// the IEEE 754 standard, which may not match the interpretation by some of
1304 /// the older, non-conformant (e.g. MIPS) hardware implementations.
1305 ///
1306 /// # Example
1307 ///
1308 /// ```
1309 /// #![feature(f128)]
1310 ///
1311 /// struct GoodBoy {
1312 /// name: &'static str,
1313 /// weight: f128,
1314 /// }
1315 ///
1316 /// let mut bois = vec![
1317 /// GoodBoy { name: "Pucci", weight: 0.1 },
1318 /// GoodBoy { name: "Woofer", weight: 99.0 },
1319 /// GoodBoy { name: "Yapper", weight: 10.0 },
1320 /// GoodBoy { name: "Chonk", weight: f128::INFINITY },
1321 /// GoodBoy { name: "Abs. Unit", weight: f128::NAN },
1322 /// GoodBoy { name: "Floaty", weight: -5.0 },
1323 /// ];
1324 ///
1325 /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1326 ///
1327 /// // `f128::NAN` could be positive or negative, which will affect the sort order.
1328 /// if f128::NAN.is_sign_negative() {
1329 /// bois.into_iter().map(|b| b.weight)
1330 /// .zip([f128::NAN, -5.0, 0.1, 10.0, 99.0, f128::INFINITY].iter())
1331 /// .for_each(|(a, b)| assert_eq!(a.to_bits(), b.to_bits()))
1332 /// } else {
1333 /// bois.into_iter().map(|b| b.weight)
1334 /// .zip([-5.0, 0.1, 10.0, 99.0, f128::INFINITY, f128::NAN].iter())
1335 /// .for_each(|(a, b)| assert_eq!(a.to_bits(), b.to_bits()))
1336 /// }
1337 /// ```
1338 #[inline]
1339 #[must_use]
1340 #[unstable(feature = "f128", issue = "116909")]
1341 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1342 pub const fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1343 let mut left = self.to_bits() as i128;
1344 let mut right = other.to_bits() as i128;
1345
1346 // In case of negatives, flip all the bits except the sign
1347 // to achieve a similar layout as two's complement integers
1348 //
1349 // Why does this work? IEEE 754 floats consist of three fields:
1350 // Sign bit, exponent and mantissa. The set of exponent and mantissa
1351 // fields as a whole have the property that their bitwise order is
1352 // equal to the numeric magnitude where the magnitude is defined.
1353 // The magnitude is not normally defined on NaN values, but
1354 // IEEE 754 totalOrder defines the NaN values also to follow the
1355 // bitwise order. This leads to order explained in the doc comment.
1356 // However, the representation of magnitude is the same for negative
1357 // and positive numbers – only the sign bit is different.
1358 // To easily compare the floats as signed integers, we need to
1359 // flip the exponent and mantissa bits in case of negative numbers.
1360 // We effectively convert the numbers to "two's complement" form.
1361 //
1362 // To do the flipping, we construct a mask and XOR against it.
1363 // We branchlessly calculate an "all-ones except for the sign bit"
1364 // mask from negative-signed values: right shifting sign-extends
1365 // the integer, so we "fill" the mask with sign bits, and then
1366 // convert to unsigned to push one more zero bit.
1367 // On positive values, the mask is all zeros, so it's a no-op.
1368 left ^= (((left >> 127) as u128) >> 1) as i128;
1369 right ^= (((right >> 127) as u128) >> 1) as i128;
1370
1371 left.cmp(&right)
1372 }
1373
1374 /// Restrict a value to a certain interval unless it is NaN.
1375 ///
1376 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1377 /// less than `min`. Otherwise this returns `self`.
1378 ///
1379 /// Note that this function returns NaN if the initial value was NaN as
1380 /// well. If the result is zero and among the three inputs `self`, `min`, and `max` there are
1381 /// zeros with different sign, either `0.0` or `-0.0` is returned non-deterministically.
1382 ///
1383 /// # Panics
1384 ///
1385 /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1386 ///
1387 /// # Examples
1388 ///
1389 /// ```
1390 /// #![feature(f128)]
1391 /// # #[cfg(target_has_reliable_f128)] {
1392 ///
1393 /// assert!((-3.0f128).clamp(-2.0, 1.0) == -2.0);
1394 /// assert!((0.0f128).clamp(-2.0, 1.0) == 0.0);
1395 /// assert!((2.0f128).clamp(-2.0, 1.0) == 1.0);
1396 /// assert!((f128::NAN).clamp(-2.0, 1.0).is_nan());
1397 ///
1398 /// // These always returns zero, but the sign (which is ignored by `==`) is non-deterministic.
1399 /// assert!((0.0f128).clamp(-0.0, -0.0) == 0.0);
1400 /// assert!((1.0f128).clamp(-0.0, 0.0) == 0.0);
1401 /// // This is definitely a negative zero.
1402 /// assert!((-1.0f128).clamp(-0.0, 1.0).is_sign_negative());
1403 /// # }
1404 /// ```
1405 #[inline]
1406 #[unstable(feature = "f128", issue = "116909")]
1407 #[must_use = "method returns a new number and does not mutate the original value"]
1408 pub const fn clamp(mut self, min: f128, max: f128) -> f128 {
1409 const_assert!(
1410 min <= max,
1411 "min > max, or either was NaN",
1412 "min > max, or either was NaN. min = {min:?}, max = {max:?}",
1413 min: f128,
1414 max: f128,
1415 );
1416
1417 if self < min {
1418 self = min;
1419 }
1420 if self > max {
1421 self = max;
1422 }
1423 self
1424 }
1425
1426 /// Clamps this number to a symmetric range centered around zero.
1427 ///
1428 /// The method clamps the number's magnitude (absolute value) to be at most `limit`.
1429 ///
1430 /// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more
1431 /// explicit about the intent.
1432 ///
1433 /// # Panics
1434 ///
1435 /// Panics if `limit` is negative or NaN, as this indicates a logic error.
1436 ///
1437 /// # Examples
1438 ///
1439 /// ```
1440 /// #![feature(f128)]
1441 /// #![feature(clamp_magnitude)]
1442 /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1443 /// assert_eq!(5.0f128.clamp_magnitude(3.0), 3.0);
1444 /// assert_eq!((-5.0f128).clamp_magnitude(3.0), -3.0);
1445 /// assert_eq!(2.0f128.clamp_magnitude(3.0), 2.0);
1446 /// assert_eq!((-2.0f128).clamp_magnitude(3.0), -2.0);
1447 /// # }
1448 /// ```
1449 #[inline]
1450 #[unstable(feature = "clamp_magnitude", issue = "148519")]
1451 #[must_use = "this returns the clamped value and does not modify the original"]
1452 pub fn clamp_magnitude(self, limit: f128) -> f128 {
1453 assert!(limit >= 0.0, "limit must be non-negative");
1454 let limit = limit.abs(); // Canonicalises -0.0 to 0.0
1455 self.clamp(-limit, limit)
1456 }
1457
1458 /// Computes the absolute value of `self`.
1459 ///
1460 /// This function always returns the precise result.
1461 ///
1462 /// # Examples
1463 ///
1464 /// ```
1465 /// #![feature(f128)]
1466 /// # #[cfg(target_has_reliable_f128)] {
1467 ///
1468 /// let x = 3.5_f128;
1469 /// let y = -3.5_f128;
1470 ///
1471 /// assert_eq!(x.abs(), x);
1472 /// assert_eq!(y.abs(), -y);
1473 ///
1474 /// assert!(f128::NAN.abs().is_nan());
1475 /// # }
1476 /// ```
1477 #[inline]
1478 #[unstable(feature = "f128", issue = "116909")]
1479 #[rustc_const_unstable(feature = "f128", issue = "116909")]
1480 #[must_use = "method returns a new number and does not mutate the original value"]
1481 pub const fn abs(self) -> Self {
1482 intrinsics::fabs(self)
1483 }
1484
1485 /// Returns a number that represents the sign of `self`.
1486 ///
1487 /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
1488 /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
1489 /// - NaN if the number is NaN
1490 ///
1491 /// # Examples
1492 ///
1493 /// ```
1494 /// #![feature(f128)]
1495 /// # #[cfg(target_has_reliable_f128)] {
1496 ///
1497 /// let f = 3.5_f128;
1498 ///
1499 /// assert_eq!(f.signum(), 1.0);
1500 /// assert_eq!(f128::NEG_INFINITY.signum(), -1.0);
1501 ///
1502 /// assert!(f128::NAN.signum().is_nan());
1503 /// # }
1504 /// ```
1505 #[inline]
1506 #[unstable(feature = "f128", issue = "116909")]
1507 #[rustc_const_unstable(feature = "f128", issue = "116909")]
1508 #[must_use = "method returns a new number and does not mutate the original value"]
1509 pub const fn signum(self) -> f128 {
1510 if self.is_nan() { Self::NAN } else { 1.0_f128.copysign(self) }
1511 }
1512
1513 /// Returns a number composed of the magnitude of `self` and the sign of
1514 /// `sign`.
1515 ///
1516 /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`.
1517 /// If `self` is a NaN, then a NaN with the same payload as `self` and the sign bit of `sign` is
1518 /// returned.
1519 ///
1520 /// If `sign` is a NaN, then this operation will still carry over its sign into the result. Note
1521 /// that IEEE 754 doesn't assign any meaning to the sign bit in case of a NaN, and as Rust
1522 /// doesn't guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the
1523 /// result of `copysign` with `sign` being a NaN might produce an unexpected or non-portable
1524 /// result. See the [specification of NaN bit patterns](primitive@f32#nan-bit-patterns) for more
1525 /// info.
1526 ///
1527 /// # Examples
1528 ///
1529 /// ```
1530 /// #![feature(f128)]
1531 /// # #[cfg(target_has_reliable_f128)] {
1532 ///
1533 /// let f = 3.5_f128;
1534 ///
1535 /// assert_eq!(f.copysign(0.42), 3.5_f128);
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 ///
1540 /// assert!(f128::NAN.copysign(1.0).is_nan());
1541 /// # }
1542 /// ```
1543 #[inline]
1544 #[unstable(feature = "f128", issue = "116909")]
1545 #[rustc_const_unstable(feature = "f128", issue = "116909")]
1546 #[must_use = "method returns a new number and does not mutate the original value"]
1547 pub const fn copysign(self, sign: f128) -> f128 {
1548 intrinsics::copysignf128(self, sign)
1549 }
1550
1551 /// Float addition that allows optimizations based on algebraic rules.
1552 ///
1553 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1554 #[must_use = "method returns a new number and does not mutate the original value"]
1555 #[unstable(feature = "float_algebraic", issue = "136469")]
1556 #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1557 #[inline]
1558 pub const fn algebraic_add(self, rhs: f128) -> f128 {
1559 intrinsics::fadd_algebraic(self, rhs)
1560 }
1561
1562 /// Float subtraction that allows optimizations based on algebraic rules.
1563 ///
1564 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1565 #[must_use = "method returns a new number and does not mutate the original value"]
1566 #[unstable(feature = "float_algebraic", issue = "136469")]
1567 #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1568 #[inline]
1569 pub const fn algebraic_sub(self, rhs: f128) -> f128 {
1570 intrinsics::fsub_algebraic(self, rhs)
1571 }
1572
1573 /// Float multiplication that allows optimizations based on algebraic rules.
1574 ///
1575 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1576 #[must_use = "method returns a new number and does not mutate the original value"]
1577 #[unstable(feature = "float_algebraic", issue = "136469")]
1578 #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1579 #[inline]
1580 pub const fn algebraic_mul(self, rhs: f128) -> f128 {
1581 intrinsics::fmul_algebraic(self, rhs)
1582 }
1583
1584 /// Float division that allows optimizations based on algebraic rules.
1585 ///
1586 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1587 #[must_use = "method returns a new number and does not mutate the original value"]
1588 #[unstable(feature = "float_algebraic", issue = "136469")]
1589 #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1590 #[inline]
1591 pub const fn algebraic_div(self, rhs: f128) -> f128 {
1592 intrinsics::fdiv_algebraic(self, rhs)
1593 }
1594
1595 /// Float remainder that allows optimizations based on algebraic rules.
1596 ///
1597 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1598 #[must_use = "method returns a new number and does not mutate the original value"]
1599 #[unstable(feature = "float_algebraic", issue = "136469")]
1600 #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1601 #[inline]
1602 pub const fn algebraic_rem(self, rhs: f128) -> f128 {
1603 intrinsics::frem_algebraic(self, rhs)
1604 }
1605}
1606
1607// Functions in this module fall into `core_float_math`
1608// #[unstable(feature = "core_float_math", issue = "137578")]
1609#[cfg(not(test))]
1610#[doc(test(attr(
1611 feature(cfg_target_has_reliable_f16_f128),
1612 expect(internal_features),
1613 allow(unused_features)
1614)))]
1615impl f128 {
1616 /// Returns the largest integer less than or equal to `self`.
1617 ///
1618 /// This function always returns the precise result.
1619 ///
1620 /// # Examples
1621 ///
1622 /// ```
1623 /// #![feature(f128)]
1624 /// # #[cfg(any(miri, target_has_reliable_f128_math))] { // Miri uses softfloats, always works
1625 ///
1626 /// let f = 3.7_f128;
1627 /// let g = 3.0_f128;
1628 /// let h = -3.7_f128;
1629 ///
1630 /// assert_eq!(f.floor(), 3.0);
1631 /// assert_eq!(g.floor(), 3.0);
1632 /// assert_eq!(h.floor(), -4.0);
1633 /// # }
1634 /// ```
1635 #[inline]
1636 #[rustc_allow_incoherent_impl]
1637 #[unstable(feature = "f128", issue = "116909")]
1638 #[rustc_const_unstable(feature = "f128", issue = "116909")]
1639 #[must_use = "method returns a new number and does not mutate the original value"]
1640 pub const fn floor(self) -> f128 {
1641 intrinsics::floorf128(self)
1642 }
1643
1644 /// Returns the smallest integer greater than or equal to `self`.
1645 ///
1646 /// This function always returns the precise result.
1647 ///
1648 /// # Examples
1649 ///
1650 /// ```
1651 /// #![feature(f128)]
1652 /// # #[cfg(any(miri, target_has_reliable_f128_math))] { // Miri uses softfloats, always works
1653 ///
1654 /// let f = 3.01_f128;
1655 /// let g = 4.0_f128;
1656 ///
1657 /// assert_eq!(f.ceil(), 4.0);
1658 /// assert_eq!(g.ceil(), 4.0);
1659 /// # }
1660 /// ```
1661 #[inline]
1662 #[doc(alias = "ceiling")]
1663 #[rustc_allow_incoherent_impl]
1664 #[unstable(feature = "f128", issue = "116909")]
1665 #[rustc_const_unstable(feature = "f128", issue = "116909")]
1666 #[must_use = "method returns a new number and does not mutate the original value"]
1667 pub const fn ceil(self) -> f128 {
1668 intrinsics::ceilf128(self)
1669 }
1670
1671 /// Returns the nearest integer to `self`. If a value is half-way between two
1672 /// integers, round away from `0.0`.
1673 ///
1674 /// This function always returns the precise result.
1675 ///
1676 /// # Examples
1677 ///
1678 /// ```
1679 /// #![feature(f128)]
1680 /// # #[cfg(any(miri, target_has_reliable_f128_math))] { // Miri uses softfloats, always works
1681 ///
1682 /// let f = 3.3_f128;
1683 /// let g = -3.3_f128;
1684 /// let h = -3.7_f128;
1685 /// let i = 3.5_f128;
1686 /// let j = 4.5_f128;
1687 ///
1688 /// assert_eq!(f.round(), 3.0);
1689 /// assert_eq!(g.round(), -3.0);
1690 /// assert_eq!(h.round(), -4.0);
1691 /// assert_eq!(i.round(), 4.0);
1692 /// assert_eq!(j.round(), 5.0);
1693 /// # }
1694 /// ```
1695 #[inline]
1696 #[rustc_allow_incoherent_impl]
1697 #[unstable(feature = "f128", issue = "116909")]
1698 #[rustc_const_unstable(feature = "f128", issue = "116909")]
1699 #[must_use = "method returns a new number and does not mutate the original value"]
1700 pub const fn round(self) -> f128 {
1701 intrinsics::roundf128(self)
1702 }
1703
1704 /// Returns the nearest integer to a number. Rounds half-way cases to the number
1705 /// with an even least significant digit.
1706 ///
1707 /// This function always returns the precise result.
1708 ///
1709 /// # Examples
1710 ///
1711 /// ```
1712 /// #![feature(f128)]
1713 /// # #[cfg(any(miri, target_has_reliable_f128_math))] { // Miri uses softfloats, always works
1714 ///
1715 /// let f = 3.3_f128;
1716 /// let g = -3.3_f128;
1717 /// let h = 3.5_f128;
1718 /// let i = 4.5_f128;
1719 ///
1720 /// assert_eq!(f.round_ties_even(), 3.0);
1721 /// assert_eq!(g.round_ties_even(), -3.0);
1722 /// assert_eq!(h.round_ties_even(), 4.0);
1723 /// assert_eq!(i.round_ties_even(), 4.0);
1724 /// # }
1725 /// ```
1726 #[inline]
1727 #[rustc_allow_incoherent_impl]
1728 #[unstable(feature = "f128", issue = "116909")]
1729 #[rustc_const_unstable(feature = "f128", issue = "116909")]
1730 #[must_use = "method returns a new number and does not mutate the original value"]
1731 pub const fn round_ties_even(self) -> f128 {
1732 intrinsics::round_ties_even_f128(self)
1733 }
1734
1735 /// Returns the integer part of `self`.
1736 /// This means that non-integer numbers are always truncated towards zero.
1737 ///
1738 /// This function always returns the precise result.
1739 ///
1740 /// # Examples
1741 ///
1742 /// ```
1743 /// #![feature(f128)]
1744 /// # #[cfg(any(miri, target_has_reliable_f128_math))] { // Miri uses softfloats, always works
1745 ///
1746 /// let f = 3.7_f128;
1747 /// let g = 3.0_f128;
1748 /// let h = -3.7_f128;
1749 ///
1750 /// assert_eq!(f.trunc(), 3.0);
1751 /// assert_eq!(g.trunc(), 3.0);
1752 /// assert_eq!(h.trunc(), -3.0);
1753 /// # }
1754 /// ```
1755 #[inline]
1756 #[doc(alias = "truncate")]
1757 #[rustc_allow_incoherent_impl]
1758 #[unstable(feature = "f128", issue = "116909")]
1759 #[rustc_const_unstable(feature = "f128", issue = "116909")]
1760 #[must_use = "method returns a new number and does not mutate the original value"]
1761 pub const fn trunc(self) -> f128 {
1762 intrinsics::truncf128(self)
1763 }
1764
1765 /// Returns the fractional part of `self`.
1766 ///
1767 /// This function always returns the precise result.
1768 ///
1769 /// # Examples
1770 ///
1771 /// ```
1772 /// #![feature(f128)]
1773 /// # #[cfg(any(miri, target_has_reliable_f128_math))] { // Miri uses softfloats, always works
1774 ///
1775 /// let x = 3.6_f128;
1776 /// let y = -3.6_f128;
1777 /// let abs_difference_x = (x.fract() - 0.6).abs();
1778 /// let abs_difference_y = (y.fract() - (-0.6)).abs();
1779 ///
1780 /// assert!(abs_difference_x <= f128::EPSILON);
1781 /// assert!(abs_difference_y <= f128::EPSILON);
1782 /// # }
1783 /// ```
1784 #[inline]
1785 #[rustc_allow_incoherent_impl]
1786 #[unstable(feature = "f128", issue = "116909")]
1787 #[rustc_const_unstable(feature = "f128", issue = "116909")]
1788 #[must_use = "method returns a new number and does not mutate the original value"]
1789 pub const fn fract(self) -> f128 {
1790 self - self.trunc()
1791 }
1792
1793 /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
1794 /// error, yielding a more accurate result than an unfused multiply-add.
1795 ///
1796 /// Using `mul_add` *may* be more performant than an unfused multiply-add if
1797 /// the target architecture has a dedicated `fma` CPU instruction. However,
1798 /// this is not always true, and will be heavily dependant on designing
1799 /// algorithms with specific target hardware in mind.
1800 ///
1801 /// # Precision
1802 ///
1803 /// The result of this operation is guaranteed to be the rounded
1804 /// infinite-precision result. It is specified by IEEE 754 as
1805 /// `fusedMultiplyAdd` and guaranteed not to change.
1806 ///
1807 /// # Examples
1808 ///
1809 /// ```
1810 /// #![feature(f128)]
1811 /// # #[cfg(any(miri, target_has_reliable_f128_math))] { // Miri uses softfloats, always works
1812 ///
1813 /// let m = 10.0_f128;
1814 /// let x = 4.0_f128;
1815 /// let b = 60.0_f128;
1816 ///
1817 /// assert_eq!(m.mul_add(x, b), 100.0);
1818 /// assert_eq!(m * x + b, 100.0);
1819 ///
1820 /// let one_plus_eps = 1.0_f128 + f128::EPSILON;
1821 /// let one_minus_eps = 1.0_f128 - f128::EPSILON;
1822 /// let minus_one = -1.0_f128;
1823 ///
1824 /// // The exact result (1 + eps) * (1 - eps) = 1 - eps * eps.
1825 /// assert_eq!(one_plus_eps.mul_add(one_minus_eps, minus_one), -f128::EPSILON * f128::EPSILON);
1826 /// // Different rounding with the non-fused multiply and add.
1827 /// assert_eq!(one_plus_eps * one_minus_eps + minus_one, 0.0);
1828 /// # }
1829 /// ```
1830 #[inline]
1831 #[rustc_allow_incoherent_impl]
1832 #[doc(alias = "fmaf128", alias = "fusedMultiplyAdd")]
1833 #[unstable(feature = "f128", issue = "116909")]
1834 #[must_use = "method returns a new number and does not mutate the original value"]
1835 pub const fn mul_add(self, a: f128, b: f128) -> f128 {
1836 intrinsics::fmaf128(self, a, b)
1837 }
1838
1839 /// Calculates Euclidean division, the matching method for `rem_euclid`.
1840 ///
1841 /// This computes the integer `n` such that
1842 /// `self = n * rhs + self.rem_euclid(rhs)`.
1843 /// In other words, the result is `self / rhs` rounded to the integer `n`
1844 /// such that `self >= n * rhs`.
1845 ///
1846 /// # Precision
1847 ///
1848 /// The result of this operation is guaranteed to be the rounded
1849 /// infinite-precision result.
1850 ///
1851 /// # Examples
1852 ///
1853 /// ```
1854 /// #![feature(f128)]
1855 /// # #[cfg(any(miri, target_has_reliable_f128_math))] { // Miri uses softfloats, always works
1856 ///
1857 /// let a: f128 = 7.0;
1858 /// let b = 4.0;
1859 /// assert_eq!(a.div_euclid(b), 1.0); // 7.0 > 4.0 * 1.0
1860 /// assert_eq!((-a).div_euclid(b), -2.0); // -7.0 >= 4.0 * -2.0
1861 /// assert_eq!(a.div_euclid(-b), -1.0); // 7.0 >= -4.0 * -1.0
1862 /// assert_eq!((-a).div_euclid(-b), 2.0); // -7.0 >= -4.0 * 2.0
1863 /// # }
1864 /// ```
1865 #[inline]
1866 #[rustc_allow_incoherent_impl]
1867 #[unstable(feature = "f128", issue = "116909")]
1868 #[must_use = "method returns a new number and does not mutate the original value"]
1869 pub fn div_euclid(self, rhs: f128) -> f128 {
1870 let q = (self / rhs).trunc();
1871 if self % rhs < 0.0 {
1872 return if rhs > 0.0 { q - 1.0 } else { q + 1.0 };
1873 }
1874 q
1875 }
1876
1877 /// Calculates the least nonnegative remainder of `self` when
1878 /// divided by `rhs`.
1879 ///
1880 /// In particular, the return value `r` satisfies `0.0 <= r < rhs.abs()` in
1881 /// most cases. However, due to a floating point round-off error it can
1882 /// result in `r == rhs.abs()`, violating the mathematical definition, if
1883 /// `self` is much smaller than `rhs.abs()` in magnitude and `self < 0.0`.
1884 /// This result is not an element of the function's codomain, but it is the
1885 /// closest floating point number in the real numbers and thus fulfills the
1886 /// property `self == self.div_euclid(rhs) * rhs + self.rem_euclid(rhs)`
1887 /// approximately.
1888 ///
1889 /// # Precision
1890 ///
1891 /// The result of this operation is guaranteed to be the rounded
1892 /// infinite-precision result.
1893 ///
1894 /// # Examples
1895 ///
1896 /// ```
1897 /// #![feature(f128)]
1898 /// # #[cfg(any(miri, target_has_reliable_f128_math))] { // Miri uses softfloats, always works
1899 ///
1900 /// let a: f128 = 7.0;
1901 /// let b = 4.0;
1902 /// assert_eq!(a.rem_euclid(b), 3.0);
1903 /// assert_eq!((-a).rem_euclid(b), 1.0);
1904 /// assert_eq!(a.rem_euclid(-b), 3.0);
1905 /// assert_eq!((-a).rem_euclid(-b), 1.0);
1906 /// // limitation due to round-off error
1907 /// assert!((-f128::EPSILON).rem_euclid(3.0) != 0.0);
1908 /// # }
1909 /// ```
1910 #[inline]
1911 #[rustc_allow_incoherent_impl]
1912 #[doc(alias = "modulo", alias = "mod")]
1913 #[unstable(feature = "f128", issue = "116909")]
1914 #[must_use = "method returns a new number and does not mutate the original value"]
1915 pub fn rem_euclid(self, rhs: f128) -> f128 {
1916 let r = self % rhs;
1917 if r < 0.0 { r + rhs.abs() } else { r }
1918 }
1919
1920 /// Raises a number to an integer power.
1921 ///
1922 /// Using this function is generally faster than using `powf`.
1923 /// It might have a different sequence of rounding operations than `powf`,
1924 /// so the results are not guaranteed to agree.
1925 ///
1926 /// Note that this function is special in that it can return non-NaN results for NaN inputs. For
1927 /// example, `f128::powi(f128::NAN, 0)` returns `1.0`. However, if an input is a *signaling*
1928 /// NaN, then the result is non-deterministically either a NaN or the result that the
1929 /// corresponding quiet NaN would produce.
1930 ///
1931 /// # Unspecified precision
1932 ///
1933 /// The precision of this function is non-deterministic. This means it varies by platform,
1934 /// Rust version, and can even differ within the same execution from one invocation to the next.
1935 ///
1936 /// # Examples
1937 ///
1938 /// ```
1939 /// #![feature(f128)]
1940 /// # #[cfg(target_has_reliable_f128_math)] {
1941 ///
1942 /// let x = 2.0_f128;
1943 /// let abs_difference = (x.powi(2) - (x * x)).abs();
1944 /// assert!(abs_difference <= 1e-9);
1945 ///
1946 /// assert_eq!(f128::powi(f128::NAN, 0), 1.0);
1947 /// assert_eq!(f128::powi(0.0, 0), 1.0);
1948 /// # }
1949 /// ```
1950 #[inline]
1951 #[rustc_allow_incoherent_impl]
1952 #[unstable(feature = "f128", issue = "116909")]
1953 #[must_use = "method returns a new number and does not mutate the original value"]
1954 pub fn powi(self, n: i32) -> f128 {
1955 intrinsics::powif128(self, n)
1956 }
1957
1958 /// Returns the square root of a number.
1959 ///
1960 /// Returns NaN if `self` is a negative number other than `-0.0`.
1961 ///
1962 /// # Precision
1963 ///
1964 /// The result of this operation is guaranteed to be the rounded
1965 /// infinite-precision result. It is specified by IEEE 754 as `squareRoot`
1966 /// and guaranteed not to change.
1967 ///
1968 /// # Examples
1969 ///
1970 /// ```
1971 /// #![feature(f128)]
1972 /// # #[cfg(any(miri, target_has_reliable_f128_math))] { // Miri uses softfloats, always works
1973 ///
1974 /// let positive = 4.0_f128;
1975 /// let negative = -4.0_f128;
1976 /// let negative_zero = -0.0_f128;
1977 ///
1978 /// assert_eq!(positive.sqrt(), 2.0);
1979 /// assert!(negative.sqrt().is_nan());
1980 /// assert!(negative_zero.sqrt() == negative_zero);
1981 /// # }
1982 /// ```
1983 #[inline]
1984 #[doc(alias = "squareRoot")]
1985 #[rustc_allow_incoherent_impl]
1986 #[unstable(feature = "f128", issue = "116909")]
1987 #[must_use = "method returns a new number and does not mutate the original value"]
1988 pub fn sqrt(self) -> f128 {
1989 intrinsics::sqrtf128(self)
1990 }
1991}