1 //! Constants for 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 #[deprecated(since = "TBD", note = "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 note = "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 #[deprecated(since = "TBD", note = "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")]
92 #[deprecated(since = "TBD", note = "replaced by the `EPSILON` associated constant on `f32`")]
93 pub const EPSILON: f32 = f32::EPSILON;
95 /// Smallest finite `f32` value.
96 /// Use [`f32::MIN`] instead.
101 /// // deprecated way
102 /// # #[allow(deprecated, deprecated_in_future)]
103 /// let min = std::f32::MIN;
106 /// let min = f32::MIN;
108 #[stable(feature = "rust1", since = "1.0.0")]
109 #[deprecated(since = "TBD", note = "replaced by the `MIN` associated constant on `f32`")]
110 pub const MIN: f32 = f32::MIN;
112 /// Smallest positive normal `f32` value.
113 /// Use [`f32::MIN_POSITIVE`] instead.
118 /// // deprecated way
119 /// # #[allow(deprecated, deprecated_in_future)]
120 /// let min = std::f32::MIN_POSITIVE;
123 /// let min = f32::MIN_POSITIVE;
125 #[stable(feature = "rust1", since = "1.0.0")]
126 #[deprecated(since = "TBD", note = "replaced by the `MIN_POSITIVE` associated constant on `f32`")]
127 pub const MIN_POSITIVE: f32 = f32::MIN_POSITIVE;
129 /// Largest finite `f32` value.
130 /// Use [`f32::MAX`] instead.
135 /// // deprecated way
136 /// # #[allow(deprecated, deprecated_in_future)]
137 /// let max = std::f32::MAX;
140 /// let max = f32::MAX;
142 #[stable(feature = "rust1", since = "1.0.0")]
143 #[deprecated(since = "TBD", note = "replaced by the `MAX` associated constant on `f32`")]
144 pub const MAX: f32 = f32::MAX;
146 /// One greater than the minimum possible normal power of 2 exponent.
147 /// Use [`f32::MIN_EXP`] instead.
152 /// // deprecated way
153 /// # #[allow(deprecated, deprecated_in_future)]
154 /// let min = std::f32::MIN_EXP;
157 /// let min = f32::MIN_EXP;
159 #[stable(feature = "rust1", since = "1.0.0")]
160 #[deprecated(since = "TBD", note = "replaced by the `MIN_EXP` associated constant on `f32`")]
161 pub const MIN_EXP: i32 = f32::MIN_EXP;
163 /// Maximum possible power of 2 exponent.
164 /// Use [`f32::MAX_EXP`] instead.
169 /// // deprecated way
170 /// # #[allow(deprecated, deprecated_in_future)]
171 /// let max = std::f32::MAX_EXP;
174 /// let max = f32::MAX_EXP;
176 #[stable(feature = "rust1", since = "1.0.0")]
177 #[deprecated(since = "TBD", note = "replaced by the `MAX_EXP` associated constant on `f32`")]
178 pub const MAX_EXP: i32 = f32::MAX_EXP;
180 /// Minimum possible normal power of 10 exponent.
181 /// Use [`f32::MIN_10_EXP`] instead.
186 /// // deprecated way
187 /// # #[allow(deprecated, deprecated_in_future)]
188 /// let min = std::f32::MIN_10_EXP;
191 /// let min = f32::MIN_10_EXP;
193 #[stable(feature = "rust1", since = "1.0.0")]
194 #[deprecated(since = "TBD", note = "replaced by the `MIN_10_EXP` associated constant on `f32`")]
195 pub const MIN_10_EXP: i32 = f32::MIN_10_EXP;
197 /// Maximum possible power of 10 exponent.
198 /// Use [`f32::MAX_10_EXP`] instead.
203 /// // deprecated way
204 /// # #[allow(deprecated, deprecated_in_future)]
205 /// let max = std::f32::MAX_10_EXP;
208 /// let max = f32::MAX_10_EXP;
210 #[stable(feature = "rust1", since = "1.0.0")]
211 #[deprecated(since = "TBD", note = "replaced by the `MAX_10_EXP` associated constant on `f32`")]
212 pub const MAX_10_EXP: i32 = f32::MAX_10_EXP;
214 /// Not a Number (NaN).
215 /// Use [`f32::NAN`] instead.
220 /// // deprecated way
221 /// # #[allow(deprecated, deprecated_in_future)]
222 /// let nan = std::f32::NAN;
225 /// let nan = f32::NAN;
227 #[stable(feature = "rust1", since = "1.0.0")]
228 #[deprecated(since = "TBD", note = "replaced by the `NAN` associated constant on `f32`")]
229 pub const NAN: f32 = f32::NAN;
232 /// Use [`f32::INFINITY`] instead.
237 /// // deprecated way
238 /// # #[allow(deprecated, deprecated_in_future)]
239 /// let inf = std::f32::INFINITY;
242 /// let inf = f32::INFINITY;
244 #[stable(feature = "rust1", since = "1.0.0")]
245 #[deprecated(since = "TBD", note = "replaced by the `INFINITY` associated constant on `f32`")]
246 pub const INFINITY: f32 = f32::INFINITY;
248 /// Negative infinity (−∞).
249 /// Use [`f32::NEG_INFINITY`] instead.
254 /// // deprecated way
255 /// # #[allow(deprecated, deprecated_in_future)]
256 /// let ninf = std::f32::NEG_INFINITY;
259 /// let ninf = f32::NEG_INFINITY;
261 #[stable(feature = "rust1", since = "1.0.0")]
262 #[deprecated(since = "TBD", note = "replaced by the `NEG_INFINITY` associated constant on `f32`")]
263 pub const NEG_INFINITY: f32 = f32::NEG_INFINITY;
265 /// Basic mathematical constants.
266 #[stable(feature = "rust1", since = "1.0.0")]
268 // FIXME: replace with mathematical constants from cmath.
270 /// Archimedes' constant (π)
271 #[stable(feature = "rust1", since = "1.0.0")]
272 pub const PI: f32 = 3.14159265358979323846264338327950288_f32;
274 /// The full circle constant (τ)
277 #[stable(feature = "tau_constant", since = "1.47.0")]
278 pub const TAU: f32 = 6.28318530717958647692528676655900577_f32;
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub const FRAC_PI_2: f32 = 1.57079632679489661923132169163975144_f32;
285 #[stable(feature = "rust1", since = "1.0.0")]
286 pub const FRAC_PI_3: f32 = 1.04719755119659774615421446109316763_f32;
289 #[stable(feature = "rust1", since = "1.0.0")]
290 pub const FRAC_PI_4: f32 = 0.785398163397448309615660845819875721_f32;
293 #[stable(feature = "rust1", since = "1.0.0")]
294 pub const FRAC_PI_6: f32 = 0.52359877559829887307710723054658381_f32;
297 #[stable(feature = "rust1", since = "1.0.0")]
298 pub const FRAC_PI_8: f32 = 0.39269908169872415480783042290993786_f32;
301 #[stable(feature = "rust1", since = "1.0.0")]
302 pub const FRAC_1_PI: f32 = 0.318309886183790671537767526745028724_f32;
305 #[stable(feature = "rust1", since = "1.0.0")]
306 pub const FRAC_2_PI: f32 = 0.636619772367581343075535053490057448_f32;
309 #[stable(feature = "rust1", since = "1.0.0")]
310 pub const FRAC_2_SQRT_PI: f32 = 1.12837916709551257389615890312154517_f32;
313 #[stable(feature = "rust1", since = "1.0.0")]
314 pub const SQRT_2: f32 = 1.41421356237309504880168872420969808_f32;
317 #[stable(feature = "rust1", since = "1.0.0")]
318 pub const FRAC_1_SQRT_2: f32 = 0.707106781186547524400844362104849039_f32;
320 /// Euler's number (e)
321 #[stable(feature = "rust1", since = "1.0.0")]
322 pub const E: f32 = 2.71828182845904523536028747135266250_f32;
324 /// log<sub>2</sub>(e)
325 #[stable(feature = "rust1", since = "1.0.0")]
326 pub const LOG2_E: f32 = 1.44269504088896340735992468100189214_f32;
328 /// log<sub>2</sub>(10)
329 #[stable(feature = "extra_log_consts", since = "1.43.0")]
330 pub const LOG2_10: f32 = 3.32192809488736234787031942948939018_f32;
332 /// log<sub>10</sub>(e)
333 #[stable(feature = "rust1", since = "1.0.0")]
334 pub const LOG10_E: f32 = 0.434294481903251827651128918916605082_f32;
336 /// log<sub>10</sub>(2)
337 #[stable(feature = "extra_log_consts", since = "1.43.0")]
338 pub const LOG10_2: f32 = 0.301029995663981195213738894724493027_f32;
341 #[stable(feature = "rust1", since = "1.0.0")]
342 pub const LN_2: f32 = 0.693147180559945309417232121458176568_f32;
345 #[stable(feature = "rust1", since = "1.0.0")]
346 pub const LN_10: f32 = 2.30258509299404568401799145468436421_f32;
351 /// The radix or base of the internal representation of `f32`.
352 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
353 pub const RADIX: u32 = 2;
355 /// Number of significant digits in base 2.
356 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
357 pub const MANTISSA_DIGITS: u32 = 24;
359 /// Approximate number of significant digits in base 10.
360 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
361 pub const DIGITS: u32 = 6;
363 /// [Machine epsilon] value for `f32`.
365 /// This is the difference between `1.0` and the next larger representable number.
367 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
368 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
369 pub const EPSILON: f32 = 1.19209290e-07_f32;
371 /// Smallest finite `f32` value.
372 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
373 pub const MIN: f32 = -3.40282347e+38_f32;
374 /// Smallest positive normal `f32` value.
375 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
376 pub const MIN_POSITIVE: f32 = 1.17549435e-38_f32;
377 /// Largest finite `f32` value.
378 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
379 pub const MAX: f32 = 3.40282347e+38_f32;
381 /// One greater than the minimum possible normal power of 2 exponent.
382 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
383 pub const MIN_EXP: i32 = -125;
384 /// Maximum possible power of 2 exponent.
385 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
386 pub const MAX_EXP: i32 = 128;
388 /// Minimum possible normal power of 10 exponent.
389 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
390 pub const MIN_10_EXP: i32 = -37;
391 /// Maximum possible power of 10 exponent.
392 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
393 pub const MAX_10_EXP: i32 = 38;
395 /// Not a Number (NaN).
397 /// Note that IEEE 754 doesn't define just a single NaN value;
398 /// a plethora of bit patterns are considered to be NaN.
399 /// Furthermore, the standard makes a difference
400 /// between a "signaling" and a "quiet" NaN,
401 /// and allows inspecting its "payload" (the unspecified bits in the bit pattern).
402 /// This constant isn't guaranteed to equal to any specific NaN bitpattern,
403 /// and the stability of its representation over Rust versions
404 /// and target platforms isn't guaranteed.
405 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
406 pub const NAN: f32 = 0.0_f32 / 0.0_f32;
408 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
409 pub const INFINITY: f32 = 1.0_f32 / 0.0_f32;
410 /// Negative infinity (−∞).
411 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
412 pub const NEG_INFINITY: f32 = -1.0_f32 / 0.0_f32;
414 /// Returns `true` if this value is NaN.
417 /// let nan = f32::NAN;
420 /// assert!(nan.is_nan());
421 /// assert!(!f.is_nan());
424 #[stable(feature = "rust1", since = "1.0.0")]
425 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
427 pub const fn is_nan(self) -> bool {
431 // FIXME(#50145): `abs` is publicly unavailable in libcore due to
432 // concerns about portability, so this implementation is for
433 // private use internally.
435 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
436 pub(crate) const fn abs_private(self) -> f32 {
437 // SAFETY: This transmutation is fine. Probably. For the reasons std is using it.
438 unsafe { mem::transmute::<u32, f32>(mem::transmute::<f32, u32>(self) & 0x7fff_ffff) }
441 /// Returns `true` if this value is positive infinity or negative infinity, and
442 /// `false` otherwise.
446 /// let inf = f32::INFINITY;
447 /// let neg_inf = f32::NEG_INFINITY;
448 /// let nan = f32::NAN;
450 /// assert!(!f.is_infinite());
451 /// assert!(!nan.is_infinite());
453 /// assert!(inf.is_infinite());
454 /// assert!(neg_inf.is_infinite());
457 #[stable(feature = "rust1", since = "1.0.0")]
458 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
460 pub const fn is_infinite(self) -> bool {
461 // Getting clever with transmutation can result in incorrect answers on some FPUs
462 // FIXME: alter the Rust <-> Rust calling convention to prevent this problem.
463 // See https://github.com/rust-lang/rust/issues/72327
464 (self == f32::INFINITY) | (self == f32::NEG_INFINITY)
467 /// Returns `true` if this number is neither infinite nor NaN.
471 /// let inf = f32::INFINITY;
472 /// let neg_inf = f32::NEG_INFINITY;
473 /// let nan = f32::NAN;
475 /// assert!(f.is_finite());
477 /// assert!(!nan.is_finite());
478 /// assert!(!inf.is_finite());
479 /// assert!(!neg_inf.is_finite());
482 #[stable(feature = "rust1", since = "1.0.0")]
483 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
485 pub const fn is_finite(self) -> bool {
486 // There's no need to handle NaN separately: if self is NaN,
487 // the comparison is not true, exactly as desired.
488 self.abs_private() < Self::INFINITY
491 /// Returns `true` if the number is [subnormal].
494 /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
495 /// let max = f32::MAX;
496 /// let lower_than_min = 1.0e-40_f32;
497 /// let zero = 0.0_f32;
499 /// assert!(!min.is_subnormal());
500 /// assert!(!max.is_subnormal());
502 /// assert!(!zero.is_subnormal());
503 /// assert!(!f32::NAN.is_subnormal());
504 /// assert!(!f32::INFINITY.is_subnormal());
505 /// // Values between `0` and `min` are Subnormal.
506 /// assert!(lower_than_min.is_subnormal());
508 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
510 #[stable(feature = "is_subnormal", since = "1.53.0")]
511 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
513 pub const fn is_subnormal(self) -> bool {
514 matches!(self.classify(), FpCategory::Subnormal)
517 /// Returns `true` if the number is neither zero, infinite,
518 /// [subnormal], or NaN.
521 /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
522 /// let max = f32::MAX;
523 /// let lower_than_min = 1.0e-40_f32;
524 /// let zero = 0.0_f32;
526 /// assert!(min.is_normal());
527 /// assert!(max.is_normal());
529 /// assert!(!zero.is_normal());
530 /// assert!(!f32::NAN.is_normal());
531 /// assert!(!f32::INFINITY.is_normal());
532 /// // Values between `0` and `min` are Subnormal.
533 /// assert!(!lower_than_min.is_normal());
535 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
537 #[stable(feature = "rust1", since = "1.0.0")]
538 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
540 pub const fn is_normal(self) -> bool {
541 matches!(self.classify(), FpCategory::Normal)
544 /// Returns the floating point category of the number. If only one property
545 /// is going to be tested, it is generally faster to use the specific
546 /// predicate instead.
549 /// use std::num::FpCategory;
551 /// let num = 12.4_f32;
552 /// let inf = f32::INFINITY;
554 /// assert_eq!(num.classify(), FpCategory::Normal);
555 /// assert_eq!(inf.classify(), FpCategory::Infinite);
557 #[stable(feature = "rust1", since = "1.0.0")]
558 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
559 pub const fn classify(self) -> FpCategory {
560 // A previous implementation tried to only use bitmask-based checks,
561 // using f32::to_bits to transmute the float to its bit repr and match on that.
562 // Unfortunately, floating point numbers can be much worse than that.
563 // This also needs to not result in recursive evaluations of f64::to_bits.
565 // On some processors, in some cases, LLVM will "helpfully" lower floating point ops,
566 // in spite of a request for them using f32 and f64, to things like x87 operations.
567 // These have an f64's mantissa, but can have a larger than normal exponent.
568 // FIXME(jubilee): Using x87 operations is never necessary in order to function
569 // on x86 processors for Rust-to-Rust calls, so this issue should not happen.
570 // Code generation should be adjusted to use non-C calling conventions, avoiding this.
572 if self.is_infinite() {
573 // Thus, a value may compare unequal to infinity, despite having a "full" exponent mask.
575 } else if self.is_nan() {
576 // And it may not be NaN, as it can simply be an "overextended" finite value.
579 // However, std can't simply compare to zero to check for zero, either,
580 // as correctness requires avoiding equality tests that may be Subnormal == -0.0
581 // because it may be wrong under "denormals are zero" and "flush to zero" modes.
582 // Most of std's targets don't use those, but they are used for thumbv7neon.
583 // So, this does use bitpattern matching for the rest.
585 // SAFETY: f32 to u32 is fine. Usually.
586 // If classify has gotten this far, the value is definitely in one of these categories.
587 unsafe { f32::partial_classify(self) }
591 // This doesn't actually return a right answer for NaN on purpose,
592 // seeing as how it cannot correctly discern between a floating point NaN,
593 // and some normal floating point numbers truncated from an x87 FPU.
594 // FIXME(jubilee): This probably could at least answer things correctly for Infinity,
595 // like the f64 version does, but I need to run more checks on how things go on x86.
596 // I fear losing mantissa data that would have answered that differently.
599 // This requires making sure you call this function for values it answers correctly on,
600 // otherwise it returns a wrong answer. This is not important for memory safety per se,
601 // but getting floats correct is important for not accidentally leaking const eval
602 // runtime-deviating logic which may or may not be acceptable.
603 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
604 const unsafe fn partial_classify(self) -> FpCategory {
605 const EXP_MASK: u32 = 0x7f800000;
606 const MAN_MASK: u32 = 0x007fffff;
608 // SAFETY: The caller is not asking questions for which this will tell lies.
609 let b = unsafe { mem::transmute::<f32, u32>(self) };
610 match (b & MAN_MASK, b & EXP_MASK) {
611 (0, 0) => FpCategory::Zero,
612 (_, 0) => FpCategory::Subnormal,
613 _ => FpCategory::Normal,
617 // This operates on bits, and only bits, so it can ignore concerns about weird FPUs.
618 // FIXME(jubilee): In a just world, this would be the entire impl for classify,
619 // plus a transmute. We do not live in a just world, but we can make it more so.
620 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
621 const fn classify_bits(b: u32) -> FpCategory {
622 const EXP_MASK: u32 = 0x7f800000;
623 const MAN_MASK: u32 = 0x007fffff;
625 match (b & MAN_MASK, b & EXP_MASK) {
626 (0, EXP_MASK) => FpCategory::Infinite,
627 (_, EXP_MASK) => FpCategory::Nan,
628 (0, 0) => FpCategory::Zero,
629 (_, 0) => FpCategory::Subnormal,
630 _ => FpCategory::Normal,
634 /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with
635 /// positive sign bit and positive infinity. Note that IEEE 754 doesn't assign any
636 /// meaning to the sign bit in case of a NaN, and as Rust doesn't guarantee that
637 /// the bit pattern of NaNs are conserved over arithmetic operations, the result of
638 /// `is_sign_positive` on a NaN might produce an unexpected result in some cases.
639 /// See [explanation of NaN as a special value](f32) for more info.
643 /// let g = -7.0_f32;
645 /// assert!(f.is_sign_positive());
646 /// assert!(!g.is_sign_positive());
649 #[stable(feature = "rust1", since = "1.0.0")]
650 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
652 pub const fn is_sign_positive(self) -> bool {
653 !self.is_sign_negative()
656 /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with
657 /// negative sign bit and negative infinity. Note that IEEE 754 doesn't assign any
658 /// meaning to the sign bit in case of a NaN, and as Rust doesn't guarantee that
659 /// the bit pattern of NaNs are conserved over arithmetic operations, the result of
660 /// `is_sign_negative` on a NaN might produce an unexpected result in some cases.
661 /// See [explanation of NaN as a special value](f32) for more info.
667 /// assert!(!f.is_sign_negative());
668 /// assert!(g.is_sign_negative());
671 #[stable(feature = "rust1", since = "1.0.0")]
672 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
674 pub const fn is_sign_negative(self) -> bool {
675 // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
676 // applies to zeros and NaNs as well.
677 // SAFETY: This is just transmuting to get the sign bit, it's fine.
678 unsafe { mem::transmute::<f32, u32>(self) & 0x8000_0000 != 0 }
681 /// Returns the least number greater than `self`.
683 /// Let `TINY` be the smallest representable positive `f32`. Then,
684 /// - if `self.is_nan()`, this returns `self`;
685 /// - if `self` is [`NEG_INFINITY`], this returns [`MIN`];
686 /// - if `self` is `-TINY`, this returns -0.0;
687 /// - if `self` is -0.0 or +0.0, this returns `TINY`;
688 /// - if `self` is [`MAX`] or [`INFINITY`], this returns [`INFINITY`];
689 /// - otherwise the unique least value greater than `self` is returned.
691 /// The identity `x.next_up() == -(-x).next_down()` holds for all non-NaN `x`. When `x`
692 /// is finite `x == x.next_up().next_down()` also holds.
695 /// #![feature(float_next_up_down)]
696 /// // f32::EPSILON is the difference between 1.0 and the next number up.
697 /// assert_eq!(1.0f32.next_up(), 1.0 + f32::EPSILON);
698 /// // But not for most numbers.
699 /// assert!(0.1f32.next_up() < 0.1 + f32::EPSILON);
700 /// assert_eq!(16777216f32.next_up(), 16777218.0);
703 /// [`NEG_INFINITY`]: Self::NEG_INFINITY
704 /// [`INFINITY`]: Self::INFINITY
705 /// [`MIN`]: Self::MIN
706 /// [`MAX`]: Self::MAX
707 #[unstable(feature = "float_next_up_down", issue = "91399")]
708 #[rustc_const_unstable(feature = "float_next_up_down", issue = "91399")]
709 pub const fn next_up(self) -> Self {
710 // We must use strictly integer arithmetic to prevent denormals from
711 // flushing to zero after an arithmetic operation on some platforms.
712 const TINY_BITS: u32 = 0x1; // Smallest positive f32.
713 const CLEAR_SIGN_MASK: u32 = 0x7fff_ffff;
715 let bits = self.to_bits();
716 if self.is_nan() || bits == Self::INFINITY.to_bits() {
720 let abs = bits & CLEAR_SIGN_MASK;
721 let next_bits = if abs == 0 {
723 } else if bits == abs {
728 Self::from_bits(next_bits)
731 /// Returns the greatest number less than `self`.
733 /// Let `TINY` be the smallest representable positive `f32`. Then,
734 /// - if `self.is_nan()`, this returns `self`;
735 /// - if `self` is [`INFINITY`], this returns [`MAX`];
736 /// - if `self` is `TINY`, this returns 0.0;
737 /// - if `self` is -0.0 or +0.0, this returns `-TINY`;
738 /// - if `self` is [`MIN`] or [`NEG_INFINITY`], this returns [`NEG_INFINITY`];
739 /// - otherwise the unique greatest value less than `self` is returned.
741 /// The identity `x.next_down() == -(-x).next_up()` holds for all non-NaN `x`. When `x`
742 /// is finite `x == x.next_down().next_up()` also holds.
745 /// #![feature(float_next_up_down)]
747 /// // Clamp value into range [0, 1).
748 /// let clamped = x.clamp(0.0, 1.0f32.next_down());
749 /// assert!(clamped < 1.0);
750 /// assert_eq!(clamped.next_up(), 1.0);
753 /// [`NEG_INFINITY`]: Self::NEG_INFINITY
754 /// [`INFINITY`]: Self::INFINITY
755 /// [`MIN`]: Self::MIN
756 /// [`MAX`]: Self::MAX
757 #[unstable(feature = "float_next_up_down", issue = "91399")]
758 #[rustc_const_unstable(feature = "float_next_up_down", issue = "91399")]
759 pub const fn next_down(self) -> Self {
760 // We must use strictly integer arithmetic to prevent denormals from
761 // flushing to zero after an arithmetic operation on some platforms.
762 const NEG_TINY_BITS: u32 = 0x8000_0001; // Smallest (in magnitude) negative f32.
763 const CLEAR_SIGN_MASK: u32 = 0x7fff_ffff;
765 let bits = self.to_bits();
766 if self.is_nan() || bits == Self::NEG_INFINITY.to_bits() {
770 let abs = bits & CLEAR_SIGN_MASK;
771 let next_bits = if abs == 0 {
773 } else if bits == abs {
778 Self::from_bits(next_bits)
781 /// Takes the reciprocal (inverse) of a number, `1/x`.
785 /// let abs_difference = (x.recip() - (1.0 / x)).abs();
787 /// assert!(abs_difference <= f32::EPSILON);
789 #[must_use = "this returns the result of the operation, without modifying the original"]
790 #[stable(feature = "rust1", since = "1.0.0")]
792 pub fn recip(self) -> f32 {
796 /// Converts radians to degrees.
799 /// let angle = std::f32::consts::PI;
801 /// let abs_difference = (angle.to_degrees() - 180.0).abs();
803 /// assert!(abs_difference <= f32::EPSILON);
805 #[must_use = "this returns the result of the operation, \
806 without modifying the original"]
807 #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
809 pub fn to_degrees(self) -> f32 {
810 // Use a constant for better precision.
811 const PIS_IN_180: f32 = 57.2957795130823208767981548141051703_f32;
815 /// Converts degrees to radians.
818 /// let angle = 180.0f32;
820 /// let abs_difference = (angle.to_radians() - std::f32::consts::PI).abs();
822 /// assert!(abs_difference <= f32::EPSILON);
824 #[must_use = "this returns the result of the operation, \
825 without modifying the original"]
826 #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
828 pub fn to_radians(self) -> f32 {
829 let value: f32 = consts::PI;
830 self * (value / 180.0f32)
833 /// Returns the maximum of the two numbers, ignoring NaN.
835 /// If one of the arguments is NaN, then the other argument is returned.
836 /// This follows the IEEE 754-2008 semantics for maxNum, except for handling of signaling NaNs;
837 /// this function handles all NaNs the same way and avoids maxNum's problems with associativity.
838 /// This also matches the behavior of libm’s fmax.
844 /// assert_eq!(x.max(y), y);
846 #[must_use = "this returns the result of the comparison, without modifying either input"]
847 #[stable(feature = "rust1", since = "1.0.0")]
849 pub fn max(self, other: f32) -> f32 {
850 intrinsics::maxnumf32(self, other)
853 /// Returns the minimum of the two numbers, ignoring NaN.
855 /// If one of the arguments is NaN, then the other argument is returned.
856 /// This follows the IEEE 754-2008 semantics for minNum, except for handling of signaling NaNs;
857 /// this function handles all NaNs the same way and avoids minNum's problems with associativity.
858 /// This also matches the behavior of libm’s fmin.
864 /// assert_eq!(x.min(y), x);
866 #[must_use = "this returns the result of the comparison, without modifying either input"]
867 #[stable(feature = "rust1", since = "1.0.0")]
869 pub fn min(self, other: f32) -> f32 {
870 intrinsics::minnumf32(self, other)
873 /// Returns the maximum of the two numbers, propagating NaN.
875 /// This returns NaN when *either* argument is NaN, as opposed to
876 /// [`f32::max`] which only returns NaN when *both* arguments are NaN.
879 /// #![feature(float_minimum_maximum)]
883 /// assert_eq!(x.maximum(y), y);
884 /// assert!(x.maximum(f32::NAN).is_nan());
887 /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the greater
888 /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
889 /// Note that this follows the semantics specified in IEEE 754-2019.
891 /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
892 /// operand is conserved; see [explanation of NaN as a special value](f32) for more info.
893 #[must_use = "this returns the result of the comparison, without modifying either input"]
894 #[unstable(feature = "float_minimum_maximum", issue = "91079")]
896 pub fn maximum(self, other: f32) -> f32 {
899 } else if other > self {
901 } else if self == other {
902 if self.is_sign_positive() && other.is_sign_negative() { self } else { other }
908 /// Returns the minimum of the two numbers, propagating NaN.
910 /// This returns NaN when *either* argument is NaN, as opposed to
911 /// [`f32::min`] which only returns NaN when *both* arguments are NaN.
914 /// #![feature(float_minimum_maximum)]
918 /// assert_eq!(x.minimum(y), x);
919 /// assert!(x.minimum(f32::NAN).is_nan());
922 /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the lesser
923 /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
924 /// Note that this follows the semantics specified in IEEE 754-2019.
926 /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
927 /// operand is conserved; see [explanation of NaN as a special value](f32) for more info.
928 #[must_use = "this returns the result of the comparison, without modifying either input"]
929 #[unstable(feature = "float_minimum_maximum", issue = "91079")]
931 pub fn minimum(self, other: f32) -> f32 {
934 } else if other < self {
936 } else if self == other {
937 if self.is_sign_negative() && other.is_sign_positive() { self } else { other }
943 /// Rounds toward zero and converts to any primitive integer type,
944 /// assuming that the value is finite and fits in that type.
947 /// let value = 4.6_f32;
948 /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
949 /// assert_eq!(rounded, 4);
951 /// let value = -128.9_f32;
952 /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
953 /// assert_eq!(rounded, i8::MIN);
961 /// * Not be infinite
962 /// * Be representable in the return type `Int`, after truncating off its fractional part
963 #[must_use = "this returns the result of the operation, \
964 without modifying the original"]
965 #[stable(feature = "float_approx_unchecked_to", since = "1.44.0")]
967 pub unsafe fn to_int_unchecked<Int>(self) -> Int
969 Self: FloatToInt<Int>,
971 // SAFETY: the caller must uphold the safety contract for
972 // `FloatToInt::to_int_unchecked`.
973 unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
976 /// Raw transmutation to `u32`.
978 /// This is currently identical to `transmute::<f32, u32>(self)` on all platforms.
980 /// See [`from_bits`](Self::from_bits) for some discussion of the
981 /// portability of this operation (there are almost no issues).
983 /// Note that this function is distinct from `as` casting, which attempts to
984 /// preserve the *numeric* value, and not the bitwise value.
989 /// assert_ne!((1f32).to_bits(), 1f32 as u32); // to_bits() is not casting!
990 /// assert_eq!((12.5f32).to_bits(), 0x41480000);
993 #[must_use = "this returns the result of the operation, \
994 without modifying the original"]
995 #[stable(feature = "float_bits_conv", since = "1.20.0")]
996 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
998 pub const fn to_bits(self) -> u32 {
999 // SAFETY: `u32` is a plain old datatype so we can always transmute to it.
1002 // It turns out that at runtime, it is possible for a floating point number
1003 // to be subject to a floating point mode that alters nonzero subnormal numbers
1004 // to zero on reads and writes, aka "denormals are zero" and "flush to zero".
1005 // This is not a problem per se, but at least one tier2 platform for Rust
1006 // actually exhibits this behavior by default.
1008 // In addition, on x86 targets with SSE or SSE2 disabled and the x87 FPU enabled,
1009 // i.e. not soft-float, the way Rust does parameter passing can actually alter
1010 // a number that is "not infinity" to have the same exponent as infinity,
1011 // in a slightly unpredictable manner.
1013 // And, of course evaluating to a NaN value is fairly nondeterministic.
1014 // More precisely: when NaN should be returned is knowable, but which NaN?
1015 // So far that's defined by a combination of LLVM and the CPU, not Rust.
1016 // This function, however, allows observing the bitstring of a NaN,
1017 // thus introspection on CTFE.
1019 // In order to preserve, at least for the moment, const-to-runtime equivalence,
1020 // we reject any of these possible situations from happening.
1021 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1022 const fn ct_f32_to_u32(ct: f32) -> u32 {
1023 match ct.classify() {
1024 FpCategory::Nan => {
1025 panic!("const-eval error: cannot use f32::to_bits on a NaN")
1027 FpCategory::Subnormal => {
1028 panic!("const-eval error: cannot use f32::to_bits on a subnormal number")
1030 FpCategory::Infinite | FpCategory::Normal | FpCategory::Zero => {
1031 // SAFETY: We have a normal floating point number. Now we transmute, i.e. do a bitcopy.
1032 unsafe { mem::transmute::<f32, u32>(ct) }
1037 #[inline(always)] // See https://github.com/rust-lang/compiler-builtins/issues/491
1038 fn rt_f32_to_u32(x: f32) -> u32 {
1039 // SAFETY: `u32` is a plain old datatype so we can always... uh...
1040 // ...look, just pretend you forgot what you just read.
1041 // Stability concerns.
1042 unsafe { mem::transmute(x) }
1044 // SAFETY: We use internal implementations that either always work or fail at compile time.
1045 unsafe { intrinsics::const_eval_select((self,), ct_f32_to_u32, rt_f32_to_u32) }
1048 /// Raw transmutation from `u32`.
1050 /// This is currently identical to `transmute::<u32, f32>(v)` on all platforms.
1051 /// It turns out this is incredibly portable, for two reasons:
1053 /// * Floats and Ints have the same endianness on all supported platforms.
1054 /// * IEEE 754 very precisely specifies the bit layout of floats.
1056 /// However there is one caveat: prior to the 2008 version of IEEE 754, how
1057 /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
1058 /// (notably x86 and ARM) picked the interpretation that was ultimately
1059 /// standardized in 2008, but some didn't (notably MIPS). As a result, all
1060 /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
1062 /// Rather than trying to preserve signaling-ness cross-platform, this
1063 /// implementation favors preserving the exact bits. This means that
1064 /// any payloads encoded in NaNs will be preserved even if the result of
1065 /// this method is sent over the network from an x86 machine to a MIPS one.
1067 /// If the results of this method are only manipulated by the same
1068 /// architecture that produced them, then there is no portability concern.
1070 /// If the input isn't NaN, then there is no portability concern.
1072 /// If you don't care about signalingness (very likely), then there is no
1073 /// portability concern.
1075 /// Note that this function is distinct from `as` casting, which attempts to
1076 /// preserve the *numeric* value, and not the bitwise value.
1081 /// let v = f32::from_bits(0x41480000);
1082 /// assert_eq!(v, 12.5);
1084 #[stable(feature = "float_bits_conv", since = "1.20.0")]
1085 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1088 pub const fn from_bits(v: u32) -> Self {
1089 // It turns out the safety issues with sNaN were overblown! Hooray!
1090 // SAFETY: `u32` is a plain old datatype so we can always transmute from it
1093 // It turns out that at runtime, it is possible for a floating point number
1094 // to be subject to floating point modes that alter nonzero subnormal numbers
1095 // to zero on reads and writes, aka "denormals are zero" and "flush to zero".
1096 // This is not a problem usually, but at least one tier2 platform for Rust
1097 // actually exhibits this behavior by default: thumbv7neon
1098 // aka "the Neon FPU in AArch32 state"
1100 // In addition, on x86 targets with SSE or SSE2 disabled and the x87 FPU enabled,
1101 // i.e. not soft-float, the way Rust does parameter passing can actually alter
1102 // a number that is "not infinity" to have the same exponent as infinity,
1103 // in a slightly unpredictable manner.
1105 // And, of course evaluating to a NaN value is fairly nondeterministic.
1106 // More precisely: when NaN should be returned is knowable, but which NaN?
1107 // So far that's defined by a combination of LLVM and the CPU, not Rust.
1108 // This function, however, allows observing the bitstring of a NaN,
1109 // thus introspection on CTFE.
1111 // In order to preserve, at least for the moment, const-to-runtime equivalence,
1112 // reject any of these possible situations from happening.
1113 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1114 const fn ct_u32_to_f32(ct: u32) -> f32 {
1115 match f32::classify_bits(ct) {
1116 FpCategory::Subnormal => {
1117 panic!("const-eval error: cannot use f32::from_bits on a subnormal number")
1119 FpCategory::Nan => {
1120 panic!("const-eval error: cannot use f32::from_bits on NaN")
1122 FpCategory::Infinite | FpCategory::Normal | FpCategory::Zero => {
1123 // SAFETY: It's not a frumious number
1124 unsafe { mem::transmute::<u32, f32>(ct) }
1129 #[inline(always)] // See https://github.com/rust-lang/compiler-builtins/issues/491
1130 fn rt_u32_to_f32(x: u32) -> f32 {
1131 // SAFETY: `u32` is a plain old datatype so we can always... uh...
1132 // ...look, just pretend you forgot what you just read.
1133 // Stability concerns.
1134 unsafe { mem::transmute(x) }
1136 // SAFETY: We use internal implementations that either always work or fail at compile time.
1137 unsafe { intrinsics::const_eval_select((v,), ct_u32_to_f32, rt_u32_to_f32) }
1140 /// Return the memory representation of this floating point number as a byte array in
1141 /// big-endian (network) byte order.
1143 /// See [`from_bits`](Self::from_bits) for some discussion of the
1144 /// portability of this operation (there are almost no issues).
1149 /// let bytes = 12.5f32.to_be_bytes();
1150 /// assert_eq!(bytes, [0x41, 0x48, 0x00, 0x00]);
1152 #[must_use = "this returns the result of the operation, \
1153 without modifying the original"]
1154 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1155 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1157 pub const fn to_be_bytes(self) -> [u8; 4] {
1158 self.to_bits().to_be_bytes()
1161 /// Return the memory representation of this floating point number as a byte array in
1162 /// little-endian byte order.
1164 /// See [`from_bits`](Self::from_bits) for some discussion of the
1165 /// portability of this operation (there are almost no issues).
1170 /// let bytes = 12.5f32.to_le_bytes();
1171 /// assert_eq!(bytes, [0x00, 0x00, 0x48, 0x41]);
1173 #[must_use = "this returns the result of the operation, \
1174 without modifying the original"]
1175 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1176 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1178 pub const fn to_le_bytes(self) -> [u8; 4] {
1179 self.to_bits().to_le_bytes()
1182 /// Return the memory representation of this floating point number as a byte array in
1183 /// native byte order.
1185 /// As the target platform's native endianness is used, portable code
1186 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1188 /// [`to_be_bytes`]: f32::to_be_bytes
1189 /// [`to_le_bytes`]: f32::to_le_bytes
1191 /// See [`from_bits`](Self::from_bits) for some discussion of the
1192 /// portability of this operation (there are almost no issues).
1197 /// let bytes = 12.5f32.to_ne_bytes();
1200 /// if cfg!(target_endian = "big") {
1201 /// [0x41, 0x48, 0x00, 0x00]
1203 /// [0x00, 0x00, 0x48, 0x41]
1207 #[must_use = "this returns the result of the operation, \
1208 without modifying the original"]
1209 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1210 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1212 pub const fn to_ne_bytes(self) -> [u8; 4] {
1213 self.to_bits().to_ne_bytes()
1216 /// Create a floating point value from its representation as a byte array in big endian.
1218 /// See [`from_bits`](Self::from_bits) for some discussion of the
1219 /// portability of this operation (there are almost no issues).
1224 /// let value = f32::from_be_bytes([0x41, 0x48, 0x00, 0x00]);
1225 /// assert_eq!(value, 12.5);
1227 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1228 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1231 pub const fn from_be_bytes(bytes: [u8; 4]) -> Self {
1232 Self::from_bits(u32::from_be_bytes(bytes))
1235 /// Create a floating point value from its representation as a byte array in little endian.
1237 /// See [`from_bits`](Self::from_bits) for some discussion of the
1238 /// portability of this operation (there are almost no issues).
1243 /// let value = f32::from_le_bytes([0x00, 0x00, 0x48, 0x41]);
1244 /// assert_eq!(value, 12.5);
1246 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1247 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1250 pub const fn from_le_bytes(bytes: [u8; 4]) -> Self {
1251 Self::from_bits(u32::from_le_bytes(bytes))
1254 /// Create a floating point value from its representation as a byte array in native endian.
1256 /// As the target platform's native endianness is used, portable code
1257 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1258 /// appropriate instead.
1260 /// [`from_be_bytes`]: f32::from_be_bytes
1261 /// [`from_le_bytes`]: f32::from_le_bytes
1263 /// See [`from_bits`](Self::from_bits) for some discussion of the
1264 /// portability of this operation (there are almost no issues).
1269 /// let value = f32::from_ne_bytes(if cfg!(target_endian = "big") {
1270 /// [0x41, 0x48, 0x00, 0x00]
1272 /// [0x00, 0x00, 0x48, 0x41]
1274 /// assert_eq!(value, 12.5);
1276 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1277 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1280 pub const fn from_ne_bytes(bytes: [u8; 4]) -> Self {
1281 Self::from_bits(u32::from_ne_bytes(bytes))
1284 /// Return the ordering between `self` and `other`.
1286 /// Unlike the standard partial comparison between floating point numbers,
1287 /// this comparison always produces an ordering in accordance to
1288 /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1289 /// floating point standard. The values are ordered in the following sequence:
1291 /// - negative quiet NaN
1292 /// - negative signaling NaN
1293 /// - negative infinity
1294 /// - negative numbers
1295 /// - negative subnormal numbers
1298 /// - positive subnormal numbers
1299 /// - positive numbers
1300 /// - positive infinity
1301 /// - positive signaling NaN
1302 /// - positive quiet NaN.
1304 /// The ordering established by this function does not always agree with the
1305 /// [`PartialOrd`] and [`PartialEq`] implementations of `f32`. For example,
1306 /// they consider negative and positive zero equal, while `total_cmp`
1309 /// The interpretation of the signaling NaN bit follows the definition in
1310 /// the IEEE 754 standard, which may not match the interpretation by some of
1311 /// the older, non-conformant (e.g. MIPS) hardware implementations.
1316 /// struct GoodBoy {
1321 /// let mut bois = vec![
1322 /// GoodBoy { name: "Pucci".to_owned(), weight: 0.1 },
1323 /// GoodBoy { name: "Woofer".to_owned(), weight: 99.0 },
1324 /// GoodBoy { name: "Yapper".to_owned(), weight: 10.0 },
1325 /// GoodBoy { name: "Chonk".to_owned(), weight: f32::INFINITY },
1326 /// GoodBoy { name: "Abs. Unit".to_owned(), weight: f32::NAN },
1327 /// GoodBoy { name: "Floaty".to_owned(), weight: -5.0 },
1330 /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1331 /// # assert!(bois.into_iter().map(|b| b.weight)
1332 /// # .zip([-5.0, 0.1, 10.0, 99.0, f32::INFINITY, f32::NAN].iter())
1333 /// # .all(|(a, b)| a.to_bits() == b.to_bits()))
1335 #[stable(feature = "total_cmp", since = "1.62.0")]
1338 pub fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1339 let mut left = self.to_bits() as i32;
1340 let mut right = other.to_bits() as i32;
1342 // In case of negatives, flip all the bits except the sign
1343 // to achieve a similar layout as two's complement integers
1345 // Why does this work? IEEE 754 floats consist of three fields:
1346 // Sign bit, exponent and mantissa. The set of exponent and mantissa
1347 // fields as a whole have the property that their bitwise order is
1348 // equal to the numeric magnitude where the magnitude is defined.
1349 // The magnitude is not normally defined on NaN values, but
1350 // IEEE 754 totalOrder defines the NaN values also to follow the
1351 // bitwise order. This leads to order explained in the doc comment.
1352 // However, the representation of magnitude is the same for negative
1353 // and positive numbers – only the sign bit is different.
1354 // To easily compare the floats as signed integers, we need to
1355 // flip the exponent and mantissa bits in case of negative numbers.
1356 // We effectively convert the numbers to "two's complement" form.
1358 // To do the flipping, we construct a mask and XOR against it.
1359 // We branchlessly calculate an "all-ones except for the sign bit"
1360 // mask from negative-signed values: right shifting sign-extends
1361 // the integer, so we "fill" the mask with sign bits, and then
1362 // convert to unsigned to push one more zero bit.
1363 // On positive values, the mask is all zeros, so it's a no-op.
1364 left ^= (((left >> 31) as u32) >> 1) as i32;
1365 right ^= (((right >> 31) as u32) >> 1) as i32;
1370 /// Restrict a value to a certain interval unless it is NaN.
1372 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1373 /// less than `min`. Otherwise this returns `self`.
1375 /// Note that this function returns NaN if the initial value was NaN as
1380 /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1385 /// assert!((-3.0f32).clamp(-2.0, 1.0) == -2.0);
1386 /// assert!((0.0f32).clamp(-2.0, 1.0) == 0.0);
1387 /// assert!((2.0f32).clamp(-2.0, 1.0) == 1.0);
1388 /// assert!((f32::NAN).clamp(-2.0, 1.0).is_nan());
1390 #[must_use = "method returns a new number and does not mutate the original value"]
1391 #[stable(feature = "clamp", since = "1.50.0")]
1393 pub fn clamp(mut self, min: f32, max: f32) -> f32 {
1394 assert!(min <= max);