1 //! This module provides constants which are specific to the implementation
2 //! of the `f64` floating point data type.
4 //! *[See also the `f64` primitive type](../../std/primitive.f64.html).*
6 //! Mathematically significant numbers are provided in the `consts` sub-module.
8 //! Although using these constants won’t cause compilation warnings,
9 //! new code should use the associated constants directly on the primitive type.
11 #![stable(feature = "rust1", since = "1.0.0")]
13 use crate::convert
::FloatToInt
;
15 use crate::intrinsics
;
17 use crate::num
::FpCategory
;
19 /// The radix or base of the internal representation of `f64`.
20 /// Use [`f64::RADIX`](../../std/primitive.f64.html#associatedconstant.RADIX) instead.
26 /// let r = std::f64::RADIX;
29 /// let r = f64::RADIX;
31 #[stable(feature = "rust1", since = "1.0.0")]
32 pub const RADIX
: u32 = f64::RADIX
;
34 /// Number of significant digits in base 2.
35 /// Use [`f64::MANTISSA_DIGITS`](../../std/primitive.f64.html#associatedconstant.MANTISSA_DIGITS) instead.
41 /// let d = std::f64::MANTISSA_DIGITS;
44 /// let d = f64::MANTISSA_DIGITS;
46 #[stable(feature = "rust1", since = "1.0.0")]
47 pub const MANTISSA_DIGITS
: u32 = f64::MANTISSA_DIGITS
;
49 /// Approximate number of significant digits in base 10.
50 /// Use [`f64::DIGITS`](../../std/primitive.f64.html#associatedconstant.DIGITS) instead.
56 /// let d = std::f64::DIGITS;
59 /// let d = f64::DIGITS;
61 #[stable(feature = "rust1", since = "1.0.0")]
62 pub const DIGITS
: u32 = f64::DIGITS
;
64 /// [Machine epsilon] value for `f64`.
65 /// Use [`f64::EPSILON`](../../std/primitive.f64.html#associatedconstant.EPSILON) instead.
67 /// This is the difference between `1.0` and the next larger representable number.
69 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
75 /// let e = std::f64::EPSILON;
78 /// let e = f64::EPSILON;
80 #[stable(feature = "rust1", since = "1.0.0")]
81 pub const EPSILON
: f64 = f64::EPSILON
;
83 /// Smallest finite `f64` value.
84 /// Use [`f64::MIN`](../../std/primitive.f64.html#associatedconstant.MIN) instead.
90 /// let min = std::f64::MIN;
93 /// let min = f64::MIN;
95 #[stable(feature = "rust1", since = "1.0.0")]
96 pub const MIN
: f64 = f64::MIN
;
98 /// Smallest positive normal `f64` value.
99 /// Use [`f64::MIN_POSITIVE`](../../std/primitive.f64.html#associatedconstant.MIN_POSITIVE) instead.
104 /// // deprecated way
105 /// let min = std::f64::MIN_POSITIVE;
108 /// let min = f64::MIN_POSITIVE;
110 #[stable(feature = "rust1", since = "1.0.0")]
111 pub const MIN_POSITIVE
: f64 = f64::MIN_POSITIVE
;
113 /// Largest finite `f64` value.
114 /// Use [`f64::MAX`](../../std/primitive.f64.html#associatedconstant.MAX) instead.
119 /// // deprecated way
120 /// let max = std::f64::MAX;
123 /// let max = f64::MAX;
125 #[stable(feature = "rust1", since = "1.0.0")]
126 pub const MAX
: f64 = f64::MAX
;
128 /// One greater than the minimum possible normal power of 2 exponent.
129 /// Use [`f64::MIN_EXP`](../../std/primitive.f64.html#associatedconstant.MIN_EXP) instead.
134 /// // deprecated way
135 /// let min = std::f64::MIN_EXP;
138 /// let min = f64::MIN_EXP;
140 #[stable(feature = "rust1", since = "1.0.0")]
141 pub const MIN_EXP
: i32 = f64::MIN_EXP
;
143 /// Maximum possible power of 2 exponent.
144 /// Use [`f64::MAX_EXP`](../../std/primitive.f64.html#associatedconstant.MAX_EXP) instead.
149 /// // deprecated way
150 /// let max = std::f64::MAX_EXP;
153 /// let max = f64::MAX_EXP;
155 #[stable(feature = "rust1", since = "1.0.0")]
156 pub const MAX_EXP
: i32 = f64::MAX_EXP
;
158 /// Minimum possible normal power of 10 exponent.
159 /// Use [`f64::MIN_10_EXP`](../../std/primitive.f64.html#associatedconstant.MIN_10_EXP) instead.
164 /// // deprecated way
165 /// let min = std::f64::MIN_10_EXP;
168 /// let min = f64::MIN_10_EXP;
170 #[stable(feature = "rust1", since = "1.0.0")]
171 pub const MIN_10_EXP
: i32 = f64::MIN_10_EXP
;
173 /// Maximum possible power of 10 exponent.
174 /// Use [`f64::MAX_10_EXP`](../../std/primitive.f64.html#associatedconstant.MAX_10_EXP) instead.
179 /// // deprecated way
180 /// let max = std::f64::MAX_10_EXP;
183 /// let max = f64::MAX_10_EXP;
185 #[stable(feature = "rust1", since = "1.0.0")]
186 pub const MAX_10_EXP
: i32 = f64::MAX_10_EXP
;
188 /// Not a Number (NaN).
189 /// Use [`f64::NAN`](../../std/primitive.f64.html#associatedconstant.NAN) instead.
194 /// // deprecated way
195 /// let nan = std::f64::NAN;
198 /// let nan = f64::NAN;
200 #[stable(feature = "rust1", since = "1.0.0")]
201 pub const NAN
: f64 = f64::NAN
;
204 /// Use [`f64::INFINITY`](../../std/primitive.f64.html#associatedconstant.INFINITY) instead.
209 /// // deprecated way
210 /// let inf = std::f64::INFINITY;
213 /// let inf = f64::INFINITY;
215 #[stable(feature = "rust1", since = "1.0.0")]
216 pub const INFINITY
: f64 = f64::INFINITY
;
218 /// Negative infinity (−∞).
219 /// Use [`f64::NEG_INFINITY`](../../std/primitive.f64.html#associatedconstant.NEG_INFINITY) instead.
224 /// // deprecated way
225 /// let ninf = std::f64::NEG_INFINITY;
228 /// let ninf = f64::NEG_INFINITY;
230 #[stable(feature = "rust1", since = "1.0.0")]
231 pub const NEG_INFINITY
: f64 = f64::NEG_INFINITY
;
233 /// Basic mathematical constants.
234 #[stable(feature = "rust1", since = "1.0.0")]
236 // FIXME: replace with mathematical constants from cmath.
238 /// Archimedes' constant (π)
239 #[stable(feature = "rust1", since = "1.0.0")]
240 pub const PI
: f64 = 3.14159265358979323846264338327950288_f64;
242 /// The full circle constant (τ)
245 #[stable(feature = "tau_constant", since = "1.47.0")]
246 pub const TAU
: f64 = 6.28318530717958647692528676655900577_f64;
249 #[stable(feature = "rust1", since = "1.0.0")]
250 pub const FRAC_PI_2
: f64 = 1.57079632679489661923132169163975144_f64;
253 #[stable(feature = "rust1", since = "1.0.0")]
254 pub const FRAC_PI_3
: f64 = 1.04719755119659774615421446109316763_f64;
257 #[stable(feature = "rust1", since = "1.0.0")]
258 pub const FRAC_PI_4
: f64 = 0.785398163397448309615660845819875721_f64;
261 #[stable(feature = "rust1", since = "1.0.0")]
262 pub const FRAC_PI_6
: f64 = 0.52359877559829887307710723054658381_f64;
265 #[stable(feature = "rust1", since = "1.0.0")]
266 pub const FRAC_PI_8
: f64 = 0.39269908169872415480783042290993786_f64;
269 #[stable(feature = "rust1", since = "1.0.0")]
270 pub const FRAC_1_PI
: f64 = 0.318309886183790671537767526745028724_f64;
273 #[stable(feature = "rust1", since = "1.0.0")]
274 pub const FRAC_2_PI
: f64 = 0.636619772367581343075535053490057448_f64;
277 #[stable(feature = "rust1", since = "1.0.0")]
278 pub const FRAC_2_SQRT_PI
: f64 = 1.12837916709551257389615890312154517_f64;
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub const SQRT_2
: f64 = 1.41421356237309504880168872420969808_f64;
285 #[stable(feature = "rust1", since = "1.0.0")]
286 pub const FRAC_1_SQRT_2
: f64 = 0.707106781186547524400844362104849039_f64;
288 /// Euler's number (e)
289 #[stable(feature = "rust1", since = "1.0.0")]
290 pub const E
: f64 = 2.71828182845904523536028747135266250_f64;
292 /// log<sub>2</sub>(10)
293 #[stable(feature = "extra_log_consts", since = "1.43.0")]
294 pub const LOG2_10
: f64 = 3.32192809488736234787031942948939018_f64;
296 /// log<sub>2</sub>(e)
297 #[stable(feature = "rust1", since = "1.0.0")]
298 pub const LOG2_E
: f64 = 1.44269504088896340735992468100189214_f64;
300 /// log<sub>10</sub>(2)
301 #[stable(feature = "extra_log_consts", since = "1.43.0")]
302 pub const LOG10_2
: f64 = 0.301029995663981195213738894724493027_f64;
304 /// log<sub>10</sub>(e)
305 #[stable(feature = "rust1", since = "1.0.0")]
306 pub const LOG10_E
: f64 = 0.434294481903251827651128918916605082_f64;
309 #[stable(feature = "rust1", since = "1.0.0")]
310 pub const LN_2
: f64 = 0.693147180559945309417232121458176568_f64;
313 #[stable(feature = "rust1", since = "1.0.0")]
314 pub const LN_10
: f64 = 2.30258509299404568401799145468436421_f64;
320 /// The radix or base of the internal representation of `f64`.
321 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
322 pub const RADIX
: u32 = 2;
324 /// Number of significant digits in base 2.
325 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
326 pub const MANTISSA_DIGITS
: u32 = 53;
327 /// Approximate number of significant digits in base 10.
328 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
329 pub const DIGITS
: u32 = 15;
331 /// [Machine epsilon] value for `f64`.
333 /// This is the difference between `1.0` and the next larger representable number.
335 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
336 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
337 pub const EPSILON
: f64 = 2.2204460492503131e-16_f64;
339 /// Smallest finite `f64` value.
340 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
341 pub const MIN
: f64 = -1.7976931348623157e+308_f64;
342 /// Smallest positive normal `f64` value.
343 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
344 pub const MIN_POSITIVE
: f64 = 2.2250738585072014e-308_f64;
345 /// Largest finite `f64` value.
346 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
347 pub const MAX
: f64 = 1.7976931348623157e+308_f64;
349 /// One greater than the minimum possible normal power of 2 exponent.
350 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
351 pub const MIN_EXP
: i32 = -1021;
352 /// Maximum possible power of 2 exponent.
353 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
354 pub const MAX_EXP
: i32 = 1024;
356 /// Minimum possible normal power of 10 exponent.
357 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
358 pub const MIN_10_EXP
: i32 = -307;
359 /// Maximum possible power of 10 exponent.
360 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
361 pub const MAX_10_EXP
: i32 = 308;
363 /// Not a Number (NaN).
364 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
365 pub const NAN
: f64 = 0.0_f64 / 0.0_f64;
367 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
368 pub const INFINITY
: f64 = 1.0_f64 / 0.0_f64;
369 /// Negative infinity (−∞).
370 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
371 pub const NEG_INFINITY
: f64 = -1.0_f64 / 0.0_f64;
373 /// Returns `true` if this value is `NaN`.
376 /// let nan = f64::NAN;
379 /// assert!(nan.is_nan());
380 /// assert!(!f.is_nan());
382 #[stable(feature = "rust1", since = "1.0.0")]
383 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
385 pub const fn is_nan(self) -> bool
{
389 // FIXME(#50145): `abs` is publicly unavailable in libcore due to
390 // concerns about portability, so this implementation is for
391 // private use internally.
393 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
394 const fn abs_private(self) -> f64 {
395 f64::from_bits(self.to_bits() & 0x7fff_ffff_ffff_ffff)
398 /// Returns `true` if this value is positive infinity or negative infinity, and
399 /// `false` otherwise.
403 /// let inf = f64::INFINITY;
404 /// let neg_inf = f64::NEG_INFINITY;
405 /// let nan = f64::NAN;
407 /// assert!(!f.is_infinite());
408 /// assert!(!nan.is_infinite());
410 /// assert!(inf.is_infinite());
411 /// assert!(neg_inf.is_infinite());
413 #[stable(feature = "rust1", since = "1.0.0")]
414 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
416 pub const fn is_infinite(self) -> bool
{
417 self.abs_private() == Self::INFINITY
420 /// Returns `true` if this number is neither infinite nor `NaN`.
424 /// let inf: f64 = f64::INFINITY;
425 /// let neg_inf: f64 = f64::NEG_INFINITY;
426 /// let nan: f64 = f64::NAN;
428 /// assert!(f.is_finite());
430 /// assert!(!nan.is_finite());
431 /// assert!(!inf.is_finite());
432 /// assert!(!neg_inf.is_finite());
434 #[stable(feature = "rust1", since = "1.0.0")]
435 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
437 pub const fn is_finite(self) -> bool
{
438 // There's no need to handle NaN separately: if self is NaN,
439 // the comparison is not true, exactly as desired.
440 self.abs_private() < Self::INFINITY
443 /// Returns `true` if the number is neither zero, infinite,
444 /// [subnormal], or `NaN`.
447 /// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308f64
448 /// let max = f64::MAX;
449 /// let lower_than_min = 1.0e-308_f64;
450 /// let zero = 0.0f64;
452 /// assert!(min.is_normal());
453 /// assert!(max.is_normal());
455 /// assert!(!zero.is_normal());
456 /// assert!(!f64::NAN.is_normal());
457 /// assert!(!f64::INFINITY.is_normal());
458 /// // Values between `0` and `min` are Subnormal.
459 /// assert!(!lower_than_min.is_normal());
461 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
462 #[stable(feature = "rust1", since = "1.0.0")]
463 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
465 pub const fn is_normal(self) -> bool
{
466 matches
!(self.classify(), FpCategory
::Normal
)
469 /// Returns the floating point category of the number. If only one property
470 /// is going to be tested, it is generally faster to use the specific
471 /// predicate instead.
474 /// use std::num::FpCategory;
476 /// let num = 12.4_f64;
477 /// let inf = f64::INFINITY;
479 /// assert_eq!(num.classify(), FpCategory::Normal);
480 /// assert_eq!(inf.classify(), FpCategory::Infinite);
482 #[stable(feature = "rust1", since = "1.0.0")]
483 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
484 pub const fn classify(self) -> FpCategory
{
485 const EXP_MASK
: u64 = 0x7ff0000000000000;
486 const MAN_MASK
: u64 = 0x000fffffffffffff;
488 let bits
= self.to_bits();
489 match (bits
& MAN_MASK
, bits
& EXP_MASK
) {
490 (0, 0) => FpCategory
::Zero
,
491 (_
, 0) => FpCategory
::Subnormal
,
492 (0, EXP_MASK
) => FpCategory
::Infinite
,
493 (_
, EXP_MASK
) => FpCategory
::Nan
,
494 _
=> FpCategory
::Normal
,
498 /// Returns `true` if `self` has a positive sign, including `+0.0`, `NaN`s with
499 /// positive sign bit and positive infinity.
503 /// let g = -7.0_f64;
505 /// assert!(f.is_sign_positive());
506 /// assert!(!g.is_sign_positive());
508 #[stable(feature = "rust1", since = "1.0.0")]
509 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
511 pub const fn is_sign_positive(self) -> bool
{
512 !self.is_sign_negative()
515 #[stable(feature = "rust1", since = "1.0.0")]
516 #[rustc_deprecated(since = "1.0.0", reason = "renamed to is_sign_positive")]
519 pub fn is_positive(self) -> bool
{
520 self.is_sign_positive()
523 /// Returns `true` if `self` has a negative sign, including `-0.0`, `NaN`s with
524 /// negative sign bit and negative infinity.
528 /// let g = -7.0_f64;
530 /// assert!(!f.is_sign_negative());
531 /// assert!(g.is_sign_negative());
533 #[stable(feature = "rust1", since = "1.0.0")]
534 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
536 pub const fn is_sign_negative(self) -> bool
{
537 self.to_bits() & 0x8000_0000_0000_0000 != 0
540 #[stable(feature = "rust1", since = "1.0.0")]
541 #[rustc_deprecated(since = "1.0.0", reason = "renamed to is_sign_negative")]
544 pub fn is_negative(self) -> bool
{
545 self.is_sign_negative()
548 /// Takes the reciprocal (inverse) of a number, `1/x`.
552 /// let abs_difference = (x.recip() - (1.0 / x)).abs();
554 /// assert!(abs_difference < 1e-10);
556 #[stable(feature = "rust1", since = "1.0.0")]
558 pub fn recip(self) -> f64 {
562 /// Converts radians to degrees.
565 /// let angle = std::f64::consts::PI;
567 /// let abs_difference = (angle.to_degrees() - 180.0).abs();
569 /// assert!(abs_difference < 1e-10);
571 #[stable(feature = "rust1", since = "1.0.0")]
573 pub fn to_degrees(self) -> f64 {
574 // The division here is correctly rounded with respect to the true
575 // value of 180/π. (This differs from f32, where a constant must be
576 // used to ensure a correctly rounded result.)
577 self * (180.0f64 / consts
::PI
)
580 /// Converts degrees to radians.
583 /// let angle = 180.0_f64;
585 /// let abs_difference = (angle.to_radians() - std::f64::consts::PI).abs();
587 /// assert!(abs_difference < 1e-10);
589 #[stable(feature = "rust1", since = "1.0.0")]
591 pub fn to_radians(self) -> f64 {
592 let value
: f64 = consts
::PI
;
593 self * (value
/ 180.0)
596 /// Returns the maximum of the two numbers.
602 /// assert_eq!(x.max(y), y);
605 /// If one of the arguments is NaN, then the other argument is returned.
606 #[stable(feature = "rust1", since = "1.0.0")]
608 pub fn max(self, other
: f64) -> f64 {
609 intrinsics
::maxnumf64(self, other
)
612 /// Returns the minimum of the two numbers.
618 /// assert_eq!(x.min(y), x);
621 /// If one of the arguments is NaN, then the other argument is returned.
622 #[stable(feature = "rust1", since = "1.0.0")]
624 pub fn min(self, other
: f64) -> f64 {
625 intrinsics
::minnumf64(self, other
)
628 /// Rounds toward zero and converts to any primitive integer type,
629 /// assuming that the value is finite and fits in that type.
632 /// let value = 4.6_f64;
633 /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
634 /// assert_eq!(rounded, 4);
636 /// let value = -128.9_f64;
637 /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
638 /// assert_eq!(rounded, i8::MIN);
646 /// * Not be infinite
647 /// * Be representable in the return type `Int`, after truncating off its fractional part
648 #[stable(feature = "float_approx_unchecked_to", since = "1.44.0")]
650 pub unsafe fn to_int_unchecked
<Int
>(self) -> Int
652 Self: FloatToInt
<Int
>,
654 // SAFETY: the caller must uphold the safety contract for
655 // `FloatToInt::to_int_unchecked`.
656 unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
659 /// Raw transmutation to `u64`.
661 /// This is currently identical to `transmute::<f64, u64>(self)` on all platforms.
663 /// See `from_bits` for some discussion of the portability of this operation
664 /// (there are almost no issues).
666 /// Note that this function is distinct from `as` casting, which attempts to
667 /// preserve the *numeric* value, and not the bitwise value.
672 /// assert!((1f64).to_bits() != 1f64 as u64); // to_bits() is not casting!
673 /// assert_eq!((12.5f64).to_bits(), 0x4029000000000000);
676 #[stable(feature = "float_bits_conv", since = "1.20.0")]
677 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
679 pub const fn to_bits(self) -> u64 {
680 // SAFETY: `u64` is a plain old datatype so we can always transmute to it
681 unsafe { mem::transmute(self) }
684 /// Raw transmutation from `u64`.
686 /// This is currently identical to `transmute::<u64, f64>(v)` on all platforms.
687 /// It turns out this is incredibly portable, for two reasons:
689 /// * Floats and Ints have the same endianness on all supported platforms.
690 /// * IEEE-754 very precisely specifies the bit layout of floats.
692 /// However there is one caveat: prior to the 2008 version of IEEE-754, how
693 /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
694 /// (notably x86 and ARM) picked the interpretation that was ultimately
695 /// standardized in 2008, but some didn't (notably MIPS). As a result, all
696 /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
698 /// Rather than trying to preserve signaling-ness cross-platform, this
699 /// implementation favors preserving the exact bits. This means that
700 /// any payloads encoded in NaNs will be preserved even if the result of
701 /// this method is sent over the network from an x86 machine to a MIPS one.
703 /// If the results of this method are only manipulated by the same
704 /// architecture that produced them, then there is no portability concern.
706 /// If the input isn't NaN, then there is no portability concern.
708 /// If you don't care about signaling-ness (very likely), then there is no
709 /// portability concern.
711 /// Note that this function is distinct from `as` casting, which attempts to
712 /// preserve the *numeric* value, and not the bitwise value.
717 /// let v = f64::from_bits(0x4029000000000000);
718 /// assert_eq!(v, 12.5);
720 #[stable(feature = "float_bits_conv", since = "1.20.0")]
721 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
723 pub const fn from_bits(v
: u64) -> Self {
724 // SAFETY: `u64` is a plain old datatype so we can always transmute from it
725 // It turns out the safety issues with sNaN were overblown! Hooray!
726 unsafe { mem::transmute(v) }
729 /// Return the memory representation of this floating point number as a byte array in
730 /// big-endian (network) byte order.
735 /// let bytes = 12.5f64.to_be_bytes();
736 /// assert_eq!(bytes, [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
738 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
739 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
741 pub const fn to_be_bytes(self) -> [u8; 8] {
742 self.to_bits().to_be_bytes()
745 /// Return the memory representation of this floating point number as a byte array in
746 /// little-endian byte order.
751 /// let bytes = 12.5f64.to_le_bytes();
752 /// assert_eq!(bytes, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]);
754 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
755 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
757 pub const fn to_le_bytes(self) -> [u8; 8] {
758 self.to_bits().to_le_bytes()
761 /// Return the memory representation of this floating point number as a byte array in
762 /// native byte order.
764 /// As the target platform's native endianness is used, portable code
765 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
767 /// [`to_be_bytes`]: #method.to_be_bytes
768 /// [`to_le_bytes`]: #method.to_le_bytes
773 /// let bytes = 12.5f64.to_ne_bytes();
776 /// if cfg!(target_endian = "big") {
777 /// [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
779 /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]
783 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
784 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
786 pub const fn to_ne_bytes(self) -> [u8; 8] {
787 self.to_bits().to_ne_bytes()
790 /// Create a floating point value from its representation as a byte array in big endian.
795 /// let value = f64::from_be_bytes([0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
796 /// assert_eq!(value, 12.5);
798 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
799 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
801 pub const fn from_be_bytes(bytes
: [u8; 8]) -> Self {
802 Self::from_bits(u64::from_be_bytes(bytes
))
805 /// Create a floating point value from its representation as a byte array in little endian.
810 /// let value = f64::from_le_bytes([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]);
811 /// assert_eq!(value, 12.5);
813 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
814 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
816 pub const fn from_le_bytes(bytes
: [u8; 8]) -> Self {
817 Self::from_bits(u64::from_le_bytes(bytes
))
820 /// Create a floating point value from its representation as a byte array in native endian.
822 /// As the target platform's native endianness is used, portable code
823 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
824 /// appropriate instead.
826 /// [`from_be_bytes`]: #method.from_be_bytes
827 /// [`from_le_bytes`]: #method.from_le_bytes
832 /// let value = f64::from_ne_bytes(if cfg!(target_endian = "big") {
833 /// [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
835 /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]
837 /// assert_eq!(value, 12.5);
839 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
840 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
842 pub const fn from_ne_bytes(bytes
: [u8; 8]) -> Self {
843 Self::from_bits(u64::from_ne_bytes(bytes
))
846 /// Returns an ordering between self and other values.
847 /// Unlike the standard partial comparison between floating point numbers,
848 /// this comparison always produces an ordering in accordance to
849 /// the totalOrder predicate as defined in IEEE 754 (2008 revision)
850 /// floating point standard. The values are ordered in following order:
851 /// - Negative quiet NaN
852 /// - Negative signaling NaN
853 /// - Negative infinity
854 /// - Negative numbers
855 /// - Negative subnormal numbers
858 /// - Positive subnormal numbers
859 /// - Positive numbers
860 /// - Positive infinity
861 /// - Positive signaling NaN
862 /// - Positive quiet NaN
866 /// #![feature(total_cmp)]
872 /// let mut bois = vec![
873 /// GoodBoy { name: "Pucci".to_owned(), weight: 0.1 },
874 /// GoodBoy { name: "Woofer".to_owned(), weight: 99.0 },
875 /// GoodBoy { name: "Yapper".to_owned(), weight: 10.0 },
876 /// GoodBoy { name: "Chonk".to_owned(), weight: f64::INFINITY },
877 /// GoodBoy { name: "Abs. Unit".to_owned(), weight: f64::NAN },
878 /// GoodBoy { name: "Floaty".to_owned(), weight: -5.0 },
881 /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
882 /// # assert!(bois.into_iter().map(|b| b.weight)
883 /// # .zip([-5.0, 0.1, 10.0, 99.0, f64::INFINITY, f64::NAN].iter())
884 /// # .all(|(a, b)| a.to_bits() == b.to_bits()))
886 #[unstable(feature = "total_cmp", issue = "72599")]
888 pub fn total_cmp(&self, other
: &Self) -> crate::cmp
::Ordering
{
889 let mut left
= self.to_bits() as i64;
890 let mut right
= other
.to_bits() as i64;
892 // In case of negatives, flip all the bits except the sign
893 // to achieve a similar layout as two's complement integers
895 // Why does this work? IEEE 754 floats consist of three fields:
896 // Sign bit, exponent and mantissa. The set of exponent and mantissa
897 // fields as a whole have the property that their bitwise order is
898 // equal to the numeric magnitude where the magnitude is defined.
899 // The magnitude is not normally defined on NaN values, but
900 // IEEE 754 totalOrder defines the NaN values also to follow the
901 // bitwise order. This leads to order explained in the doc comment.
902 // However, the representation of magnitude is the same for negative
903 // and positive numbers – only the sign bit is different.
904 // To easily compare the floats as signed integers, we need to
905 // flip the exponent and mantissa bits in case of negative numbers.
906 // We effectively convert the numbers to "two's complement" form.
908 // To do the flipping, we construct a mask and XOR against it.
909 // We branchlessly calculate an "all-ones except for the sign bit"
910 // mask from negative-signed values: right shifting sign-extends
911 // the integer, so we "fill" the mask with sign bits, and then
912 // convert to unsigned to push one more zero bit.
913 // On positive values, the mask is all zeros, so it's a no-op.
914 left ^
= (((left
>> 63) as u64) >> 1) as i64;
915 right ^
= (((right
>> 63) as u64) >> 1) as i64;