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;
375 /// The radix or base of the internal representation of `f32`.
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 = 24;
383 /// Approximate number of significant digits in base 10.
384 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
385 pub const DIGITS: u32 = 6;
387 /// [Machine epsilon] value for `f32`.
389 /// This is the difference between `1.0` and the next larger representable number.
391 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
392 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
393 pub const EPSILON: f32 = 1.19209290e-07_f32;
395 /// Smallest finite `f32` value.
396 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
397 pub const MIN: f32 = -3.40282347e+38_f32;
398 /// Smallest positive normal `f32` value.
399 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
400 pub const MIN_POSITIVE: f32 = 1.17549435e-38_f32;
401 /// Largest finite `f32` value.
402 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
403 pub const MAX: f32 = 3.40282347e+38_f32;
405 /// One greater than the minimum possible normal power of 2 exponent.
406 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
407 pub const MIN_EXP: i32 = -125;
408 /// Maximum possible power of 2 exponent.
409 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
410 pub const MAX_EXP: i32 = 128;
412 /// Minimum possible normal power of 10 exponent.
413 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
414 pub const MIN_10_EXP: i32 = -37;
415 /// Maximum possible power of 10 exponent.
416 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
417 pub const MAX_10_EXP: i32 = 38;
419 /// Not a Number (NaN).
420 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
421 pub const NAN: f32 = 0.0_f32 / 0.0_f32;
423 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
424 pub const INFINITY: f32 = 1.0_f32 / 0.0_f32;
425 /// Negative infinity (−∞).
426 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
427 pub const NEG_INFINITY: f32 = -1.0_f32 / 0.0_f32;
429 /// Returns `true` if this value is `NaN`.
432 /// let nan = f32::NAN;
435 /// assert!(nan.is_nan());
436 /// 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 // SAFETY: This transmutation is fine. Probably. For the reasons std is using it.
453 unsafe { mem::transmute::<u32, f32>(mem::transmute::<f32, u32>(self) & 0x7fff_ffff) }
456 /// Returns `true` if this value is positive infinity or negative infinity, and
457 /// `false` otherwise.
461 /// let inf = f32::INFINITY;
462 /// let neg_inf = f32::NEG_INFINITY;
463 /// let nan = f32::NAN;
465 /// assert!(!f.is_infinite());
466 /// assert!(!nan.is_infinite());
468 /// assert!(inf.is_infinite());
469 /// assert!(neg_inf.is_infinite());
472 #[stable(feature = "rust1", since = "1.0.0")]
473 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
475 pub const fn is_infinite(self) -> bool {
476 // Getting clever with transmutation can result in incorrect answers on some FPUs
477 // FIXME: alter the Rust <-> Rust calling convention to prevent this problem.
478 // See https://github.com/rust-lang/rust/issues/72327
479 (self == f32::INFINITY) | (self == f32::NEG_INFINITY)
482 /// Returns `true` if this number is neither infinite nor `NaN`.
486 /// let inf = f32::INFINITY;
487 /// let neg_inf = f32::NEG_INFINITY;
488 /// let nan = f32::NAN;
490 /// assert!(f.is_finite());
492 /// assert!(!nan.is_finite());
493 /// assert!(!inf.is_finite());
494 /// assert!(!neg_inf.is_finite());
497 #[stable(feature = "rust1", since = "1.0.0")]
498 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
500 pub const fn is_finite(self) -> bool {
501 // There's no need to handle NaN separately: if self is NaN,
502 // the comparison is not true, exactly as desired.
503 self.abs_private() < Self::INFINITY
506 /// Returns `true` if the number is [subnormal].
509 /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
510 /// let max = f32::MAX;
511 /// let lower_than_min = 1.0e-40_f32;
512 /// let zero = 0.0_f32;
514 /// assert!(!min.is_subnormal());
515 /// assert!(!max.is_subnormal());
517 /// assert!(!zero.is_subnormal());
518 /// assert!(!f32::NAN.is_subnormal());
519 /// assert!(!f32::INFINITY.is_subnormal());
520 /// // Values between `0` and `min` are Subnormal.
521 /// assert!(lower_than_min.is_subnormal());
523 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
525 #[stable(feature = "is_subnormal", since = "1.53.0")]
526 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
528 pub const fn is_subnormal(self) -> bool {
529 matches!(self.classify(), FpCategory::Subnormal)
532 /// Returns `true` if the number is neither zero, infinite,
533 /// [subnormal], or `NaN`.
536 /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
537 /// let max = f32::MAX;
538 /// let lower_than_min = 1.0e-40_f32;
539 /// let zero = 0.0_f32;
541 /// assert!(min.is_normal());
542 /// assert!(max.is_normal());
544 /// assert!(!zero.is_normal());
545 /// assert!(!f32::NAN.is_normal());
546 /// assert!(!f32::INFINITY.is_normal());
547 /// // Values between `0` and `min` are Subnormal.
548 /// assert!(!lower_than_min.is_normal());
550 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
552 #[stable(feature = "rust1", since = "1.0.0")]
553 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
555 pub const fn is_normal(self) -> bool {
556 matches!(self.classify(), FpCategory::Normal)
559 /// Returns the floating point category of the number. If only one property
560 /// is going to be tested, it is generally faster to use the specific
561 /// predicate instead.
564 /// use std::num::FpCategory;
566 /// let num = 12.4_f32;
567 /// let inf = f32::INFINITY;
569 /// assert_eq!(num.classify(), FpCategory::Normal);
570 /// assert_eq!(inf.classify(), FpCategory::Infinite);
572 #[stable(feature = "rust1", since = "1.0.0")]
573 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
574 pub const fn classify(self) -> FpCategory {
575 // A previous implementation tried to only use bitmask-based checks,
576 // using f32::to_bits to transmute the float to its bit repr and match on that.
577 // Unfortunately, floating point numbers can be much worse than that.
578 // This also needs to not result in recursive evaluations of f64::to_bits.
580 // On some processors, in some cases, LLVM will "helpfully" lower floating point ops,
581 // in spite of a request for them using f32 and f64, to things like x87 operations.
582 // These have an f64's mantissa, but can have a larger than normal exponent.
583 // FIXME(jubilee): Using x87 operations is never necessary in order to function
584 // on x86 processors for Rust-to-Rust calls, so this issue should not happen.
585 // Code generation should be adjusted to use non-C calling conventions, avoiding this.
587 if self.is_infinite() {
588 // Thus, a value may compare unequal to infinity, despite having a "full" exponent mask.
590 } else if self.is_nan() {
591 // And it may not be NaN, as it can simply be an "overextended" finite value.
594 // However, std can't simply compare to zero to check for zero, either,
595 // as correctness requires avoiding equality tests that may be Subnormal == -0.0
596 // because it may be wrong under "denormals are zero" and "flush to zero" modes.
597 // Most of std's targets don't use those, but they are used for thumbv7neon.
598 // So, this does use bitpattern matching for the rest.
600 // SAFETY: f32 to u32 is fine. Usually.
601 // If classify has gotten this far, the value is definitely in one of these categories.
602 unsafe { f32::partial_classify(self) }
606 // This doesn't actually return a right answer for NaN on purpose,
607 // seeing as how it cannot correctly discern between a floating point NaN,
608 // and some normal floating point numbers truncated from an x87 FPU.
609 // FIXME(jubilee): This probably could at least answer things correctly for Infinity,
610 // like the f64 version does, but I need to run more checks on how things go on x86.
611 // I fear losing mantissa data that would have answered that differently.
614 // This requires making sure you call this function for values it answers correctly on,
615 // otherwise it returns a wrong answer. This is not important for memory safety per se,
616 // but getting floats correct is important for not accidentally leaking const eval
617 // runtime-deviating logic which may or may not be acceptable.
618 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
619 const unsafe fn partial_classify(self) -> FpCategory {
620 const EXP_MASK: u32 = 0x7f800000;
621 const MAN_MASK: u32 = 0x007fffff;
623 // SAFETY: The caller is not asking questions for which this will tell lies.
624 let b = unsafe { mem::transmute::<f32, u32>(self) };
625 match (b & MAN_MASK, b & EXP_MASK) {
626 (0, 0) => FpCategory::Zero,
627 (_, 0) => FpCategory::Subnormal,
628 _ => FpCategory::Normal,
632 // This operates on bits, and only bits, so it can ignore concerns about weird FPUs.
633 // FIXME(jubilee): In a just world, this would be the entire impl for classify,
634 // plus a transmute. We do not live in a just world, but we can make it more so.
635 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
636 const fn classify_bits(b: u32) -> FpCategory {
637 const EXP_MASK: u32 = 0x7f800000;
638 const MAN_MASK: u32 = 0x007fffff;
640 match (b & MAN_MASK, b & EXP_MASK) {
641 (0, EXP_MASK) => FpCategory::Infinite,
642 (_, EXP_MASK) => FpCategory::Nan,
643 (0, 0) => FpCategory::Zero,
644 (_, 0) => FpCategory::Subnormal,
645 _ => FpCategory::Normal,
649 /// Returns `true` if `self` has a positive sign, including `+0.0`, `NaN`s with
650 /// positive sign bit and positive infinity.
654 /// let g = -7.0_f32;
656 /// assert!(f.is_sign_positive());
657 /// assert!(!g.is_sign_positive());
660 #[stable(feature = "rust1", since = "1.0.0")]
661 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
663 pub const fn is_sign_positive(self) -> bool {
664 !self.is_sign_negative()
667 /// Returns `true` if `self` has a negative sign, including `-0.0`, `NaN`s with
668 /// negative sign bit and negative infinity.
674 /// assert!(!f.is_sign_negative());
675 /// assert!(g.is_sign_negative());
678 #[stable(feature = "rust1", since = "1.0.0")]
679 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
681 pub const fn is_sign_negative(self) -> bool {
682 // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
683 // applies to zeros and NaNs as well.
684 // SAFETY: This is just transmuting to get the sign bit, it's fine.
685 unsafe { mem::transmute::<f32, u32>(self) & 0x8000_0000 != 0 }
688 /// Takes the reciprocal (inverse) of a number, `1/x`.
692 /// let abs_difference = (x.recip() - (1.0 / x)).abs();
694 /// assert!(abs_difference <= f32::EPSILON);
696 #[must_use = "this returns the result of the operation, without modifying the original"]
697 #[stable(feature = "rust1", since = "1.0.0")]
699 pub fn recip(self) -> f32 {
703 /// Converts radians to degrees.
706 /// let angle = std::f32::consts::PI;
708 /// let abs_difference = (angle.to_degrees() - 180.0).abs();
710 /// assert!(abs_difference <= f32::EPSILON);
712 #[must_use = "this returns the result of the operation, \
713 without modifying the original"]
714 #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
716 pub fn to_degrees(self) -> f32 {
717 // Use a constant for better precision.
718 const PIS_IN_180: f32 = 57.2957795130823208767981548141051703_f32;
722 /// Converts degrees to radians.
725 /// let angle = 180.0f32;
727 /// let abs_difference = (angle.to_radians() - std::f32::consts::PI).abs();
729 /// assert!(abs_difference <= f32::EPSILON);
731 #[must_use = "this returns the result of the operation, \
732 without modifying the original"]
733 #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
735 pub fn to_radians(self) -> f32 {
736 let value: f32 = consts::PI;
737 self * (value / 180.0f32)
740 /// Returns the maximum of the two numbers.
742 /// Follows the IEEE-754 2008 semantics for maxNum, except for handling of signaling NaNs.
743 /// This matches the behavior of libm’s fmax.
749 /// assert_eq!(x.max(y), y);
752 /// If one of the arguments is NaN, then the other argument is returned.
753 #[must_use = "this returns the result of the comparison, without modifying either input"]
754 #[stable(feature = "rust1", since = "1.0.0")]
756 pub fn max(self, other: f32) -> f32 {
757 intrinsics::maxnumf32(self, other)
760 /// Returns the minimum of the two numbers.
762 /// Follows the IEEE-754 2008 semantics for minNum, except for handling of signaling NaNs.
763 /// This matches the behavior of libm’s fmin.
769 /// assert_eq!(x.min(y), x);
772 /// If one of the arguments is NaN, then the other argument is returned.
773 #[must_use = "this returns the result of the comparison, without modifying either input"]
774 #[stable(feature = "rust1", since = "1.0.0")]
776 pub fn min(self, other: f32) -> f32 {
777 intrinsics::minnumf32(self, other)
780 /// Returns the maximum of the two numbers, propagating NaNs.
782 /// This returns NaN when *either* argument is NaN, as opposed to
783 /// [`f32::max`] which only returns NaN when *both* arguments are NaN.
786 /// #![feature(float_minimum_maximum)]
790 /// assert_eq!(x.maximum(y), y);
791 /// assert!(x.maximum(f32::NAN).is_nan());
794 /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the greater
795 /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
796 /// Note that this follows the semantics specified in IEEE 754-2019.
797 #[must_use = "this returns the result of the comparison, without modifying either input"]
798 #[unstable(feature = "float_minimum_maximum", issue = "91079")]
800 pub fn maximum(self, other: f32) -> f32 {
803 } else if other > self {
805 } else if self == other {
806 if self.is_sign_positive() && other.is_sign_negative() { self } else { other }
812 /// Returns the minimum of the two numbers, propagating NaNs.
814 /// This returns NaN when *either* argument is NaN, as opposed to
815 /// [`f32::min`] which only returns NaN when *both* arguments are NaN.
818 /// #![feature(float_minimum_maximum)]
822 /// assert_eq!(x.minimum(y), x);
823 /// assert!(x.minimum(f32::NAN).is_nan());
826 /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the lesser
827 /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
828 /// Note that this follows the semantics specified in IEEE 754-2019.
829 #[must_use = "this returns the result of the comparison, without modifying either input"]
830 #[unstable(feature = "float_minimum_maximum", issue = "91079")]
832 pub fn minimum(self, other: f32) -> f32 {
835 } else if other < self {
837 } else if self == other {
838 if self.is_sign_negative() && other.is_sign_positive() { self } else { other }
844 /// Rounds toward zero and converts to any primitive integer type,
845 /// assuming that the value is finite and fits in that type.
848 /// let value = 4.6_f32;
849 /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
850 /// assert_eq!(rounded, 4);
852 /// let value = -128.9_f32;
853 /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
854 /// assert_eq!(rounded, i8::MIN);
862 /// * Not be infinite
863 /// * Be representable in the return type `Int`, after truncating off its fractional part
864 #[must_use = "this returns the result of the operation, \
865 without modifying the original"]
866 #[stable(feature = "float_approx_unchecked_to", since = "1.44.0")]
868 pub unsafe fn to_int_unchecked<Int>(self) -> Int
870 Self: FloatToInt<Int>,
872 // SAFETY: the caller must uphold the safety contract for
873 // `FloatToInt::to_int_unchecked`.
874 unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
877 /// Raw transmutation to `u32`.
879 /// This is currently identical to `transmute::<f32, u32>(self)` on all platforms.
881 /// See [`from_bits`](Self::from_bits) for some discussion of the
882 /// portability of this operation (there are almost no issues).
884 /// Note that this function is distinct from `as` casting, which attempts to
885 /// preserve the *numeric* value, and not the bitwise value.
890 /// assert_ne!((1f32).to_bits(), 1f32 as u32); // to_bits() is not casting!
891 /// assert_eq!((12.5f32).to_bits(), 0x41480000);
894 #[must_use = "this returns the result of the operation, \
895 without modifying the original"]
896 #[stable(feature = "float_bits_conv", since = "1.20.0")]
897 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
899 pub const fn to_bits(self) -> u32 {
900 // SAFETY: `u32` is a plain old datatype so we can always transmute to it.
903 // It turns out that at runtime, it is possible for a floating point number
904 // to be subject to a floating point mode that alters nonzero subnormal numbers
905 // to zero on reads and writes, aka "denormals are zero" and "flush to zero".
906 // This is not a problem per se, but at least one tier2 platform for Rust
907 // actually exhibits this behavior by default.
909 // In addition, on x86 targets with SSE or SSE2 disabled and the x87 FPU enabled,
910 // i.e. not soft-float, the way Rust does parameter passing can actually alter
911 // a number that is "not infinity" to have the same exponent as infinity,
912 // in a slightly unpredictable manner.
914 // And, of course evaluating to a NaN value is fairly nondeterministic.
915 // More precisely: when NaN should be returned is knowable, but which NaN?
916 // So far that's defined by a combination of LLVM and the CPU, not Rust.
917 // This function, however, allows observing the bitstring of a NaN,
918 // thus introspection on CTFE.
920 // In order to preserve, at least for the moment, const-to-runtime equivalence,
921 // we reject any of these possible situations from happening.
922 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
923 const fn ct_f32_to_u32(ct: f32) -> u32 {
924 match ct.classify() {
926 panic!("const-eval error: cannot use f32::to_bits on a NaN")
928 FpCategory::Subnormal => {
929 panic!("const-eval error: cannot use f32::to_bits on a subnormal number")
931 FpCategory::Infinite =>
932 // SAFETY: Infinity per se is fine
933 unsafe { mem::transmute::<f32, u32>(ct) },
934 FpCategory::Zero | FpCategory::Normal => {
935 // SAFETY: We have a normal floating point number. Now we transmute, i.e. do a bitcopy.
936 let bits: u32 = unsafe { mem::transmute::<f32, u32>(ct) };
937 // Let's doublecheck to make sure it wasn't a weird float by truncating it.
938 if bits >> 23 & 0xFF == 0xFF {
940 "const-eval error: an unusually large x87 floating point value should not leak into const eval"
947 // SAFETY: `u32` is a plain old datatype so we can always... uh...
948 // ...look, just pretend you forgot what you just read.
949 // Stability concerns.
950 let rt_f32_to_u32 = |rt| unsafe { mem::transmute::<f32, u32>(rt) };
951 // SAFETY: We use internal implementations that either always work or fail at compile time.
952 unsafe { intrinsics::const_eval_select((self,), ct_f32_to_u32, rt_f32_to_u32) }
955 /// Raw transmutation from `u32`.
957 /// This is currently identical to `transmute::<u32, f32>(v)` on all platforms.
958 /// It turns out this is incredibly portable, for two reasons:
960 /// * Floats and Ints have the same endianness on all supported platforms.
961 /// * IEEE-754 very precisely specifies the bit layout of floats.
963 /// However there is one caveat: prior to the 2008 version of IEEE-754, how
964 /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
965 /// (notably x86 and ARM) picked the interpretation that was ultimately
966 /// standardized in 2008, but some didn't (notably MIPS). As a result, all
967 /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
969 /// Rather than trying to preserve signaling-ness cross-platform, this
970 /// implementation favors preserving the exact bits. This means that
971 /// any payloads encoded in NaNs will be preserved even if the result of
972 /// this method is sent over the network from an x86 machine to a MIPS one.
974 /// If the results of this method are only manipulated by the same
975 /// architecture that produced them, then there is no portability concern.
977 /// If the input isn't NaN, then there is no portability concern.
979 /// If you don't care about signalingness (very likely), then there is no
980 /// portability concern.
982 /// Note that this function is distinct from `as` casting, which attempts to
983 /// preserve the *numeric* value, and not the bitwise value.
988 /// let v = f32::from_bits(0x41480000);
989 /// assert_eq!(v, 12.5);
991 #[stable(feature = "float_bits_conv", since = "1.20.0")]
992 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
995 pub const fn from_bits(v: u32) -> Self {
996 // It turns out the safety issues with sNaN were overblown! Hooray!
997 // SAFETY: `u32` is a plain old datatype so we can always transmute from it
1000 // It turns out that at runtime, it is possible for a floating point number
1001 // to be subject to floating point modes that alter nonzero subnormal numbers
1002 // to zero on reads and writes, aka "denormals are zero" and "flush to zero".
1003 // This is not a problem usually, but at least one tier2 platform for Rust
1004 // actually exhibits this behavior by default: thumbv7neon
1005 // aka "the Neon FPU in AArch32 state"
1007 // In addition, on x86 targets with SSE or SSE2 disabled and the x87 FPU enabled,
1008 // i.e. not soft-float, the way Rust does parameter passing can actually alter
1009 // a number that is "not infinity" to have the same exponent as infinity,
1010 // in a slightly unpredictable manner.
1012 // And, of course evaluating to a NaN value is fairly nondeterministic.
1013 // More precisely: when NaN should be returned is knowable, but which NaN?
1014 // So far that's defined by a combination of LLVM and the CPU, not Rust.
1015 // This function, however, allows observing the bitstring of a NaN,
1016 // thus introspection on CTFE.
1018 // In order to preserve, at least for the moment, const-to-runtime equivalence,
1019 // reject any of these possible situations from happening.
1020 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1021 const fn ct_u32_to_f32(ct: u32) -> f32 {
1022 match f32::classify_bits(ct) {
1023 FpCategory::Subnormal => {
1024 panic!("const-eval error: cannot use f32::from_bits on a subnormal number");
1026 FpCategory::Nan => {
1027 panic!("const-eval error: cannot use f32::from_bits on NaN");
1029 // SAFETY: It's not a frumious number
1030 _ => unsafe { mem::transmute::<u32, f32>(ct) },
1033 // SAFETY: `u32` is a plain old datatype so we can always... uh...
1034 // ...look, just pretend you forgot what you just read.
1035 // Stability concerns.
1036 let rt_u32_to_f32 = |rt| unsafe { mem::transmute::<u32, f32>(rt) };
1037 // SAFETY: We use internal implementations that either always work or fail at compile time.
1038 unsafe { intrinsics::const_eval_select((v,), ct_u32_to_f32, rt_u32_to_f32) }
1041 /// Return the memory representation of this floating point number as a byte array in
1042 /// big-endian (network) byte order.
1047 /// let bytes = 12.5f32.to_be_bytes();
1048 /// assert_eq!(bytes, [0x41, 0x48, 0x00, 0x00]);
1050 #[must_use = "this returns the result of the operation, \
1051 without modifying the original"]
1052 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1053 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1055 pub const fn to_be_bytes(self) -> [u8; 4] {
1056 self.to_bits().to_be_bytes()
1059 /// Return the memory representation of this floating point number as a byte array in
1060 /// little-endian byte order.
1065 /// let bytes = 12.5f32.to_le_bytes();
1066 /// assert_eq!(bytes, [0x00, 0x00, 0x48, 0x41]);
1068 #[must_use = "this returns the result of the operation, \
1069 without modifying the original"]
1070 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1071 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1073 pub const fn to_le_bytes(self) -> [u8; 4] {
1074 self.to_bits().to_le_bytes()
1077 /// Return the memory representation of this floating point number as a byte array in
1078 /// native byte order.
1080 /// As the target platform's native endianness is used, portable code
1081 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1083 /// [`to_be_bytes`]: f32::to_be_bytes
1084 /// [`to_le_bytes`]: f32::to_le_bytes
1089 /// let bytes = 12.5f32.to_ne_bytes();
1092 /// if cfg!(target_endian = "big") {
1093 /// [0x41, 0x48, 0x00, 0x00]
1095 /// [0x00, 0x00, 0x48, 0x41]
1099 #[must_use = "this returns the result of the operation, \
1100 without modifying the original"]
1101 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1102 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1104 pub const fn to_ne_bytes(self) -> [u8; 4] {
1105 self.to_bits().to_ne_bytes()
1108 /// Create a floating point value from its representation as a byte array in big endian.
1113 /// let value = f32::from_be_bytes([0x41, 0x48, 0x00, 0x00]);
1114 /// assert_eq!(value, 12.5);
1116 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1117 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1120 pub const fn from_be_bytes(bytes: [u8; 4]) -> Self {
1121 Self::from_bits(u32::from_be_bytes(bytes))
1124 /// Create a floating point value from its representation as a byte array in little endian.
1129 /// let value = f32::from_le_bytes([0x00, 0x00, 0x48, 0x41]);
1130 /// assert_eq!(value, 12.5);
1132 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1133 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1136 pub const fn from_le_bytes(bytes: [u8; 4]) -> Self {
1137 Self::from_bits(u32::from_le_bytes(bytes))
1140 /// Create a floating point value from its representation as a byte array in native endian.
1142 /// As the target platform's native endianness is used, portable code
1143 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1144 /// appropriate instead.
1146 /// [`from_be_bytes`]: f32::from_be_bytes
1147 /// [`from_le_bytes`]: f32::from_le_bytes
1152 /// let value = f32::from_ne_bytes(if cfg!(target_endian = "big") {
1153 /// [0x41, 0x48, 0x00, 0x00]
1155 /// [0x00, 0x00, 0x48, 0x41]
1157 /// assert_eq!(value, 12.5);
1159 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1160 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1163 pub const fn from_ne_bytes(bytes: [u8; 4]) -> Self {
1164 Self::from_bits(u32::from_ne_bytes(bytes))
1167 /// Return the ordering between `self` and `other`.
1169 /// Unlike the standard partial comparison between floating point numbers,
1170 /// this comparison always produces an ordering in accordance to
1171 /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1172 /// floating point standard. The values are ordered in the following sequence:
1174 /// - negative quiet NaN
1175 /// - negative signaling NaN
1176 /// - negative infinity
1177 /// - negative numbers
1178 /// - negative subnormal numbers
1181 /// - positive subnormal numbers
1182 /// - positive numbers
1183 /// - positive infinity
1184 /// - positive signaling NaN
1185 /// - positive quiet NaN.
1187 /// The ordering established by this function does not always agree with the
1188 /// [`PartialOrd`] and [`PartialEq`] implementations of `f32`. For example,
1189 /// they consider negative and positive zero equal, while `total_cmp`
1192 /// The interpretation of the signaling NaN bit follows the definition in
1193 /// the IEEE 754 standard, which may not match the interpretation by some of
1194 /// the older, non-conformant (e.g. MIPS) hardware implementations.
1199 /// struct GoodBoy {
1204 /// let mut bois = vec![
1205 /// GoodBoy { name: "Pucci".to_owned(), weight: 0.1 },
1206 /// GoodBoy { name: "Woofer".to_owned(), weight: 99.0 },
1207 /// GoodBoy { name: "Yapper".to_owned(), weight: 10.0 },
1208 /// GoodBoy { name: "Chonk".to_owned(), weight: f32::INFINITY },
1209 /// GoodBoy { name: "Abs. Unit".to_owned(), weight: f32::NAN },
1210 /// GoodBoy { name: "Floaty".to_owned(), weight: -5.0 },
1213 /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1214 /// # assert!(bois.into_iter().map(|b| b.weight)
1215 /// # .zip([-5.0, 0.1, 10.0, 99.0, f32::INFINITY, f32::NAN].iter())
1216 /// # .all(|(a, b)| a.to_bits() == b.to_bits()))
1218 #[stable(feature = "total_cmp", since = "1.62.0")]
1221 pub fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1222 let mut left = self.to_bits() as i32;
1223 let mut right = other.to_bits() as i32;
1225 // In case of negatives, flip all the bits except the sign
1226 // to achieve a similar layout as two's complement integers
1228 // Why does this work? IEEE 754 floats consist of three fields:
1229 // Sign bit, exponent and mantissa. The set of exponent and mantissa
1230 // fields as a whole have the property that their bitwise order is
1231 // equal to the numeric magnitude where the magnitude is defined.
1232 // The magnitude is not normally defined on NaN values, but
1233 // IEEE 754 totalOrder defines the NaN values also to follow the
1234 // bitwise order. This leads to order explained in the doc comment.
1235 // However, the representation of magnitude is the same for negative
1236 // and positive numbers – only the sign bit is different.
1237 // To easily compare the floats as signed integers, we need to
1238 // flip the exponent and mantissa bits in case of negative numbers.
1239 // We effectively convert the numbers to "two's complement" form.
1241 // To do the flipping, we construct a mask and XOR against it.
1242 // We branchlessly calculate an "all-ones except for the sign bit"
1243 // mask from negative-signed values: right shifting sign-extends
1244 // the integer, so we "fill" the mask with sign bits, and then
1245 // convert to unsigned to push one more zero bit.
1246 // On positive values, the mask is all zeros, so it's a no-op.
1247 left ^= (((left >> 31) as u32) >> 1) as i32;
1248 right ^= (((right >> 31) as u32) >> 1) as i32;
1253 /// Restrict a value to a certain interval unless it is NaN.
1255 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1256 /// less than `min`. Otherwise this returns `self`.
1258 /// Note that this function returns NaN if the initial value was NaN as
1263 /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1268 /// assert!((-3.0f32).clamp(-2.0, 1.0) == -2.0);
1269 /// assert!((0.0f32).clamp(-2.0, 1.0) == 0.0);
1270 /// assert!((2.0f32).clamp(-2.0, 1.0) == 1.0);
1271 /// assert!((f32::NAN).clamp(-2.0, 1.0).is_nan());
1273 #[must_use = "method returns a new number and does not mutate the original value"]
1274 #[stable(feature = "clamp", since = "1.50.0")]
1276 pub fn clamp(self, min: f32, max: f32) -> f32 {
1277 assert!(min <= max);