1 //! This module provides constants which are specific to the implementation
2 //! of the `f32` floating point data type.
4 //! *[See also the `f32` primitive type](../../std/primitive.f32.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 `f32`.
20 /// Use [`f32::RADIX`](../../std/primitive.f32.html#associatedconstant.RADIX) instead.
26 /// let r = std::f32::RADIX;
29 /// let r = f32::RADIX;
31 #[stable(feature = "rust1", since = "1.0.0")]
32 pub const RADIX: u32 = f32::RADIX;
34 /// Number of significant digits in base 2.
35 /// Use [`f32::MANTISSA_DIGITS`](../../std/primitive.f32.html#associatedconstant.MANTISSA_DIGITS) instead.
41 /// let d = std::f32::MANTISSA_DIGITS;
44 /// let d = f32::MANTISSA_DIGITS;
46 #[stable(feature = "rust1", since = "1.0.0")]
47 pub const MANTISSA_DIGITS: u32 = f32::MANTISSA_DIGITS;
49 /// Approximate number of significant digits in base 10.
50 /// Use [`f32::DIGITS`](../../std/primitive.f32.html#associatedconstant.DIGITS) instead.
56 /// let d = std::f32::DIGITS;
59 /// let d = f32::DIGITS;
61 #[stable(feature = "rust1", since = "1.0.0")]
62 pub const DIGITS: u32 = f32::DIGITS;
64 /// [Machine epsilon] value for `f32`.
65 /// Use [`f32::EPSILON`](../../std/primitive.f32.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::f32::EPSILON;
78 /// let e = f32::EPSILON;
80 #[stable(feature = "rust1", since = "1.0.0")]
81 pub const EPSILON: f32 = f32::EPSILON;
83 /// Smallest finite `f32` value.
84 /// Use [`f32::MIN`](../../std/primitive.f32.html#associatedconstant.MIN) instead.
90 /// let min = std::f32::MIN;
93 /// let min = f32::MIN;
95 #[stable(feature = "rust1", since = "1.0.0")]
96 pub const MIN: f32 = f32::MIN;
98 /// Smallest positive normal `f32` value.
99 /// Use [`f32::MIN_POSITIVE`](../../std/primitive.f32.html#associatedconstant.MIN_POSITIVE) instead.
104 /// // deprecated way
105 /// let min = std::f32::MIN_POSITIVE;
108 /// let min = f32::MIN_POSITIVE;
110 #[stable(feature = "rust1", since = "1.0.0")]
111 pub const MIN_POSITIVE: f32 = f32::MIN_POSITIVE;
113 /// Largest finite `f32` value.
114 /// Use [`f32::MAX`](../../std/primitive.f32.html#associatedconstant.MAX) instead.
119 /// // deprecated way
120 /// let max = std::f32::MAX;
123 /// let max = f32::MAX;
125 #[stable(feature = "rust1", since = "1.0.0")]
126 pub const MAX: f32 = f32::MAX;
128 /// One greater than the minimum possible normal power of 2 exponent.
129 /// Use [`f32::MIN_EXP`](../../std/primitive.f32.html#associatedconstant.MIN_EXP) instead.
134 /// // deprecated way
135 /// let min = std::f32::MIN_EXP;
138 /// let min = f32::MIN_EXP;
140 #[stable(feature = "rust1", since = "1.0.0")]
141 pub const MIN_EXP: i32 = f32::MIN_EXP;
143 /// Maximum possible power of 2 exponent.
144 /// Use [`f32::MAX_EXP`](../../std/primitive.f32.html#associatedconstant.MAX_EXP) instead.
149 /// // deprecated way
150 /// let max = std::f32::MAX_EXP;
153 /// let max = f32::MAX_EXP;
155 #[stable(feature = "rust1", since = "1.0.0")]
156 pub const MAX_EXP: i32 = f32::MAX_EXP;
158 /// Minimum possible normal power of 10 exponent.
159 /// Use [`f32::MIN_10_EXP`](../../std/primitive.f32.html#associatedconstant.MIN_10_EXP) instead.
164 /// // deprecated way
165 /// let min = std::f32::MIN_10_EXP;
168 /// let min = f32::MIN_10_EXP;
170 #[stable(feature = "rust1", since = "1.0.0")]
171 pub const MIN_10_EXP: i32 = f32::MIN_10_EXP;
173 /// Maximum possible power of 10 exponent.
174 /// Use [`f32::MAX_10_EXP`](../../std/primitive.f32.html#associatedconstant.MAX_10_EXP) instead.
179 /// // deprecated way
180 /// let max = std::f32::MAX_10_EXP;
183 /// let max = f32::MAX_10_EXP;
185 #[stable(feature = "rust1", since = "1.0.0")]
186 pub const MAX_10_EXP: i32 = f32::MAX_10_EXP;
188 /// Not a Number (NaN).
189 /// Use [`f32::NAN`](../../std/primitive.f32.html#associatedconstant.NAN) instead.
194 /// // deprecated way
195 /// let nan = std::f32::NAN;
198 /// let nan = f32::NAN;
200 #[stable(feature = "rust1", since = "1.0.0")]
201 pub const NAN: f32 = f32::NAN;
204 /// Use [`f32::INFINITY`](../../std/primitive.f32.html#associatedconstant.INFINITY) instead.
209 /// // deprecated way
210 /// let inf = std::f32::INFINITY;
213 /// let inf = f32::INFINITY;
215 #[stable(feature = "rust1", since = "1.0.0")]
216 pub const INFINITY: f32 = f32::INFINITY;
218 /// Negative infinity (−∞).
219 /// Use [`f32::NEG_INFINITY`](../../std/primitive.f32.html#associatedconstant.NEG_INFINITY) instead.
224 /// // deprecated way
225 /// let ninf = std::f32::NEG_INFINITY;
228 /// let ninf = f32::NEG_INFINITY;
230 #[stable(feature = "rust1", since = "1.0.0")]
231 pub const NEG_INFINITY: f32 = f32::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: f32 = 3.14159265358979323846264338327950288_f32;
242 /// The full circle constant (τ)
245 #[stable(feature = "tau_constant", since = "1.47.0")]
246 pub const TAU: f32 = 6.28318530717958647692528676655900577_f32;
249 #[stable(feature = "rust1", since = "1.0.0")]
250 pub const FRAC_PI_2: f32 = 1.57079632679489661923132169163975144_f32;
253 #[stable(feature = "rust1", since = "1.0.0")]
254 pub const FRAC_PI_3: f32 = 1.04719755119659774615421446109316763_f32;
257 #[stable(feature = "rust1", since = "1.0.0")]
258 pub const FRAC_PI_4: f32 = 0.785398163397448309615660845819875721_f32;
261 #[stable(feature = "rust1", since = "1.0.0")]
262 pub const FRAC_PI_6: f32 = 0.52359877559829887307710723054658381_f32;
265 #[stable(feature = "rust1", since = "1.0.0")]
266 pub const FRAC_PI_8: f32 = 0.39269908169872415480783042290993786_f32;
269 #[stable(feature = "rust1", since = "1.0.0")]
270 pub const FRAC_1_PI: f32 = 0.318309886183790671537767526745028724_f32;
273 #[stable(feature = "rust1", since = "1.0.0")]
274 pub const FRAC_2_PI: f32 = 0.636619772367581343075535053490057448_f32;
277 #[stable(feature = "rust1", since = "1.0.0")]
278 pub const FRAC_2_SQRT_PI: f32 = 1.12837916709551257389615890312154517_f32;
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub const SQRT_2: f32 = 1.41421356237309504880168872420969808_f32;
285 #[stable(feature = "rust1", since = "1.0.0")]
286 pub const FRAC_1_SQRT_2: f32 = 0.707106781186547524400844362104849039_f32;
288 /// Euler's number (e)
289 #[stable(feature = "rust1", since = "1.0.0")]
290 pub const E: f32 = 2.71828182845904523536028747135266250_f32;
292 /// log<sub>2</sub>(e)
293 #[stable(feature = "rust1", since = "1.0.0")]
294 pub const LOG2_E: f32 = 1.44269504088896340735992468100189214_f32;
296 /// log<sub>2</sub>(10)
297 #[stable(feature = "extra_log_consts", since = "1.43.0")]
298 pub const LOG2_10: f32 = 3.32192809488736234787031942948939018_f32;
300 /// log<sub>10</sub>(e)
301 #[stable(feature = "rust1", since = "1.0.0")]
302 pub const LOG10_E: f32 = 0.434294481903251827651128918916605082_f32;
304 /// log<sub>10</sub>(2)
305 #[stable(feature = "extra_log_consts", since = "1.43.0")]
306 pub const LOG10_2: f32 = 0.301029995663981195213738894724493027_f32;
309 #[stable(feature = "rust1", since = "1.0.0")]
310 pub const LN_2: f32 = 0.693147180559945309417232121458176568_f32;
313 #[stable(feature = "rust1", since = "1.0.0")]
314 pub const LN_10: f32 = 2.30258509299404568401799145468436421_f32;
320 /// The radix or base of the internal representation of `f32`.
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 = 24;
328 /// Approximate number of significant digits in base 10.
329 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
330 pub const DIGITS: u32 = 6;
332 /// [Machine epsilon] value for `f32`.
334 /// This is the difference between `1.0` and the next larger representable number.
336 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
337 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
338 pub const EPSILON: f32 = 1.19209290e-07_f32;
340 /// Smallest finite `f32` value.
341 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
342 pub const MIN: f32 = -3.40282347e+38_f32;
343 /// Smallest positive normal `f32` value.
344 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
345 pub const MIN_POSITIVE: f32 = 1.17549435e-38_f32;
346 /// Largest finite `f32` value.
347 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
348 pub const MAX: f32 = 3.40282347e+38_f32;
350 /// One greater than the minimum possible normal power of 2 exponent.
351 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
352 pub const MIN_EXP: i32 = -125;
353 /// Maximum possible power of 2 exponent.
354 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
355 pub const MAX_EXP: i32 = 128;
357 /// Minimum possible normal power of 10 exponent.
358 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
359 pub const MIN_10_EXP: i32 = -37;
360 /// Maximum possible power of 10 exponent.
361 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
362 pub const MAX_10_EXP: i32 = 38;
364 /// Not a Number (NaN).
365 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
366 pub const NAN: f32 = 0.0_f32 / 0.0_f32;
368 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
369 pub const INFINITY: f32 = 1.0_f32 / 0.0_f32;
370 /// Negative infinity (−∞).
371 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
372 pub const NEG_INFINITY: f32 = -1.0_f32 / 0.0_f32;
374 /// Returns `true` if this value is `NaN`.
377 /// let nan = f32::NAN;
380 /// assert!(nan.is_nan());
381 /// assert!(!f.is_nan());
383 #[stable(feature = "rust1", since = "1.0.0")]
385 pub 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 fn abs_private(self) -> f32 {
394 f32::from_bits(self.to_bits() & 0x7fff_ffff)
397 /// Returns `true` if this value is positive infinity or negative infinity, and
398 /// `false` otherwise.
402 /// let inf = f32::INFINITY;
403 /// let neg_inf = f32::NEG_INFINITY;
404 /// let nan = f32::NAN;
406 /// assert!(!f.is_infinite());
407 /// assert!(!nan.is_infinite());
409 /// assert!(inf.is_infinite());
410 /// assert!(neg_inf.is_infinite());
412 #[stable(feature = "rust1", since = "1.0.0")]
414 pub fn is_infinite(self) -> bool {
415 self.abs_private() == Self::INFINITY
418 /// Returns `true` if this number is neither infinite nor `NaN`.
422 /// let inf = f32::INFINITY;
423 /// let neg_inf = f32::NEG_INFINITY;
424 /// let nan = f32::NAN;
426 /// assert!(f.is_finite());
428 /// assert!(!nan.is_finite());
429 /// assert!(!inf.is_finite());
430 /// assert!(!neg_inf.is_finite());
432 #[stable(feature = "rust1", since = "1.0.0")]
434 pub fn is_finite(self) -> bool {
435 // There's no need to handle NaN separately: if self is NaN,
436 // the comparison is not true, exactly as desired.
437 self.abs_private() < Self::INFINITY
440 /// Returns `true` if the number is neither zero, infinite,
441 /// [subnormal], or `NaN`.
444 /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
445 /// let max = f32::MAX;
446 /// let lower_than_min = 1.0e-40_f32;
447 /// let zero = 0.0_f32;
449 /// assert!(min.is_normal());
450 /// assert!(max.is_normal());
452 /// assert!(!zero.is_normal());
453 /// assert!(!f32::NAN.is_normal());
454 /// assert!(!f32::INFINITY.is_normal());
455 /// // Values between `0` and `min` are Subnormal.
456 /// assert!(!lower_than_min.is_normal());
458 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
459 #[stable(feature = "rust1", since = "1.0.0")]
461 pub fn is_normal(self) -> bool {
462 self.classify() == FpCategory::Normal
465 /// Returns the floating point category of the number. If only one property
466 /// is going to be tested, it is generally faster to use the specific
467 /// predicate instead.
470 /// use std::num::FpCategory;
472 /// let num = 12.4_f32;
473 /// let inf = f32::INFINITY;
475 /// assert_eq!(num.classify(), FpCategory::Normal);
476 /// assert_eq!(inf.classify(), FpCategory::Infinite);
478 #[stable(feature = "rust1", since = "1.0.0")]
479 pub fn classify(self) -> FpCategory {
480 const EXP_MASK: u32 = 0x7f800000;
481 const MAN_MASK: u32 = 0x007fffff;
483 let bits = self.to_bits();
484 match (bits & MAN_MASK, bits & EXP_MASK) {
485 (0, 0) => FpCategory::Zero,
486 (_, 0) => FpCategory::Subnormal,
487 (0, EXP_MASK) => FpCategory::Infinite,
488 (_, EXP_MASK) => FpCategory::Nan,
489 _ => FpCategory::Normal,
493 /// Returns `true` if `self` has a positive sign, including `+0.0`, `NaN`s with
494 /// positive sign bit and positive infinity.
498 /// let g = -7.0_f32;
500 /// assert!(f.is_sign_positive());
501 /// assert!(!g.is_sign_positive());
503 #[stable(feature = "rust1", since = "1.0.0")]
505 pub fn is_sign_positive(self) -> bool {
506 !self.is_sign_negative()
509 /// Returns `true` if `self` has a negative sign, including `-0.0`, `NaN`s with
510 /// negative sign bit and negative infinity.
516 /// assert!(!f.is_sign_negative());
517 /// assert!(g.is_sign_negative());
519 #[stable(feature = "rust1", since = "1.0.0")]
521 pub fn is_sign_negative(self) -> bool {
522 // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
523 // applies to zeros and NaNs as well.
524 self.to_bits() & 0x8000_0000 != 0
527 /// Takes the reciprocal (inverse) of a number, `1/x`.
531 /// let abs_difference = (x.recip() - (1.0 / x)).abs();
533 /// assert!(abs_difference <= f32::EPSILON);
535 #[stable(feature = "rust1", since = "1.0.0")]
537 pub fn recip(self) -> f32 {
541 /// Converts radians to degrees.
544 /// let angle = std::f32::consts::PI;
546 /// let abs_difference = (angle.to_degrees() - 180.0).abs();
548 /// assert!(abs_difference <= f32::EPSILON);
550 #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
552 pub fn to_degrees(self) -> f32 {
553 // Use a constant for better precision.
554 const PIS_IN_180: f32 = 57.2957795130823208767981548141051703_f32;
558 /// Converts degrees to radians.
561 /// let angle = 180.0f32;
563 /// let abs_difference = (angle.to_radians() - std::f32::consts::PI).abs();
565 /// assert!(abs_difference <= f32::EPSILON);
567 #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
569 pub fn to_radians(self) -> f32 {
570 let value: f32 = consts::PI;
571 self * (value / 180.0f32)
574 /// Returns the maximum of the two numbers.
580 /// assert_eq!(x.max(y), y);
583 /// If one of the arguments is NaN, then the other argument is returned.
584 #[stable(feature = "rust1", since = "1.0.0")]
586 pub fn max(self, other: f32) -> f32 {
587 intrinsics::maxnumf32(self, other)
590 /// Returns the minimum of the two numbers.
596 /// assert_eq!(x.min(y), x);
599 /// If one of the arguments is NaN, then the other argument is returned.
600 #[stable(feature = "rust1", since = "1.0.0")]
602 pub fn min(self, other: f32) -> f32 {
603 intrinsics::minnumf32(self, other)
606 /// Rounds toward zero and converts to any primitive integer type,
607 /// assuming that the value is finite and fits in that type.
610 /// let value = 4.6_f32;
611 /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
612 /// assert_eq!(rounded, 4);
614 /// let value = -128.9_f32;
615 /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
616 /// assert_eq!(rounded, i8::MIN);
624 /// * Not be infinite
625 /// * Be representable in the return type `Int`, after truncating off its fractional part
626 #[stable(feature = "float_approx_unchecked_to", since = "1.44.0")]
628 pub unsafe fn to_int_unchecked<Int>(self) -> Int
630 Self: FloatToInt<Int>,
632 // SAFETY: the caller must uphold the safety contract for
633 // `FloatToInt::to_int_unchecked`.
634 unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
637 /// Raw transmutation to `u32`.
639 /// This is currently identical to `transmute::<f32, u32>(self)` on all platforms.
641 /// See `from_bits` for some discussion of the portability of this operation
642 /// (there are almost no issues).
644 /// Note that this function is distinct from `as` casting, which attempts to
645 /// preserve the *numeric* value, and not the bitwise value.
650 /// assert_ne!((1f32).to_bits(), 1f32 as u32); // to_bits() is not casting!
651 /// assert_eq!((12.5f32).to_bits(), 0x41480000);
654 #[stable(feature = "float_bits_conv", since = "1.20.0")]
656 pub fn to_bits(self) -> u32 {
657 // SAFETY: `u32` is a plain old datatype so we can always transmute to it
658 unsafe { mem::transmute(self) }
661 /// Raw transmutation from `u32`.
663 /// This is currently identical to `transmute::<u32, f32>(v)` on all platforms.
664 /// It turns out this is incredibly portable, for two reasons:
666 /// * Floats and Ints have the same endianness on all supported platforms.
667 /// * IEEE-754 very precisely specifies the bit layout of floats.
669 /// However there is one caveat: prior to the 2008 version of IEEE-754, how
670 /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
671 /// (notably x86 and ARM) picked the interpretation that was ultimately
672 /// standardized in 2008, but some didn't (notably MIPS). As a result, all
673 /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
675 /// Rather than trying to preserve signaling-ness cross-platform, this
676 /// implementation favors preserving the exact bits. This means that
677 /// any payloads encoded in NaNs will be preserved even if the result of
678 /// this method is sent over the network from an x86 machine to a MIPS one.
680 /// If the results of this method are only manipulated by the same
681 /// architecture that produced them, then there is no portability concern.
683 /// If the input isn't NaN, then there is no portability concern.
685 /// If you don't care about signalingness (very likely), then there is no
686 /// portability concern.
688 /// Note that this function is distinct from `as` casting, which attempts to
689 /// preserve the *numeric* value, and not the bitwise value.
694 /// let v = f32::from_bits(0x41480000);
695 /// assert_eq!(v, 12.5);
697 #[stable(feature = "float_bits_conv", since = "1.20.0")]
699 pub fn from_bits(v: u32) -> Self {
700 // SAFETY: `u32` is a plain old datatype so we can always transmute from it
701 // It turns out the safety issues with sNaN were overblown! Hooray!
702 unsafe { mem::transmute(v) }
705 /// Return the memory representation of this floating point number as a byte array in
706 /// big-endian (network) byte order.
711 /// let bytes = 12.5f32.to_be_bytes();
712 /// assert_eq!(bytes, [0x41, 0x48, 0x00, 0x00]);
714 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
716 pub fn to_be_bytes(self) -> [u8; 4] {
717 self.to_bits().to_be_bytes()
720 /// Return the memory representation of this floating point number as a byte array in
721 /// little-endian byte order.
726 /// let bytes = 12.5f32.to_le_bytes();
727 /// assert_eq!(bytes, [0x00, 0x00, 0x48, 0x41]);
729 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
731 pub fn to_le_bytes(self) -> [u8; 4] {
732 self.to_bits().to_le_bytes()
735 /// Return the memory representation of this floating point number as a byte array in
736 /// native byte order.
738 /// As the target platform's native endianness is used, portable code
739 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
741 /// [`to_be_bytes`]: #method.to_be_bytes
742 /// [`to_le_bytes`]: #method.to_le_bytes
747 /// let bytes = 12.5f32.to_ne_bytes();
750 /// if cfg!(target_endian = "big") {
751 /// [0x41, 0x48, 0x00, 0x00]
753 /// [0x00, 0x00, 0x48, 0x41]
757 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
759 pub fn to_ne_bytes(self) -> [u8; 4] {
760 self.to_bits().to_ne_bytes()
763 /// Create a floating point value from its representation as a byte array in big endian.
768 /// let value = f32::from_be_bytes([0x41, 0x48, 0x00, 0x00]);
769 /// assert_eq!(value, 12.5);
771 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
773 pub fn from_be_bytes(bytes: [u8; 4]) -> Self {
774 Self::from_bits(u32::from_be_bytes(bytes))
777 /// Create a floating point value from its representation as a byte array in little endian.
782 /// let value = f32::from_le_bytes([0x00, 0x00, 0x48, 0x41]);
783 /// assert_eq!(value, 12.5);
785 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
787 pub fn from_le_bytes(bytes: [u8; 4]) -> Self {
788 Self::from_bits(u32::from_le_bytes(bytes))
791 /// Create a floating point value from its representation as a byte array in native endian.
793 /// As the target platform's native endianness is used, portable code
794 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
795 /// appropriate instead.
797 /// [`from_be_bytes`]: #method.from_be_bytes
798 /// [`from_le_bytes`]: #method.from_le_bytes
803 /// let value = f32::from_ne_bytes(if cfg!(target_endian = "big") {
804 /// [0x41, 0x48, 0x00, 0x00]
806 /// [0x00, 0x00, 0x48, 0x41]
808 /// assert_eq!(value, 12.5);
810 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
812 pub fn from_ne_bytes(bytes: [u8; 4]) -> Self {
813 Self::from_bits(u32::from_ne_bytes(bytes))
816 /// Returns an ordering between self and other values.
817 /// Unlike the standard partial comparison between floating point numbers,
818 /// this comparison always produces an ordering in accordance to
819 /// the totalOrder predicate as defined in IEEE 754 (2008 revision)
820 /// floating point standard. The values are ordered in following order:
821 /// - Negative quiet NaN
822 /// - Negative signaling NaN
823 /// - Negative infinity
824 /// - Negative numbers
825 /// - Negative subnormal numbers
828 /// - Positive subnormal numbers
829 /// - Positive numbers
830 /// - Positive infinity
831 /// - Positive signaling NaN
832 /// - Positive quiet NaN
836 /// #![feature(total_cmp)]
842 /// let mut bois = vec![
843 /// GoodBoy { name: "Pucci".to_owned(), weight: 0.1 },
844 /// GoodBoy { name: "Woofer".to_owned(), weight: 99.0 },
845 /// GoodBoy { name: "Yapper".to_owned(), weight: 10.0 },
846 /// GoodBoy { name: "Chonk".to_owned(), weight: f32::INFINITY },
847 /// GoodBoy { name: "Abs. Unit".to_owned(), weight: f32::NAN },
848 /// GoodBoy { name: "Floaty".to_owned(), weight: -5.0 },
851 /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
852 /// # assert!(bois.into_iter().map(|b| b.weight)
853 /// # .zip([-5.0, 0.1, 10.0, 99.0, f32::INFINITY, f32::NAN].iter())
854 /// # .all(|(a, b)| a.to_bits() == b.to_bits()))
856 #[unstable(feature = "total_cmp", issue = "72599")]
858 pub fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
859 let mut left = self.to_bits() as i32;
860 let mut right = other.to_bits() as i32;
862 // In case of negatives, flip all the bits except the sign
863 // to achieve a similar layout as two's complement integers
865 // Why does this work? IEEE 754 floats consist of three fields:
866 // Sign bit, exponent and mantissa. The set of exponent and mantissa
867 // fields as a whole have the property that their bitwise order is
868 // equal to the numeric magnitude where the magnitude is defined.
869 // The magnitude is not normally defined on NaN values, but
870 // IEEE 754 totalOrder defines the NaN values also to follow the
871 // bitwise order. This leads to order explained in the doc comment.
872 // However, the representation of magnitude is the same for negative
873 // and positive numbers – only the sign bit is different.
874 // To easily compare the floats as signed integers, we need to
875 // flip the exponent and mantissa bits in case of negative numbers.
876 // We effectively convert the numbers to "two's complement" form.
878 // To do the flipping, we construct a mask and XOR against it.
879 // We branchlessly calculate an "all-ones except for the sign bit"
880 // mask from negative-signed values: right shifting sign-extends
881 // the integer, so we "fill" the mask with sign bits, and then
882 // convert to unsigned to push one more zero bit.
883 // On positive values, the mask is all zeros, so it's a no-op.
884 left ^= (((left >> 31) as u32) >> 1) as i32;
885 right ^= (((right >> 31) as u32) >> 1) as i32;