1 //! Constants specific to the `f64` double-precision floating point type.
3 //! *[See also the `f64` primitive type][f64].*
5 //! Mathematically significant numbers are provided in the `consts` sub-module.
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 `f64` type.
12 #![stable(feature = "rust1", since = "1.0.0")]
14 use crate::convert::FloatToInt;
16 use crate::intrinsics;
18 use crate::num::FpCategory;
20 /// The radix or base of the internal representation of `f64`.
21 /// Use [`f64::RADIX`] instead.
27 /// # #[allow(deprecated, deprecated_in_future)]
28 /// let r = std::f64::RADIX;
31 /// let r = f64::RADIX;
33 #[stable(feature = "rust1", since = "1.0.0")]
34 #[rustc_deprecated(since = "TBD", reason = "replaced by the `RADIX` associated constant on `f64`")]
35 pub const RADIX: u32 = f64::RADIX;
37 /// Number of significant digits in base 2.
38 /// Use [`f64::MANTISSA_DIGITS`] instead.
44 /// # #[allow(deprecated, deprecated_in_future)]
45 /// let d = std::f64::MANTISSA_DIGITS;
48 /// let d = f64::MANTISSA_DIGITS;
50 #[stable(feature = "rust1", since = "1.0.0")]
53 reason = "replaced by the `MANTISSA_DIGITS` associated constant on `f64`"
55 pub const MANTISSA_DIGITS: u32 = f64::MANTISSA_DIGITS;
57 /// Approximate number of significant digits in base 10.
58 /// Use [`f64::DIGITS`] instead.
64 /// # #[allow(deprecated, deprecated_in_future)]
65 /// let d = std::f64::DIGITS;
68 /// let d = f64::DIGITS;
70 #[stable(feature = "rust1", since = "1.0.0")]
71 #[rustc_deprecated(since = "TBD", reason = "replaced by the `DIGITS` associated constant on `f64`")]
72 pub const DIGITS: u32 = f64::DIGITS;
74 /// [Machine epsilon] value for `f64`.
75 /// Use [`f64::EPSILON`] instead.
77 /// This is the difference between `1.0` and the next larger representable number.
79 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
85 /// # #[allow(deprecated, deprecated_in_future)]
86 /// let e = std::f64::EPSILON;
89 /// let e = f64::EPSILON;
91 #[stable(feature = "rust1", since = "1.0.0")]
94 reason = "replaced by the `EPSILON` associated constant on `f64`"
96 pub const EPSILON: f64 = f64::EPSILON;
98 /// Smallest finite `f64` value.
99 /// Use [`f64::MIN`] instead.
104 /// // deprecated way
105 /// # #[allow(deprecated, deprecated_in_future)]
106 /// let min = std::f64::MIN;
109 /// let min = f64::MIN;
111 #[stable(feature = "rust1", since = "1.0.0")]
112 #[rustc_deprecated(since = "TBD", reason = "replaced by the `MIN` associated constant on `f64`")]
113 pub const MIN: f64 = f64::MIN;
115 /// Smallest positive normal `f64` value.
116 /// Use [`f64::MIN_POSITIVE`] instead.
121 /// // deprecated way
122 /// # #[allow(deprecated, deprecated_in_future)]
123 /// let min = std::f64::MIN_POSITIVE;
126 /// let min = f64::MIN_POSITIVE;
128 #[stable(feature = "rust1", since = "1.0.0")]
131 reason = "replaced by the `MIN_POSITIVE` associated constant on `f64`"
133 pub const MIN_POSITIVE: f64 = f64::MIN_POSITIVE;
135 /// Largest finite `f64` value.
136 /// Use [`f64::MAX`] instead.
141 /// // deprecated way
142 /// # #[allow(deprecated, deprecated_in_future)]
143 /// let max = std::f64::MAX;
146 /// let max = f64::MAX;
148 #[stable(feature = "rust1", since = "1.0.0")]
149 #[rustc_deprecated(since = "TBD", reason = "replaced by the `MAX` associated constant on `f64`")]
150 pub const MAX: f64 = f64::MAX;
152 /// One greater than the minimum possible normal power of 2 exponent.
153 /// Use [`f64::MIN_EXP`] instead.
158 /// // deprecated way
159 /// # #[allow(deprecated, deprecated_in_future)]
160 /// let min = std::f64::MIN_EXP;
163 /// let min = f64::MIN_EXP;
165 #[stable(feature = "rust1", since = "1.0.0")]
168 reason = "replaced by the `MIN_EXP` associated constant on `f64`"
170 pub const MIN_EXP: i32 = f64::MIN_EXP;
172 /// Maximum possible power of 2 exponent.
173 /// Use [`f64::MAX_EXP`] instead.
178 /// // deprecated way
179 /// # #[allow(deprecated, deprecated_in_future)]
180 /// let max = std::f64::MAX_EXP;
183 /// let max = f64::MAX_EXP;
185 #[stable(feature = "rust1", since = "1.0.0")]
188 reason = "replaced by the `MAX_EXP` associated constant on `f64`"
190 pub const MAX_EXP: i32 = f64::MAX_EXP;
192 /// Minimum possible normal power of 10 exponent.
193 /// Use [`f64::MIN_10_EXP`] instead.
198 /// // deprecated way
199 /// # #[allow(deprecated, deprecated_in_future)]
200 /// let min = std::f64::MIN_10_EXP;
203 /// let min = f64::MIN_10_EXP;
205 #[stable(feature = "rust1", since = "1.0.0")]
208 reason = "replaced by the `MIN_10_EXP` associated constant on `f64`"
210 pub const MIN_10_EXP: i32 = f64::MIN_10_EXP;
212 /// Maximum possible power of 10 exponent.
213 /// Use [`f64::MAX_10_EXP`] instead.
218 /// // deprecated way
219 /// # #[allow(deprecated, deprecated_in_future)]
220 /// let max = std::f64::MAX_10_EXP;
223 /// let max = f64::MAX_10_EXP;
225 #[stable(feature = "rust1", since = "1.0.0")]
228 reason = "replaced by the `MAX_10_EXP` associated constant on `f64`"
230 pub const MAX_10_EXP: i32 = f64::MAX_10_EXP;
232 /// Not a Number (NaN).
233 /// Use [`f64::NAN`] instead.
238 /// // deprecated way
239 /// # #[allow(deprecated, deprecated_in_future)]
240 /// let nan = std::f64::NAN;
243 /// let nan = f64::NAN;
245 #[stable(feature = "rust1", since = "1.0.0")]
246 #[rustc_deprecated(since = "TBD", reason = "replaced by the `NAN` associated constant on `f64`")]
247 pub const NAN: f64 = f64::NAN;
250 /// Use [`f64::INFINITY`] instead.
255 /// // deprecated way
256 /// # #[allow(deprecated, deprecated_in_future)]
257 /// let inf = std::f64::INFINITY;
260 /// let inf = f64::INFINITY;
262 #[stable(feature = "rust1", since = "1.0.0")]
265 reason = "replaced by the `INFINITY` associated constant on `f64`"
267 pub const INFINITY: f64 = f64::INFINITY;
269 /// Negative infinity (−∞).
270 /// Use [`f64::NEG_INFINITY`] instead.
275 /// // deprecated way
276 /// # #[allow(deprecated, deprecated_in_future)]
277 /// let ninf = std::f64::NEG_INFINITY;
280 /// let ninf = f64::NEG_INFINITY;
282 #[stable(feature = "rust1", since = "1.0.0")]
285 reason = "replaced by the `NEG_INFINITY` associated constant on `f64`"
287 pub const NEG_INFINITY: f64 = f64::NEG_INFINITY;
289 /// Basic mathematical constants.
290 #[stable(feature = "rust1", since = "1.0.0")]
292 // FIXME: replace with mathematical constants from cmath.
294 /// Archimedes' constant (π)
295 #[stable(feature = "rust1", since = "1.0.0")]
296 pub const PI: f64 = 3.14159265358979323846264338327950288_f64;
298 /// The full circle constant (τ)
301 #[stable(feature = "tau_constant", since = "1.47.0")]
302 pub const TAU: f64 = 6.28318530717958647692528676655900577_f64;
305 #[stable(feature = "rust1", since = "1.0.0")]
306 pub const FRAC_PI_2: f64 = 1.57079632679489661923132169163975144_f64;
309 #[stable(feature = "rust1", since = "1.0.0")]
310 pub const FRAC_PI_3: f64 = 1.04719755119659774615421446109316763_f64;
313 #[stable(feature = "rust1", since = "1.0.0")]
314 pub const FRAC_PI_4: f64 = 0.785398163397448309615660845819875721_f64;
317 #[stable(feature = "rust1", since = "1.0.0")]
318 pub const FRAC_PI_6: f64 = 0.52359877559829887307710723054658381_f64;
321 #[stable(feature = "rust1", since = "1.0.0")]
322 pub const FRAC_PI_8: f64 = 0.39269908169872415480783042290993786_f64;
325 #[stable(feature = "rust1", since = "1.0.0")]
326 pub const FRAC_1_PI: f64 = 0.318309886183790671537767526745028724_f64;
329 #[stable(feature = "rust1", since = "1.0.0")]
330 pub const FRAC_2_PI: f64 = 0.636619772367581343075535053490057448_f64;
333 #[stable(feature = "rust1", since = "1.0.0")]
334 pub const FRAC_2_SQRT_PI: f64 = 1.12837916709551257389615890312154517_f64;
337 #[stable(feature = "rust1", since = "1.0.0")]
338 pub const SQRT_2: f64 = 1.41421356237309504880168872420969808_f64;
341 #[stable(feature = "rust1", since = "1.0.0")]
342 pub const FRAC_1_SQRT_2: f64 = 0.707106781186547524400844362104849039_f64;
344 /// Euler's number (e)
345 #[stable(feature = "rust1", since = "1.0.0")]
346 pub const E: f64 = 2.71828182845904523536028747135266250_f64;
348 /// log<sub>2</sub>(10)
349 #[stable(feature = "extra_log_consts", since = "1.43.0")]
350 pub const LOG2_10: f64 = 3.32192809488736234787031942948939018_f64;
352 /// log<sub>2</sub>(e)
353 #[stable(feature = "rust1", since = "1.0.0")]
354 pub const LOG2_E: f64 = 1.44269504088896340735992468100189214_f64;
356 /// log<sub>10</sub>(2)
357 #[stable(feature = "extra_log_consts", since = "1.43.0")]
358 pub const LOG10_2: f64 = 0.301029995663981195213738894724493027_f64;
360 /// log<sub>10</sub>(e)
361 #[stable(feature = "rust1", since = "1.0.0")]
362 pub const LOG10_E: f64 = 0.434294481903251827651128918916605082_f64;
365 #[stable(feature = "rust1", since = "1.0.0")]
366 pub const LN_2: f64 = 0.693147180559945309417232121458176568_f64;
369 #[stable(feature = "rust1", since = "1.0.0")]
370 pub const LN_10: f64 = 2.30258509299404568401799145468436421_f64;
375 /// The radix or base of the internal representation of `f64`.
376 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
377 pub const RADIX: u32 = 2;
379 /// Number of significant digits in base 2.
380 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
381 pub const MANTISSA_DIGITS: u32 = 53;
382 /// Approximate number of significant digits in base 10.
383 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
384 pub const DIGITS: u32 = 15;
386 /// [Machine epsilon] value for `f64`.
388 /// This is the difference between `1.0` and the next larger representable number.
390 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
391 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
392 pub const EPSILON: f64 = 2.2204460492503131e-16_f64;
394 /// Smallest finite `f64` value.
395 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
396 pub const MIN: f64 = -1.7976931348623157e+308_f64;
397 /// Smallest positive normal `f64` value.
398 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
399 pub const MIN_POSITIVE: f64 = 2.2250738585072014e-308_f64;
400 /// Largest finite `f64` value.
401 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
402 pub const MAX: f64 = 1.7976931348623157e+308_f64;
404 /// One greater than the minimum possible normal power of 2 exponent.
405 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
406 pub const MIN_EXP: i32 = -1021;
407 /// Maximum possible power of 2 exponent.
408 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
409 pub const MAX_EXP: i32 = 1024;
411 /// Minimum possible normal power of 10 exponent.
412 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
413 pub const MIN_10_EXP: i32 = -307;
414 /// Maximum possible power of 10 exponent.
415 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
416 pub const MAX_10_EXP: i32 = 308;
418 /// Not a Number (NaN).
419 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
420 pub const NAN: f64 = 0.0_f64 / 0.0_f64;
422 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
423 pub const INFINITY: f64 = 1.0_f64 / 0.0_f64;
424 /// Negative infinity (−∞).
425 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
426 pub const NEG_INFINITY: f64 = -1.0_f64 / 0.0_f64;
428 /// Returns `true` if this value is `NaN`.
431 /// let nan = f64::NAN;
434 /// assert!(nan.is_nan());
435 /// assert!(!f.is_nan());
438 #[stable(feature = "rust1", since = "1.0.0")]
439 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
441 pub const fn is_nan(self) -> bool {
445 // FIXME(#50145): `abs` is publicly unavailable in libcore due to
446 // concerns about portability, so this implementation is for
447 // private use internally.
449 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
450 pub(crate) const fn abs_private(self) -> f64 {
451 f64::from_bits(self.to_bits() & 0x7fff_ffff_ffff_ffff)
454 /// Returns `true` if this value is positive infinity or negative infinity, and
455 /// `false` otherwise.
459 /// let inf = f64::INFINITY;
460 /// let neg_inf = f64::NEG_INFINITY;
461 /// let nan = f64::NAN;
463 /// assert!(!f.is_infinite());
464 /// assert!(!nan.is_infinite());
466 /// assert!(inf.is_infinite());
467 /// assert!(neg_inf.is_infinite());
470 #[stable(feature = "rust1", since = "1.0.0")]
471 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
473 pub const fn is_infinite(self) -> bool {
474 self.abs_private() == Self::INFINITY
477 /// Returns `true` if this number is neither infinite nor `NaN`.
481 /// let inf: f64 = f64::INFINITY;
482 /// let neg_inf: f64 = f64::NEG_INFINITY;
483 /// let nan: f64 = f64::NAN;
485 /// assert!(f.is_finite());
487 /// assert!(!nan.is_finite());
488 /// assert!(!inf.is_finite());
489 /// assert!(!neg_inf.is_finite());
492 #[stable(feature = "rust1", since = "1.0.0")]
493 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
495 pub const fn is_finite(self) -> bool {
496 // There's no need to handle NaN separately: if self is NaN,
497 // the comparison is not true, exactly as desired.
498 self.abs_private() < Self::INFINITY
501 /// Returns `true` if the number is [subnormal].
504 /// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308_f64
505 /// let max = f64::MAX;
506 /// let lower_than_min = 1.0e-308_f64;
507 /// let zero = 0.0_f64;
509 /// assert!(!min.is_subnormal());
510 /// assert!(!max.is_subnormal());
512 /// assert!(!zero.is_subnormal());
513 /// assert!(!f64::NAN.is_subnormal());
514 /// assert!(!f64::INFINITY.is_subnormal());
515 /// // Values between `0` and `min` are Subnormal.
516 /// assert!(lower_than_min.is_subnormal());
518 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
520 #[stable(feature = "is_subnormal", since = "1.53.0")]
521 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
523 pub const fn is_subnormal(self) -> bool {
524 matches!(self.classify(), FpCategory::Subnormal)
527 /// Returns `true` if the number is neither zero, infinite,
528 /// [subnormal], or `NaN`.
531 /// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308f64
532 /// let max = f64::MAX;
533 /// let lower_than_min = 1.0e-308_f64;
534 /// let zero = 0.0f64;
536 /// assert!(min.is_normal());
537 /// assert!(max.is_normal());
539 /// assert!(!zero.is_normal());
540 /// assert!(!f64::NAN.is_normal());
541 /// assert!(!f64::INFINITY.is_normal());
542 /// // Values between `0` and `min` are Subnormal.
543 /// assert!(!lower_than_min.is_normal());
545 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
547 #[stable(feature = "rust1", since = "1.0.0")]
548 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
550 pub const fn is_normal(self) -> bool {
551 matches!(self.classify(), FpCategory::Normal)
554 /// Returns the floating point category of the number. If only one property
555 /// is going to be tested, it is generally faster to use the specific
556 /// predicate instead.
559 /// use std::num::FpCategory;
561 /// let num = 12.4_f64;
562 /// let inf = f64::INFINITY;
564 /// assert_eq!(num.classify(), FpCategory::Normal);
565 /// assert_eq!(inf.classify(), FpCategory::Infinite);
567 #[stable(feature = "rust1", since = "1.0.0")]
568 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
569 pub const fn classify(self) -> FpCategory {
570 const EXP_MASK: u64 = 0x7ff0000000000000;
571 const MAN_MASK: u64 = 0x000fffffffffffff;
573 let bits = self.to_bits();
574 match (bits & MAN_MASK, bits & EXP_MASK) {
575 (0, 0) => FpCategory::Zero,
576 (_, 0) => FpCategory::Subnormal,
577 (0, EXP_MASK) => FpCategory::Infinite,
578 (_, EXP_MASK) => FpCategory::Nan,
579 _ => FpCategory::Normal,
583 /// Returns `true` if `self` has a positive sign, including `+0.0`, `NaN`s with
584 /// positive sign bit and positive infinity.
588 /// let g = -7.0_f64;
590 /// assert!(f.is_sign_positive());
591 /// assert!(!g.is_sign_positive());
594 #[stable(feature = "rust1", since = "1.0.0")]
595 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
597 pub const fn is_sign_positive(self) -> bool {
598 !self.is_sign_negative()
602 #[stable(feature = "rust1", since = "1.0.0")]
603 #[rustc_deprecated(since = "1.0.0", reason = "renamed to is_sign_positive")]
606 pub fn is_positive(self) -> bool {
607 self.is_sign_positive()
610 /// Returns `true` if `self` has a negative sign, including `-0.0`, `NaN`s with
611 /// negative sign bit and negative infinity.
615 /// let g = -7.0_f64;
617 /// assert!(!f.is_sign_negative());
618 /// assert!(g.is_sign_negative());
621 #[stable(feature = "rust1", since = "1.0.0")]
622 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
624 pub const fn is_sign_negative(self) -> bool {
625 self.to_bits() & 0x8000_0000_0000_0000 != 0
629 #[stable(feature = "rust1", since = "1.0.0")]
630 #[rustc_deprecated(since = "1.0.0", reason = "renamed to is_sign_negative")]
633 pub fn is_negative(self) -> bool {
634 self.is_sign_negative()
637 /// Takes the reciprocal (inverse) of a number, `1/x`.
641 /// let abs_difference = (x.recip() - (1.0 / x)).abs();
643 /// assert!(abs_difference < 1e-10);
645 #[must_use = "this returns the result of the operation, without modifying the original"]
646 #[stable(feature = "rust1", since = "1.0.0")]
648 pub fn recip(self) -> f64 {
652 /// Converts radians to degrees.
655 /// let angle = std::f64::consts::PI;
657 /// let abs_difference = (angle.to_degrees() - 180.0).abs();
659 /// assert!(abs_difference < 1e-10);
661 #[must_use = "this returns the result of the operation, \
662 without modifying the original"]
663 #[stable(feature = "rust1", since = "1.0.0")]
665 pub fn to_degrees(self) -> f64 {
666 // The division here is correctly rounded with respect to the true
667 // value of 180/π. (This differs from f32, where a constant must be
668 // used to ensure a correctly rounded result.)
669 self * (180.0f64 / consts::PI)
672 /// Converts degrees to radians.
675 /// let angle = 180.0_f64;
677 /// let abs_difference = (angle.to_radians() - std::f64::consts::PI).abs();
679 /// assert!(abs_difference < 1e-10);
681 #[must_use = "this returns the result of the operation, \
682 without modifying the original"]
683 #[stable(feature = "rust1", since = "1.0.0")]
685 pub fn to_radians(self) -> f64 {
686 let value: f64 = consts::PI;
687 self * (value / 180.0)
690 /// Returns the maximum of the two numbers.
692 /// Follows the IEEE-754 2008 semantics for maxNum, except for handling of signaling NaNs.
693 /// This matches the behavior of libm’s fmax.
699 /// assert_eq!(x.max(y), y);
702 /// If one of the arguments is NaN, then the other argument is returned.
703 #[must_use = "this returns the result of the comparison, without modifying either input"]
704 #[stable(feature = "rust1", since = "1.0.0")]
706 pub fn max(self, other: f64) -> f64 {
707 intrinsics::maxnumf64(self, other)
710 /// Returns the minimum of the two numbers.
712 /// Follows the IEEE-754 2008 semantics for minNum, except for handling of signaling NaNs.
713 /// This matches the behavior of libm’s fmin.
719 /// assert_eq!(x.min(y), x);
722 /// If one of the arguments is NaN, then the other argument is returned.
723 #[must_use = "this returns the result of the comparison, without modifying either input"]
724 #[stable(feature = "rust1", since = "1.0.0")]
726 pub fn min(self, other: f64) -> f64 {
727 intrinsics::minnumf64(self, other)
730 /// Returns the maximum of the two numbers, propagating NaNs.
732 /// This returns NaN when *either* argument is NaN, as opposed to
733 /// [`f64::max`] which only returns NaN when *both* arguments are NaN.
736 /// #![feature(float_minimum_maximum)]
740 /// assert_eq!(x.maximum(y), y);
741 /// assert!(x.maximum(f64::NAN).is_nan());
744 /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the greater
745 /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
746 /// Note that this follows the semantics specified in IEEE 754-2019.
747 #[must_use = "this returns the result of the comparison, without modifying either input"]
748 #[unstable(feature = "float_minimum_maximum", issue = "91079")]
750 pub fn maximum(self, other: f64) -> f64 {
753 } else if other > self {
755 } else if self == other {
756 if self.is_sign_positive() && other.is_sign_negative() { self } else { other }
762 /// Returns the minimum of the two numbers, propagating NaNs.
764 /// This returns NaN when *either* argument is NaN, as opposed to
765 /// [`f64::min`] which only returns NaN when *both* arguments are NaN.
768 /// #![feature(float_minimum_maximum)]
772 /// assert_eq!(x.minimum(y), x);
773 /// assert!(x.minimum(f64::NAN).is_nan());
776 /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the lesser
777 /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
778 /// Note that this follows the semantics specified in IEEE 754-2019.
779 #[must_use = "this returns the result of the comparison, without modifying either input"]
780 #[unstable(feature = "float_minimum_maximum", issue = "91079")]
782 pub fn minimum(self, other: f64) -> f64 {
785 } else if other < self {
787 } else if self == other {
788 if self.is_sign_negative() && other.is_sign_positive() { self } else { other }
794 /// Rounds toward zero and converts to any primitive integer type,
795 /// assuming that the value is finite and fits in that type.
798 /// let value = 4.6_f64;
799 /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
800 /// assert_eq!(rounded, 4);
802 /// let value = -128.9_f64;
803 /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
804 /// assert_eq!(rounded, i8::MIN);
812 /// * Not be infinite
813 /// * Be representable in the return type `Int`, after truncating off its fractional part
814 #[must_use = "this returns the result of the operation, \
815 without modifying the original"]
816 #[stable(feature = "float_approx_unchecked_to", since = "1.44.0")]
818 pub unsafe fn to_int_unchecked<Int>(self) -> Int
820 Self: FloatToInt<Int>,
822 // SAFETY: the caller must uphold the safety contract for
823 // `FloatToInt::to_int_unchecked`.
824 unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
827 /// Raw transmutation to `u64`.
829 /// This is currently identical to `transmute::<f64, u64>(self)` on all platforms.
831 /// See [`from_bits`](Self::from_bits) for some discussion of the
832 /// portability of this operation (there are almost no issues).
834 /// Note that this function is distinct from `as` casting, which attempts to
835 /// preserve the *numeric* value, and not the bitwise value.
840 /// assert!((1f64).to_bits() != 1f64 as u64); // to_bits() is not casting!
841 /// assert_eq!((12.5f64).to_bits(), 0x4029000000000000);
844 #[must_use = "this returns the result of the operation, \
845 without modifying the original"]
846 #[stable(feature = "float_bits_conv", since = "1.20.0")]
847 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
849 pub const fn to_bits(self) -> u64 {
850 // SAFETY: `u64` is a plain old datatype so we can always transmute to it
851 unsafe { mem::transmute(self) }
854 /// Raw transmutation from `u64`.
856 /// This is currently identical to `transmute::<u64, f64>(v)` on all platforms.
857 /// It turns out this is incredibly portable, for two reasons:
859 /// * Floats and Ints have the same endianness on all supported platforms.
860 /// * IEEE-754 very precisely specifies the bit layout of floats.
862 /// However there is one caveat: prior to the 2008 version of IEEE-754, how
863 /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
864 /// (notably x86 and ARM) picked the interpretation that was ultimately
865 /// standardized in 2008, but some didn't (notably MIPS). As a result, all
866 /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
868 /// Rather than trying to preserve signaling-ness cross-platform, this
869 /// implementation favors preserving the exact bits. This means that
870 /// any payloads encoded in NaNs will be preserved even if the result of
871 /// this method is sent over the network from an x86 machine to a MIPS one.
873 /// If the results of this method are only manipulated by the same
874 /// architecture that produced them, then there is no portability concern.
876 /// If the input isn't NaN, then there is no portability concern.
878 /// If you don't care about signaling-ness (very likely), then there is no
879 /// portability concern.
881 /// Note that this function is distinct from `as` casting, which attempts to
882 /// preserve the *numeric* value, and not the bitwise value.
887 /// let v = f64::from_bits(0x4029000000000000);
888 /// assert_eq!(v, 12.5);
890 #[stable(feature = "float_bits_conv", since = "1.20.0")]
891 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
894 pub const fn from_bits(v: u64) -> Self {
895 // SAFETY: `u64` is a plain old datatype so we can always transmute from it
896 // It turns out the safety issues with sNaN were overblown! Hooray!
897 unsafe { mem::transmute(v) }
900 /// Return the memory representation of this floating point number as a byte array in
901 /// big-endian (network) byte order.
906 /// let bytes = 12.5f64.to_be_bytes();
907 /// assert_eq!(bytes, [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
909 #[must_use = "this returns the result of the operation, \
910 without modifying the original"]
911 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
912 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
914 pub const fn to_be_bytes(self) -> [u8; 8] {
915 self.to_bits().to_be_bytes()
918 /// Return the memory representation of this floating point number as a byte array in
919 /// little-endian byte order.
924 /// let bytes = 12.5f64.to_le_bytes();
925 /// assert_eq!(bytes, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]);
927 #[must_use = "this returns the result of the operation, \
928 without modifying the original"]
929 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
930 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
932 pub const fn to_le_bytes(self) -> [u8; 8] {
933 self.to_bits().to_le_bytes()
936 /// Return the memory representation of this floating point number as a byte array in
937 /// native byte order.
939 /// As the target platform's native endianness is used, portable code
940 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
942 /// [`to_be_bytes`]: f64::to_be_bytes
943 /// [`to_le_bytes`]: f64::to_le_bytes
948 /// let bytes = 12.5f64.to_ne_bytes();
951 /// if cfg!(target_endian = "big") {
952 /// [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
954 /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]
958 #[must_use = "this returns the result of the operation, \
959 without modifying the original"]
960 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
961 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
963 pub const fn to_ne_bytes(self) -> [u8; 8] {
964 self.to_bits().to_ne_bytes()
967 /// Create a floating point value from its representation as a byte array in big endian.
972 /// let value = f64::from_be_bytes([0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
973 /// assert_eq!(value, 12.5);
975 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
976 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
979 pub const fn from_be_bytes(bytes: [u8; 8]) -> Self {
980 Self::from_bits(u64::from_be_bytes(bytes))
983 /// Create a floating point value from its representation as a byte array in little endian.
988 /// let value = f64::from_le_bytes([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]);
989 /// assert_eq!(value, 12.5);
991 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
992 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
995 pub const fn from_le_bytes(bytes: [u8; 8]) -> Self {
996 Self::from_bits(u64::from_le_bytes(bytes))
999 /// Create a floating point value from its representation as a byte array in native endian.
1001 /// As the target platform's native endianness is used, portable code
1002 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1003 /// appropriate instead.
1005 /// [`from_be_bytes`]: f64::from_be_bytes
1006 /// [`from_le_bytes`]: f64::from_le_bytes
1011 /// let value = f64::from_ne_bytes(if cfg!(target_endian = "big") {
1012 /// [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1014 /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]
1016 /// assert_eq!(value, 12.5);
1018 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1019 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1022 pub const fn from_ne_bytes(bytes: [u8; 8]) -> Self {
1023 Self::from_bits(u64::from_ne_bytes(bytes))
1026 /// Return the ordering between `self` and `other`.
1028 /// Unlike the standard partial comparison between floating point numbers,
1029 /// this comparison always produces an ordering in accordance to
1030 /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1031 /// floating point standard. The values are ordered in the following sequence:
1033 /// - negative quiet NaN
1034 /// - negative signaling NaN
1035 /// - negative infinity
1036 /// - negative numbers
1037 /// - negative subnormal numbers
1040 /// - positive subnormal numbers
1041 /// - positive numbers
1042 /// - positive infinity
1043 /// - positive signaling NaN
1044 /// - positive quiet NaN.
1046 /// The ordering established by this function does not always agree with the
1047 /// [`PartialOrd`] and [`PartialEq`] implementations of `f64`. For example,
1048 /// they consider negative and positive zero equal, while `total_cmp`
1051 /// The interpretation of the signaling NaN bit follows the definition in
1052 /// the IEEE 754 standard, which may not match the interpretation by some of
1053 /// the older, non-conformant (e.g. MIPS) hardware implementations.
1058 /// struct GoodBoy {
1063 /// let mut bois = vec![
1064 /// GoodBoy { name: "Pucci".to_owned(), weight: 0.1 },
1065 /// GoodBoy { name: "Woofer".to_owned(), weight: 99.0 },
1066 /// GoodBoy { name: "Yapper".to_owned(), weight: 10.0 },
1067 /// GoodBoy { name: "Chonk".to_owned(), weight: f64::INFINITY },
1068 /// GoodBoy { name: "Abs. Unit".to_owned(), weight: f64::NAN },
1069 /// GoodBoy { name: "Floaty".to_owned(), weight: -5.0 },
1072 /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1073 /// # assert!(bois.into_iter().map(|b| b.weight)
1074 /// # .zip([-5.0, 0.1, 10.0, 99.0, f64::INFINITY, f64::NAN].iter())
1075 /// # .all(|(a, b)| a.to_bits() == b.to_bits()))
1077 #[stable(feature = "total_cmp", since = "1.62.0")]
1080 pub fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1081 let mut left = self.to_bits() as i64;
1082 let mut right = other.to_bits() as i64;
1084 // In case of negatives, flip all the bits except the sign
1085 // to achieve a similar layout as two's complement integers
1087 // Why does this work? IEEE 754 floats consist of three fields:
1088 // Sign bit, exponent and mantissa. The set of exponent and mantissa
1089 // fields as a whole have the property that their bitwise order is
1090 // equal to the numeric magnitude where the magnitude is defined.
1091 // The magnitude is not normally defined on NaN values, but
1092 // IEEE 754 totalOrder defines the NaN values also to follow the
1093 // bitwise order. This leads to order explained in the doc comment.
1094 // However, the representation of magnitude is the same for negative
1095 // and positive numbers – only the sign bit is different.
1096 // To easily compare the floats as signed integers, we need to
1097 // flip the exponent and mantissa bits in case of negative numbers.
1098 // We effectively convert the numbers to "two's complement" form.
1100 // To do the flipping, we construct a mask and XOR against it.
1101 // We branchlessly calculate an "all-ones except for the sign bit"
1102 // mask from negative-signed values: right shifting sign-extends
1103 // the integer, so we "fill" the mask with sign bits, and then
1104 // convert to unsigned to push one more zero bit.
1105 // On positive values, the mask is all zeros, so it's a no-op.
1106 left ^= (((left >> 63) as u64) >> 1) as i64;
1107 right ^= (((right >> 63) as u64) >> 1) as i64;
1112 /// Restrict a value to a certain interval unless it is NaN.
1114 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1115 /// less than `min`. Otherwise this returns `self`.
1117 /// Note that this function returns NaN if the initial value was NaN as
1122 /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1127 /// assert!((-3.0f64).clamp(-2.0, 1.0) == -2.0);
1128 /// assert!((0.0f64).clamp(-2.0, 1.0) == 0.0);
1129 /// assert!((2.0f64).clamp(-2.0, 1.0) == 1.0);
1130 /// assert!((f64::NAN).clamp(-2.0, 1.0).is_nan());
1132 #[must_use = "method returns a new number and does not mutate the original value"]
1133 #[stable(feature = "clamp", since = "1.50.0")]
1135 pub fn clamp(self, min: f64, max: f64) -> f64 {
1136 assert!(min <= max);