1 //! Constants specific to the `f32` single-precision floating point type.
3 //! *[See also the `f32` primitive type][f32].*
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 `f32` 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 `f32`.
21 /// Use [`f32::RADIX`] instead.
27 /// # #[allow(deprecated, deprecated_in_future)]
28 /// let r = std::f32::RADIX;
31 /// let r = f32::RADIX;
33 #[stable(feature = "rust1", since = "1.0.0")]
34 #[rustc_deprecated(since = "TBD", reason = "replaced by the `RADIX` associated constant on `f32`")]
35 pub const RADIX: u32 = f32::RADIX;
37 /// Number of significant digits in base 2.
38 /// Use [`f32::MANTISSA_DIGITS`] instead.
44 /// # #[allow(deprecated, deprecated_in_future)]
45 /// let d = std::f32::MANTISSA_DIGITS;
48 /// let d = f32::MANTISSA_DIGITS;
50 #[stable(feature = "rust1", since = "1.0.0")]
53 reason = "replaced by the `MANTISSA_DIGITS` associated constant on `f32`"
55 pub const MANTISSA_DIGITS: u32 = f32::MANTISSA_DIGITS;
57 /// Approximate number of significant digits in base 10.
58 /// Use [`f32::DIGITS`] instead.
64 /// # #[allow(deprecated, deprecated_in_future)]
65 /// let d = std::f32::DIGITS;
68 /// let d = f32::DIGITS;
70 #[stable(feature = "rust1", since = "1.0.0")]
71 #[rustc_deprecated(since = "TBD", reason = "replaced by the `DIGITS` associated constant on `f32`")]
72 pub const DIGITS: u32 = f32::DIGITS;
74 /// [Machine epsilon] value for `f32`.
75 /// Use [`f32::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::f32::EPSILON;
89 /// let e = f32::EPSILON;
91 #[stable(feature = "rust1", since = "1.0.0")]
94 reason = "replaced by the `EPSILON` associated constant on `f32`"
96 pub const EPSILON: f32 = f32::EPSILON;
98 /// Smallest finite `f32` value.
99 /// Use [`f32::MIN`] instead.
104 /// // deprecated way
105 /// # #[allow(deprecated, deprecated_in_future)]
106 /// let min = std::f32::MIN;
109 /// let min = f32::MIN;
111 #[stable(feature = "rust1", since = "1.0.0")]
112 #[rustc_deprecated(since = "TBD", reason = "replaced by the `MIN` associated constant on `f32`")]
113 pub const MIN: f32 = f32::MIN;
115 /// Smallest positive normal `f32` value.
116 /// Use [`f32::MIN_POSITIVE`] instead.
121 /// // deprecated way
122 /// # #[allow(deprecated, deprecated_in_future)]
123 /// let min = std::f32::MIN_POSITIVE;
126 /// let min = f32::MIN_POSITIVE;
128 #[stable(feature = "rust1", since = "1.0.0")]
131 reason = "replaced by the `MIN_POSITIVE` associated constant on `f32`"
133 pub const MIN_POSITIVE: f32 = f32::MIN_POSITIVE;
135 /// Largest finite `f32` value.
136 /// Use [`f32::MAX`] instead.
141 /// // deprecated way
142 /// # #[allow(deprecated, deprecated_in_future)]
143 /// let max = std::f32::MAX;
146 /// let max = f32::MAX;
148 #[stable(feature = "rust1", since = "1.0.0")]
149 #[rustc_deprecated(since = "TBD", reason = "replaced by the `MAX` associated constant on `f32`")]
150 pub const MAX: f32 = f32::MAX;
152 /// One greater than the minimum possible normal power of 2 exponent.
153 /// Use [`f32::MIN_EXP`] instead.
158 /// // deprecated way
159 /// # #[allow(deprecated, deprecated_in_future)]
160 /// let min = std::f32::MIN_EXP;
163 /// let min = f32::MIN_EXP;
165 #[stable(feature = "rust1", since = "1.0.0")]
168 reason = "replaced by the `MIN_EXP` associated constant on `f32`"
170 pub const MIN_EXP: i32 = f32::MIN_EXP;
172 /// Maximum possible power of 2 exponent.
173 /// Use [`f32::MAX_EXP`] instead.
178 /// // deprecated way
179 /// # #[allow(deprecated, deprecated_in_future)]
180 /// let max = std::f32::MAX_EXP;
183 /// let max = f32::MAX_EXP;
185 #[stable(feature = "rust1", since = "1.0.0")]
188 reason = "replaced by the `MAX_EXP` associated constant on `f32`"
190 pub const MAX_EXP: i32 = f32::MAX_EXP;
192 /// Minimum possible normal power of 10 exponent.
193 /// Use [`f32::MIN_10_EXP`] instead.
198 /// // deprecated way
199 /// # #[allow(deprecated, deprecated_in_future)]
200 /// let min = std::f32::MIN_10_EXP;
203 /// let min = f32::MIN_10_EXP;
205 #[stable(feature = "rust1", since = "1.0.0")]
208 reason = "replaced by the `MIN_10_EXP` associated constant on `f32`"
210 pub const MIN_10_EXP: i32 = f32::MIN_10_EXP;
212 /// Maximum possible power of 10 exponent.
213 /// Use [`f32::MAX_10_EXP`] instead.
218 /// // deprecated way
219 /// # #[allow(deprecated, deprecated_in_future)]
220 /// let max = std::f32::MAX_10_EXP;
223 /// let max = f32::MAX_10_EXP;
225 #[stable(feature = "rust1", since = "1.0.0")]
228 reason = "replaced by the `MAX_10_EXP` associated constant on `f32`"
230 pub const MAX_10_EXP: i32 = f32::MAX_10_EXP;
232 /// Not a Number (NaN).
233 /// Use [`f32::NAN`] instead.
238 /// // deprecated way
239 /// # #[allow(deprecated, deprecated_in_future)]
240 /// let nan = std::f32::NAN;
243 /// let nan = f32::NAN;
245 #[stable(feature = "rust1", since = "1.0.0")]
246 #[rustc_deprecated(since = "TBD", reason = "replaced by the `NAN` associated constant on `f32`")]
247 pub const NAN: f32 = f32::NAN;
250 /// Use [`f32::INFINITY`] instead.
255 /// // deprecated way
256 /// # #[allow(deprecated, deprecated_in_future)]
257 /// let inf = std::f32::INFINITY;
260 /// let inf = f32::INFINITY;
262 #[stable(feature = "rust1", since = "1.0.0")]
265 reason = "replaced by the `INFINITY` associated constant on `f32`"
267 pub const INFINITY: f32 = f32::INFINITY;
269 /// Negative infinity (−∞).
270 /// Use [`f32::NEG_INFINITY`] instead.
275 /// // deprecated way
276 /// # #[allow(deprecated, deprecated_in_future)]
277 /// let ninf = std::f32::NEG_INFINITY;
280 /// let ninf = f32::NEG_INFINITY;
282 #[stable(feature = "rust1", since = "1.0.0")]
285 reason = "replaced by the `NEG_INFINITY` associated constant on `f32`"
287 pub const NEG_INFINITY: f32 = f32::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: f32 = 3.14159265358979323846264338327950288_f32;
298 /// The full circle constant (τ)
301 #[stable(feature = "tau_constant", since = "1.47.0")]
302 pub const TAU: f32 = 6.28318530717958647692528676655900577_f32;
305 #[stable(feature = "rust1", since = "1.0.0")]
306 pub const FRAC_PI_2: f32 = 1.57079632679489661923132169163975144_f32;
309 #[stable(feature = "rust1", since = "1.0.0")]
310 pub const FRAC_PI_3: f32 = 1.04719755119659774615421446109316763_f32;
313 #[stable(feature = "rust1", since = "1.0.0")]
314 pub const FRAC_PI_4: f32 = 0.785398163397448309615660845819875721_f32;
317 #[stable(feature = "rust1", since = "1.0.0")]
318 pub const FRAC_PI_6: f32 = 0.52359877559829887307710723054658381_f32;
321 #[stable(feature = "rust1", since = "1.0.0")]
322 pub const FRAC_PI_8: f32 = 0.39269908169872415480783042290993786_f32;
325 #[stable(feature = "rust1", since = "1.0.0")]
326 pub const FRAC_1_PI: f32 = 0.318309886183790671537767526745028724_f32;
329 #[stable(feature = "rust1", since = "1.0.0")]
330 pub const FRAC_2_PI: f32 = 0.636619772367581343075535053490057448_f32;
333 #[stable(feature = "rust1", since = "1.0.0")]
334 pub const FRAC_2_SQRT_PI: f32 = 1.12837916709551257389615890312154517_f32;
337 #[stable(feature = "rust1", since = "1.0.0")]
338 pub const SQRT_2: f32 = 1.41421356237309504880168872420969808_f32;
341 #[stable(feature = "rust1", since = "1.0.0")]
342 pub const FRAC_1_SQRT_2: f32 = 0.707106781186547524400844362104849039_f32;
344 /// Euler's number (e)
345 #[stable(feature = "rust1", since = "1.0.0")]
346 pub const E: f32 = 2.71828182845904523536028747135266250_f32;
348 /// log<sub>2</sub>(e)
349 #[stable(feature = "rust1", since = "1.0.0")]
350 pub const LOG2_E: f32 = 1.44269504088896340735992468100189214_f32;
352 /// log<sub>2</sub>(10)
353 #[stable(feature = "extra_log_consts", since = "1.43.0")]
354 pub const LOG2_10: f32 = 3.32192809488736234787031942948939018_f32;
356 /// log<sub>10</sub>(e)
357 #[stable(feature = "rust1", since = "1.0.0")]
358 pub const LOG10_E: f32 = 0.434294481903251827651128918916605082_f32;
360 /// log<sub>10</sub>(2)
361 #[stable(feature = "extra_log_consts", since = "1.43.0")]
362 pub const LOG10_2: f32 = 0.301029995663981195213738894724493027_f32;
365 #[stable(feature = "rust1", since = "1.0.0")]
366 pub const LN_2: f32 = 0.693147180559945309417232121458176568_f32;
369 #[stable(feature = "rust1", since = "1.0.0")]
370 pub const LN_10: f32 = 2.30258509299404568401799145468436421_f32;
376 /// The radix or base of the internal representation of `f32`.
377 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
378 pub const RADIX: u32 = 2;
380 /// Number of significant digits in base 2.
381 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
382 pub const MANTISSA_DIGITS: u32 = 24;
384 /// Approximate number of significant digits in base 10.
385 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
386 pub const DIGITS: u32 = 6;
388 /// [Machine epsilon] value for `f32`.
390 /// This is the difference between `1.0` and the next larger representable number.
392 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
393 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
394 pub const EPSILON: f32 = 1.19209290e-07_f32;
396 /// Smallest finite `f32` value.
397 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
398 pub const MIN: f32 = -3.40282347e+38_f32;
399 /// Smallest positive normal `f32` value.
400 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
401 pub const MIN_POSITIVE: f32 = 1.17549435e-38_f32;
402 /// Largest finite `f32` value.
403 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
404 pub const MAX: f32 = 3.40282347e+38_f32;
406 /// One greater than the minimum possible normal power of 2 exponent.
407 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
408 pub const MIN_EXP: i32 = -125;
409 /// Maximum possible power of 2 exponent.
410 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
411 pub const MAX_EXP: i32 = 128;
413 /// Minimum possible normal power of 10 exponent.
414 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
415 pub const MIN_10_EXP: i32 = -37;
416 /// Maximum possible power of 10 exponent.
417 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
418 pub const MAX_10_EXP: i32 = 38;
420 /// Not a Number (NaN).
421 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
422 pub const NAN: f32 = 0.0_f32 / 0.0_f32;
424 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
425 pub const INFINITY: f32 = 1.0_f32 / 0.0_f32;
426 /// Negative infinity (−∞).
427 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
428 pub const NEG_INFINITY: f32 = -1.0_f32 / 0.0_f32;
430 /// Returns `true` if this value is `NaN`.
433 /// let nan = f32::NAN;
436 /// assert!(nan.is_nan());
437 /// assert!(!f.is_nan());
439 #[stable(feature = "rust1", since = "1.0.0")]
440 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
442 pub const fn is_nan(self) -> bool {
446 // FIXME(#50145): `abs` is publicly unavailable in libcore due to
447 // concerns about portability, so this implementation is for
448 // private use internally.
450 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
451 pub(crate) const fn abs_private(self) -> f32 {
452 f32::from_bits(self.to_bits() & 0x7fff_ffff)
455 /// Returns `true` if this value is positive infinity or negative infinity, and
456 /// `false` otherwise.
460 /// let inf = f32::INFINITY;
461 /// let neg_inf = f32::NEG_INFINITY;
462 /// let nan = f32::NAN;
464 /// assert!(!f.is_infinite());
465 /// assert!(!nan.is_infinite());
467 /// assert!(inf.is_infinite());
468 /// 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 = f32::INFINITY;
482 /// let neg_inf = f32::NEG_INFINITY;
483 /// let nan = f32::NAN;
485 /// assert!(f.is_finite());
487 /// assert!(!nan.is_finite());
488 /// assert!(!inf.is_finite());
489 /// assert!(!neg_inf.is_finite());
491 #[stable(feature = "rust1", since = "1.0.0")]
492 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
494 pub const fn is_finite(self) -> bool {
495 // There's no need to handle NaN separately: if self is NaN,
496 // the comparison is not true, exactly as desired.
497 self.abs_private() < Self::INFINITY
500 /// Returns `true` if the number is [subnormal].
503 /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
504 /// let max = f32::MAX;
505 /// let lower_than_min = 1.0e-40_f32;
506 /// let zero = 0.0_f32;
508 /// assert!(!min.is_subnormal());
509 /// assert!(!max.is_subnormal());
511 /// assert!(!zero.is_subnormal());
512 /// assert!(!f32::NAN.is_subnormal());
513 /// assert!(!f32::INFINITY.is_subnormal());
514 /// // Values between `0` and `min` are Subnormal.
515 /// assert!(lower_than_min.is_subnormal());
517 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
518 #[stable(feature = "is_subnormal", since = "1.53.0")]
519 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
521 pub const fn is_subnormal(self) -> bool {
522 matches!(self.classify(), FpCategory::Subnormal)
525 /// Returns `true` if the number is neither zero, infinite,
526 /// [subnormal], or `NaN`.
529 /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
530 /// let max = f32::MAX;
531 /// let lower_than_min = 1.0e-40_f32;
532 /// let zero = 0.0_f32;
534 /// assert!(min.is_normal());
535 /// assert!(max.is_normal());
537 /// assert!(!zero.is_normal());
538 /// assert!(!f32::NAN.is_normal());
539 /// assert!(!f32::INFINITY.is_normal());
540 /// // Values between `0` and `min` are Subnormal.
541 /// assert!(!lower_than_min.is_normal());
543 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
544 #[stable(feature = "rust1", since = "1.0.0")]
545 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
547 pub const fn is_normal(self) -> bool {
548 matches!(self.classify(), FpCategory::Normal)
551 /// Returns the floating point category of the number. If only one property
552 /// is going to be tested, it is generally faster to use the specific
553 /// predicate instead.
556 /// use std::num::FpCategory;
558 /// let num = 12.4_f32;
559 /// let inf = f32::INFINITY;
561 /// assert_eq!(num.classify(), FpCategory::Normal);
562 /// assert_eq!(inf.classify(), FpCategory::Infinite);
564 #[stable(feature = "rust1", since = "1.0.0")]
565 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
566 pub const fn classify(self) -> FpCategory {
567 const EXP_MASK: u32 = 0x7f800000;
568 const MAN_MASK: u32 = 0x007fffff;
570 let bits = self.to_bits();
571 match (bits & MAN_MASK, bits & EXP_MASK) {
572 (0, 0) => FpCategory::Zero,
573 (_, 0) => FpCategory::Subnormal,
574 (0, EXP_MASK) => FpCategory::Infinite,
575 (_, EXP_MASK) => FpCategory::Nan,
576 _ => FpCategory::Normal,
580 /// Returns `true` if `self` has a positive sign, including `+0.0`, `NaN`s with
581 /// positive sign bit and positive infinity.
585 /// let g = -7.0_f32;
587 /// assert!(f.is_sign_positive());
588 /// assert!(!g.is_sign_positive());
590 #[stable(feature = "rust1", since = "1.0.0")]
591 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
593 pub const fn is_sign_positive(self) -> bool {
594 !self.is_sign_negative()
597 /// Returns `true` if `self` has a negative sign, including `-0.0`, `NaN`s with
598 /// negative sign bit and negative infinity.
604 /// assert!(!f.is_sign_negative());
605 /// assert!(g.is_sign_negative());
607 #[stable(feature = "rust1", since = "1.0.0")]
608 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
610 pub const fn is_sign_negative(self) -> bool {
611 // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
612 // applies to zeros and NaNs as well.
613 self.to_bits() & 0x8000_0000 != 0
616 /// Takes the reciprocal (inverse) of a number, `1/x`.
620 /// let abs_difference = (x.recip() - (1.0 / x)).abs();
622 /// assert!(abs_difference <= f32::EPSILON);
624 #[stable(feature = "rust1", since = "1.0.0")]
626 pub fn recip(self) -> f32 {
630 /// Converts radians to degrees.
633 /// let angle = std::f32::consts::PI;
635 /// let abs_difference = (angle.to_degrees() - 180.0).abs();
637 /// assert!(abs_difference <= f32::EPSILON);
639 #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
641 pub fn to_degrees(self) -> f32 {
642 // Use a constant for better precision.
643 const PIS_IN_180: f32 = 57.2957795130823208767981548141051703_f32;
647 /// Converts degrees to radians.
650 /// let angle = 180.0f32;
652 /// let abs_difference = (angle.to_radians() - std::f32::consts::PI).abs();
654 /// assert!(abs_difference <= f32::EPSILON);
656 #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
658 pub fn to_radians(self) -> f32 {
659 let value: f32 = consts::PI;
660 self * (value / 180.0f32)
663 /// Returns the maximum of the two numbers.
669 /// assert_eq!(x.max(y), y);
672 /// If one of the arguments is NaN, then the other argument is returned.
673 #[stable(feature = "rust1", since = "1.0.0")]
675 pub fn max(self, other: f32) -> f32 {
676 intrinsics::maxnumf32(self, other)
679 /// Returns the minimum of the two numbers.
685 /// assert_eq!(x.min(y), x);
688 /// If one of the arguments is NaN, then the other argument is returned.
689 #[stable(feature = "rust1", since = "1.0.0")]
691 pub fn min(self, other: f32) -> f32 {
692 intrinsics::minnumf32(self, other)
695 /// Rounds toward zero and converts to any primitive integer type,
696 /// assuming that the value is finite and fits in that type.
699 /// let value = 4.6_f32;
700 /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
701 /// assert_eq!(rounded, 4);
703 /// let value = -128.9_f32;
704 /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
705 /// assert_eq!(rounded, i8::MIN);
713 /// * Not be infinite
714 /// * Be representable in the return type `Int`, after truncating off its fractional part
715 #[stable(feature = "float_approx_unchecked_to", since = "1.44.0")]
717 pub unsafe fn to_int_unchecked<Int>(self) -> Int
719 Self: FloatToInt<Int>,
721 // SAFETY: the caller must uphold the safety contract for
722 // `FloatToInt::to_int_unchecked`.
723 unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
726 /// Raw transmutation to `u32`.
728 /// This is currently identical to `transmute::<f32, u32>(self)` on all platforms.
730 /// See [`from_bits`](Self::from_bits) for some discussion of the
731 /// portability of this operation (there are almost no issues).
733 /// Note that this function is distinct from `as` casting, which attempts to
734 /// preserve the *numeric* value, and not the bitwise value.
739 /// assert_ne!((1f32).to_bits(), 1f32 as u32); // to_bits() is not casting!
740 /// assert_eq!((12.5f32).to_bits(), 0x41480000);
743 #[stable(feature = "float_bits_conv", since = "1.20.0")]
744 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
746 pub const fn to_bits(self) -> u32 {
747 // SAFETY: `u32` is a plain old datatype so we can always transmute to it
748 unsafe { mem::transmute(self) }
751 /// Raw transmutation from `u32`.
753 /// This is currently identical to `transmute::<u32, f32>(v)` on all platforms.
754 /// It turns out this is incredibly portable, for two reasons:
756 /// * Floats and Ints have the same endianness on all supported platforms.
757 /// * IEEE-754 very precisely specifies the bit layout of floats.
759 /// However there is one caveat: prior to the 2008 version of IEEE-754, how
760 /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
761 /// (notably x86 and ARM) picked the interpretation that was ultimately
762 /// standardized in 2008, but some didn't (notably MIPS). As a result, all
763 /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
765 /// Rather than trying to preserve signaling-ness cross-platform, this
766 /// implementation favors preserving the exact bits. This means that
767 /// any payloads encoded in NaNs will be preserved even if the result of
768 /// this method is sent over the network from an x86 machine to a MIPS one.
770 /// If the results of this method are only manipulated by the same
771 /// architecture that produced them, then there is no portability concern.
773 /// If the input isn't NaN, then there is no portability concern.
775 /// If you don't care about signalingness (very likely), then there is no
776 /// portability concern.
778 /// Note that this function is distinct from `as` casting, which attempts to
779 /// preserve the *numeric* value, and not the bitwise value.
784 /// let v = f32::from_bits(0x41480000);
785 /// assert_eq!(v, 12.5);
787 #[stable(feature = "float_bits_conv", since = "1.20.0")]
788 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
790 pub const fn from_bits(v: u32) -> Self {
791 // SAFETY: `u32` is a plain old datatype so we can always transmute from it
792 // It turns out the safety issues with sNaN were overblown! Hooray!
793 unsafe { mem::transmute(v) }
796 /// Return the memory representation of this floating point number as a byte array in
797 /// big-endian (network) byte order.
802 /// let bytes = 12.5f32.to_be_bytes();
803 /// assert_eq!(bytes, [0x41, 0x48, 0x00, 0x00]);
805 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
806 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
808 pub const fn to_be_bytes(self) -> [u8; 4] {
809 self.to_bits().to_be_bytes()
812 /// Return the memory representation of this floating point number as a byte array in
813 /// little-endian byte order.
818 /// let bytes = 12.5f32.to_le_bytes();
819 /// assert_eq!(bytes, [0x00, 0x00, 0x48, 0x41]);
821 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
822 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
824 pub const fn to_le_bytes(self) -> [u8; 4] {
825 self.to_bits().to_le_bytes()
828 /// Return the memory representation of this floating point number as a byte array in
829 /// native byte order.
831 /// As the target platform's native endianness is used, portable code
832 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
834 /// [`to_be_bytes`]: f32::to_be_bytes
835 /// [`to_le_bytes`]: f32::to_le_bytes
840 /// let bytes = 12.5f32.to_ne_bytes();
843 /// if cfg!(target_endian = "big") {
844 /// [0x41, 0x48, 0x00, 0x00]
846 /// [0x00, 0x00, 0x48, 0x41]
850 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
851 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
853 pub const fn to_ne_bytes(self) -> [u8; 4] {
854 self.to_bits().to_ne_bytes()
857 /// Create a floating point value from its representation as a byte array in big endian.
862 /// let value = f32::from_be_bytes([0x41, 0x48, 0x00, 0x00]);
863 /// assert_eq!(value, 12.5);
865 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
866 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
868 pub const fn from_be_bytes(bytes: [u8; 4]) -> Self {
869 Self::from_bits(u32::from_be_bytes(bytes))
872 /// Create a floating point value from its representation as a byte array in little endian.
877 /// let value = f32::from_le_bytes([0x00, 0x00, 0x48, 0x41]);
878 /// assert_eq!(value, 12.5);
880 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
881 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
883 pub const fn from_le_bytes(bytes: [u8; 4]) -> Self {
884 Self::from_bits(u32::from_le_bytes(bytes))
887 /// Create a floating point value from its representation as a byte array in native endian.
889 /// As the target platform's native endianness is used, portable code
890 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
891 /// appropriate instead.
893 /// [`from_be_bytes`]: f32::from_be_bytes
894 /// [`from_le_bytes`]: f32::from_le_bytes
899 /// let value = f32::from_ne_bytes(if cfg!(target_endian = "big") {
900 /// [0x41, 0x48, 0x00, 0x00]
902 /// [0x00, 0x00, 0x48, 0x41]
904 /// assert_eq!(value, 12.5);
906 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
907 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
909 pub const fn from_ne_bytes(bytes: [u8; 4]) -> Self {
910 Self::from_bits(u32::from_ne_bytes(bytes))
913 /// Returns an ordering between self and other values.
914 /// Unlike the standard partial comparison between floating point numbers,
915 /// this comparison always produces an ordering in accordance to
916 /// the totalOrder predicate as defined in IEEE 754 (2008 revision)
917 /// floating point standard. The values are ordered in following order:
918 /// - Negative quiet NaN
919 /// - Negative signaling NaN
920 /// - Negative infinity
921 /// - Negative numbers
922 /// - Negative subnormal numbers
925 /// - Positive subnormal numbers
926 /// - Positive numbers
927 /// - Positive infinity
928 /// - Positive signaling NaN
929 /// - Positive quiet NaN
931 /// Note that this function does not always agree with the [`PartialOrd`]
932 /// and [`PartialEq`] implementations of `f32`. In particular, they regard
933 /// negative and positive zero as equal, while `total_cmp` doesn't.
937 /// #![feature(total_cmp)]
943 /// let mut bois = vec![
944 /// GoodBoy { name: "Pucci".to_owned(), weight: 0.1 },
945 /// GoodBoy { name: "Woofer".to_owned(), weight: 99.0 },
946 /// GoodBoy { name: "Yapper".to_owned(), weight: 10.0 },
947 /// GoodBoy { name: "Chonk".to_owned(), weight: f32::INFINITY },
948 /// GoodBoy { name: "Abs. Unit".to_owned(), weight: f32::NAN },
949 /// GoodBoy { name: "Floaty".to_owned(), weight: -5.0 },
952 /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
953 /// # assert!(bois.into_iter().map(|b| b.weight)
954 /// # .zip([-5.0, 0.1, 10.0, 99.0, f32::INFINITY, f32::NAN].iter())
955 /// # .all(|(a, b)| a.to_bits() == b.to_bits()))
957 #[unstable(feature = "total_cmp", issue = "72599")]
959 pub fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
960 let mut left = self.to_bits() as i32;
961 let mut right = other.to_bits() as i32;
963 // In case of negatives, flip all the bits except the sign
964 // to achieve a similar layout as two's complement integers
966 // Why does this work? IEEE 754 floats consist of three fields:
967 // Sign bit, exponent and mantissa. The set of exponent and mantissa
968 // fields as a whole have the property that their bitwise order is
969 // equal to the numeric magnitude where the magnitude is defined.
970 // The magnitude is not normally defined on NaN values, but
971 // IEEE 754 totalOrder defines the NaN values also to follow the
972 // bitwise order. This leads to order explained in the doc comment.
973 // However, the representation of magnitude is the same for negative
974 // and positive numbers – only the sign bit is different.
975 // To easily compare the floats as signed integers, we need to
976 // flip the exponent and mantissa bits in case of negative numbers.
977 // We effectively convert the numbers to "two's complement" form.
979 // To do the flipping, we construct a mask and XOR against it.
980 // We branchlessly calculate an "all-ones except for the sign bit"
981 // mask from negative-signed values: right shifting sign-extends
982 // the integer, so we "fill" the mask with sign bits, and then
983 // convert to unsigned to push one more zero bit.
984 // On positive values, the mask is all zeros, so it's a no-op.
985 left ^= (((left >> 31) as u32) >> 1) as i32;
986 right ^= (((right >> 31) as u32) >> 1) as i32;
991 /// Restrict a value to a certain interval unless it is NaN.
993 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
994 /// less than `min`. Otherwise this returns `self`.
996 /// Note that this function returns NaN if the initial value was NaN as
1001 /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1006 /// assert!((-3.0f32).clamp(-2.0, 1.0) == -2.0);
1007 /// assert!((0.0f32).clamp(-2.0, 1.0) == 0.0);
1008 /// assert!((2.0f32).clamp(-2.0, 1.0) == 1.0);
1009 /// assert!((f32::NAN).clamp(-2.0, 1.0).is_nan());
1011 #[must_use = "method returns a new number and does not mutate the original value"]
1012 #[stable(feature = "clamp", since = "1.50.0")]
1014 pub fn clamp(self, min: f32, max: f32) -> f32 {
1015 assert!(min <= max);