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