1 //! Constants for the `f64` double-precision floating point type.
3 //! *[See also the `f64` primitive type][f64].*
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 `f64` 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 `f64`.
21 /// Use [`f64::RADIX`] instead.
27 /// # #[allow(deprecated, deprecated_in_future)]
28 /// let r = std::f64::RADIX;
31 /// let r = f64::RADIX;
33 #[stable(feature = "rust1", since = "1.0.0")]
34 #[deprecated(since = "TBD", note = "replaced by the `RADIX` associated constant on `f64`")]
35 pub const RADIX: u32 = f64::RADIX;
37 /// Number of significant digits in base 2.
38 /// Use [`f64::MANTISSA_DIGITS`] instead.
44 /// # #[allow(deprecated, deprecated_in_future)]
45 /// let d = std::f64::MANTISSA_DIGITS;
48 /// let d = f64::MANTISSA_DIGITS;
50 #[stable(feature = "rust1", since = "1.0.0")]
53 note = "replaced by the `MANTISSA_DIGITS` associated constant on `f64`"
55 pub const MANTISSA_DIGITS: u32 = f64::MANTISSA_DIGITS;
57 /// Approximate number of significant digits in base 10.
58 /// Use [`f64::DIGITS`] instead.
64 /// # #[allow(deprecated, deprecated_in_future)]
65 /// let d = std::f64::DIGITS;
68 /// let d = f64::DIGITS;
70 #[stable(feature = "rust1", since = "1.0.0")]
71 #[deprecated(since = "TBD", note = "replaced by the `DIGITS` associated constant on `f64`")]
72 pub const DIGITS: u32 = f64::DIGITS;
74 /// [Machine epsilon] value for `f64`.
75 /// Use [`f64::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::f64::EPSILON;
89 /// let e = f64::EPSILON;
91 #[stable(feature = "rust1", since = "1.0.0")]
92 #[deprecated(since = "TBD", note = "replaced by the `EPSILON` associated constant on `f64`")]
93 pub const EPSILON: f64 = f64::EPSILON;
95 /// Smallest finite `f64` value.
96 /// Use [`f64::MIN`] instead.
101 /// // deprecated way
102 /// # #[allow(deprecated, deprecated_in_future)]
103 /// let min = std::f64::MIN;
106 /// let min = f64::MIN;
108 #[stable(feature = "rust1", since = "1.0.0")]
109 #[deprecated(since = "TBD", note = "replaced by the `MIN` associated constant on `f64`")]
110 pub const MIN: f64 = f64::MIN;
112 /// Smallest positive normal `f64` value.
113 /// Use [`f64::MIN_POSITIVE`] instead.
118 /// // deprecated way
119 /// # #[allow(deprecated, deprecated_in_future)]
120 /// let min = std::f64::MIN_POSITIVE;
123 /// let min = f64::MIN_POSITIVE;
125 #[stable(feature = "rust1", since = "1.0.0")]
126 #[deprecated(since = "TBD", note = "replaced by the `MIN_POSITIVE` associated constant on `f64`")]
127 pub const MIN_POSITIVE: f64 = f64::MIN_POSITIVE;
129 /// Largest finite `f64` value.
130 /// Use [`f64::MAX`] instead.
135 /// // deprecated way
136 /// # #[allow(deprecated, deprecated_in_future)]
137 /// let max = std::f64::MAX;
140 /// let max = f64::MAX;
142 #[stable(feature = "rust1", since = "1.0.0")]
143 #[deprecated(since = "TBD", note = "replaced by the `MAX` associated constant on `f64`")]
144 pub const MAX: f64 = f64::MAX;
146 /// One greater than the minimum possible normal power of 2 exponent.
147 /// Use [`f64::MIN_EXP`] instead.
152 /// // deprecated way
153 /// # #[allow(deprecated, deprecated_in_future)]
154 /// let min = std::f64::MIN_EXP;
157 /// let min = f64::MIN_EXP;
159 #[stable(feature = "rust1", since = "1.0.0")]
160 #[deprecated(since = "TBD", note = "replaced by the `MIN_EXP` associated constant on `f64`")]
161 pub const MIN_EXP: i32 = f64::MIN_EXP;
163 /// Maximum possible power of 2 exponent.
164 /// Use [`f64::MAX_EXP`] instead.
169 /// // deprecated way
170 /// # #[allow(deprecated, deprecated_in_future)]
171 /// let max = std::f64::MAX_EXP;
174 /// let max = f64::MAX_EXP;
176 #[stable(feature = "rust1", since = "1.0.0")]
177 #[deprecated(since = "TBD", note = "replaced by the `MAX_EXP` associated constant on `f64`")]
178 pub const MAX_EXP: i32 = f64::MAX_EXP;
180 /// Minimum possible normal power of 10 exponent.
181 /// Use [`f64::MIN_10_EXP`] instead.
186 /// // deprecated way
187 /// # #[allow(deprecated, deprecated_in_future)]
188 /// let min = std::f64::MIN_10_EXP;
191 /// let min = f64::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 `f64`")]
195 pub const MIN_10_EXP: i32 = f64::MIN_10_EXP;
197 /// Maximum possible power of 10 exponent.
198 /// Use [`f64::MAX_10_EXP`] instead.
203 /// // deprecated way
204 /// # #[allow(deprecated, deprecated_in_future)]
205 /// let max = std::f64::MAX_10_EXP;
208 /// let max = f64::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 `f64`")]
212 pub const MAX_10_EXP: i32 = f64::MAX_10_EXP;
214 /// Not a Number (NaN).
215 /// Use [`f64::NAN`] instead.
220 /// // deprecated way
221 /// # #[allow(deprecated, deprecated_in_future)]
222 /// let nan = std::f64::NAN;
225 /// let nan = f64::NAN;
227 #[stable(feature = "rust1", since = "1.0.0")]
228 #[deprecated(since = "TBD", note = "replaced by the `NAN` associated constant on `f64`")]
229 pub const NAN: f64 = f64::NAN;
232 /// Use [`f64::INFINITY`] instead.
237 /// // deprecated way
238 /// # #[allow(deprecated, deprecated_in_future)]
239 /// let inf = std::f64::INFINITY;
242 /// let inf = f64::INFINITY;
244 #[stable(feature = "rust1", since = "1.0.0")]
245 #[deprecated(since = "TBD", note = "replaced by the `INFINITY` associated constant on `f64`")]
246 pub const INFINITY: f64 = f64::INFINITY;
248 /// Negative infinity (−∞).
249 /// Use [`f64::NEG_INFINITY`] instead.
254 /// // deprecated way
255 /// # #[allow(deprecated, deprecated_in_future)]
256 /// let ninf = std::f64::NEG_INFINITY;
259 /// let ninf = f64::NEG_INFINITY;
261 #[stable(feature = "rust1", since = "1.0.0")]
262 #[deprecated(since = "TBD", note = "replaced by the `NEG_INFINITY` associated constant on `f64`")]
263 pub const NEG_INFINITY: f64 = f64::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: f64 = 3.14159265358979323846264338327950288_f64;
274 /// The full circle constant (τ)
277 #[stable(feature = "tau_constant", since = "1.47.0")]
278 pub const TAU: f64 = 6.28318530717958647692528676655900577_f64;
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub const FRAC_PI_2: f64 = 1.57079632679489661923132169163975144_f64;
285 #[stable(feature = "rust1", since = "1.0.0")]
286 pub const FRAC_PI_3: f64 = 1.04719755119659774615421446109316763_f64;
289 #[stable(feature = "rust1", since = "1.0.0")]
290 pub const FRAC_PI_4: f64 = 0.785398163397448309615660845819875721_f64;
293 #[stable(feature = "rust1", since = "1.0.0")]
294 pub const FRAC_PI_6: f64 = 0.52359877559829887307710723054658381_f64;
297 #[stable(feature = "rust1", since = "1.0.0")]
298 pub const FRAC_PI_8: f64 = 0.39269908169872415480783042290993786_f64;
301 #[stable(feature = "rust1", since = "1.0.0")]
302 pub const FRAC_1_PI: f64 = 0.318309886183790671537767526745028724_f64;
305 #[stable(feature = "rust1", since = "1.0.0")]
306 pub const FRAC_2_PI: f64 = 0.636619772367581343075535053490057448_f64;
309 #[stable(feature = "rust1", since = "1.0.0")]
310 pub const FRAC_2_SQRT_PI: f64 = 1.12837916709551257389615890312154517_f64;
313 #[stable(feature = "rust1", since = "1.0.0")]
314 pub const SQRT_2: f64 = 1.41421356237309504880168872420969808_f64;
317 #[stable(feature = "rust1", since = "1.0.0")]
318 pub const FRAC_1_SQRT_2: f64 = 0.707106781186547524400844362104849039_f64;
320 /// Euler's number (e)
321 #[stable(feature = "rust1", since = "1.0.0")]
322 pub const E: f64 = 2.71828182845904523536028747135266250_f64;
324 /// log<sub>2</sub>(10)
325 #[stable(feature = "extra_log_consts", since = "1.43.0")]
326 pub const LOG2_10: f64 = 3.32192809488736234787031942948939018_f64;
328 /// log<sub>2</sub>(e)
329 #[stable(feature = "rust1", since = "1.0.0")]
330 pub const LOG2_E: f64 = 1.44269504088896340735992468100189214_f64;
332 /// log<sub>10</sub>(2)
333 #[stable(feature = "extra_log_consts", since = "1.43.0")]
334 pub const LOG10_2: f64 = 0.301029995663981195213738894724493027_f64;
336 /// log<sub>10</sub>(e)
337 #[stable(feature = "rust1", since = "1.0.0")]
338 pub const LOG10_E: f64 = 0.434294481903251827651128918916605082_f64;
341 #[stable(feature = "rust1", since = "1.0.0")]
342 pub const LN_2: f64 = 0.693147180559945309417232121458176568_f64;
345 #[stable(feature = "rust1", since = "1.0.0")]
346 pub const LN_10: f64 = 2.30258509299404568401799145468436421_f64;
351 /// The radix or base of the internal representation of `f64`.
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 = 53;
358 /// Approximate number of significant digits in base 10.
359 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
360 pub const DIGITS: u32 = 15;
362 /// [Machine epsilon] value for `f64`.
364 /// This is the difference between `1.0` and the next larger representable number.
366 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
367 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
368 pub const EPSILON: f64 = 2.2204460492503131e-16_f64;
370 /// Smallest finite `f64` value.
371 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
372 pub const MIN: f64 = -1.7976931348623157e+308_f64;
373 /// Smallest positive normal `f64` value.
374 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
375 pub const MIN_POSITIVE: f64 = 2.2250738585072014e-308_f64;
376 /// Largest finite `f64` value.
377 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
378 pub const MAX: f64 = 1.7976931348623157e+308_f64;
380 /// One greater than the minimum possible normal power of 2 exponent.
381 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
382 pub const MIN_EXP: i32 = -1021;
383 /// Maximum possible power of 2 exponent.
384 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
385 pub const MAX_EXP: i32 = 1024;
387 /// Minimum possible normal power of 10 exponent.
388 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
389 pub const MIN_10_EXP: i32 = -307;
390 /// Maximum possible power of 10 exponent.
391 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
392 pub const MAX_10_EXP: i32 = 308;
394 /// Not a Number (NaN).
396 /// Note that IEEE 754 doesn't define just a single NaN value;
397 /// a plethora of bit patterns are considered to be NaN.
398 /// Furthermore, the standard makes a difference
399 /// between a "signaling" and a "quiet" NaN,
400 /// and allows inspecting its "payload" (the unspecified bits in the bit pattern).
401 /// This constant isn't guaranteed to equal to any specific NaN bitpattern,
402 /// and the stability of its representation over Rust versions
403 /// and target platforms isn't guaranteed.
404 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
405 pub const NAN: f64 = 0.0_f64 / 0.0_f64;
407 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
408 pub const INFINITY: f64 = 1.0_f64 / 0.0_f64;
409 /// Negative infinity (−∞).
410 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
411 pub const NEG_INFINITY: f64 = -1.0_f64 / 0.0_f64;
413 /// Returns `true` if this value is NaN.
416 /// let nan = f64::NAN;
419 /// assert!(nan.is_nan());
420 /// assert!(!f.is_nan());
423 #[stable(feature = "rust1", since = "1.0.0")]
424 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
426 pub const fn is_nan(self) -> bool {
430 // FIXME(#50145): `abs` is publicly unavailable in libcore due to
431 // concerns about portability, so this implementation is for
432 // private use internally.
434 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
435 pub(crate) const fn abs_private(self) -> f64 {
436 // SAFETY: This transmutation is fine. Probably. For the reasons std is using it.
438 mem::transmute::<u64, f64>(mem::transmute::<f64, u64>(self) & 0x7fff_ffff_ffff_ffff)
442 /// Returns `true` if this value is positive infinity or negative infinity, and
443 /// `false` otherwise.
447 /// let inf = f64::INFINITY;
448 /// let neg_inf = f64::NEG_INFINITY;
449 /// let nan = f64::NAN;
451 /// assert!(!f.is_infinite());
452 /// assert!(!nan.is_infinite());
454 /// assert!(inf.is_infinite());
455 /// assert!(neg_inf.is_infinite());
458 #[stable(feature = "rust1", since = "1.0.0")]
459 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
461 pub const fn is_infinite(self) -> bool {
462 // Getting clever with transmutation can result in incorrect answers on some FPUs
463 // FIXME: alter the Rust <-> Rust calling convention to prevent this problem.
464 // See https://github.com/rust-lang/rust/issues/72327
465 (self == f64::INFINITY) | (self == f64::NEG_INFINITY)
468 /// Returns `true` if this number is neither infinite nor NaN.
472 /// let inf: f64 = f64::INFINITY;
473 /// let neg_inf: f64 = f64::NEG_INFINITY;
474 /// let nan: f64 = f64::NAN;
476 /// assert!(f.is_finite());
478 /// assert!(!nan.is_finite());
479 /// assert!(!inf.is_finite());
480 /// assert!(!neg_inf.is_finite());
483 #[stable(feature = "rust1", since = "1.0.0")]
484 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
486 pub const fn is_finite(self) -> bool {
487 // There's no need to handle NaN separately: if self is NaN,
488 // the comparison is not true, exactly as desired.
489 self.abs_private() < Self::INFINITY
492 /// Returns `true` if the number is [subnormal].
495 /// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308_f64
496 /// let max = f64::MAX;
497 /// let lower_than_min = 1.0e-308_f64;
498 /// let zero = 0.0_f64;
500 /// assert!(!min.is_subnormal());
501 /// assert!(!max.is_subnormal());
503 /// assert!(!zero.is_subnormal());
504 /// assert!(!f64::NAN.is_subnormal());
505 /// assert!(!f64::INFINITY.is_subnormal());
506 /// // Values between `0` and `min` are Subnormal.
507 /// assert!(lower_than_min.is_subnormal());
509 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
511 #[stable(feature = "is_subnormal", since = "1.53.0")]
512 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
514 pub const fn is_subnormal(self) -> bool {
515 matches!(self.classify(), FpCategory::Subnormal)
518 /// Returns `true` if the number is neither zero, infinite,
519 /// [subnormal], or NaN.
522 /// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308f64
523 /// let max = f64::MAX;
524 /// let lower_than_min = 1.0e-308_f64;
525 /// let zero = 0.0f64;
527 /// assert!(min.is_normal());
528 /// assert!(max.is_normal());
530 /// assert!(!zero.is_normal());
531 /// assert!(!f64::NAN.is_normal());
532 /// assert!(!f64::INFINITY.is_normal());
533 /// // Values between `0` and `min` are Subnormal.
534 /// assert!(!lower_than_min.is_normal());
536 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
538 #[stable(feature = "rust1", since = "1.0.0")]
539 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
541 pub const fn is_normal(self) -> bool {
542 matches!(self.classify(), FpCategory::Normal)
545 /// Returns the floating point category of the number. If only one property
546 /// is going to be tested, it is generally faster to use the specific
547 /// predicate instead.
550 /// use std::num::FpCategory;
552 /// let num = 12.4_f64;
553 /// let inf = f64::INFINITY;
555 /// assert_eq!(num.classify(), FpCategory::Normal);
556 /// assert_eq!(inf.classify(), FpCategory::Infinite);
558 #[stable(feature = "rust1", since = "1.0.0")]
559 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
560 pub const fn classify(self) -> FpCategory {
561 // A previous implementation tried to only use bitmask-based checks,
562 // using f64::to_bits to transmute the float to its bit repr and match on that.
563 // Unfortunately, floating point numbers can be much worse than that.
564 // This also needs to not result in recursive evaluations of f64::to_bits.
566 // On some processors, in some cases, LLVM will "helpfully" lower floating point ops,
567 // in spite of a request for them using f32 and f64, to things like x87 operations.
568 // These have an f64's mantissa, but can have a larger than normal exponent.
569 // FIXME(jubilee): Using x87 operations is never necessary in order to function
570 // on x86 processors for Rust-to-Rust calls, so this issue should not happen.
571 // Code generation should be adjusted to use non-C calling conventions, avoiding this.
573 // Thus, a value may compare unequal to infinity, despite having a "full" exponent mask.
574 // And it may not be NaN, as it can simply be an "overextended" finite value.
578 // However, std can't simply compare to zero to check for zero, either,
579 // as correctness requires avoiding equality tests that may be Subnormal == -0.0
580 // because it may be wrong under "denormals are zero" and "flush to zero" modes.
581 // Most of std's targets don't use those, but they are used for thumbv7neon.
582 // So, this does use bitpattern matching for the rest.
584 // SAFETY: f64 to u64 is fine. Usually.
585 // If control flow has gotten this far, the value is definitely in one of the categories
586 // that f64::partial_classify can correctly analyze.
587 unsafe { f64::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 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
595 const unsafe fn partial_classify(self) -> FpCategory {
596 const EXP_MASK: u64 = 0x7ff0000000000000;
597 const MAN_MASK: u64 = 0x000fffffffffffff;
599 // SAFETY: The caller is not asking questions for which this will tell lies.
600 let b = unsafe { mem::transmute::<f64, u64>(self) };
601 match (b & MAN_MASK, b & EXP_MASK) {
602 (0, EXP_MASK) => FpCategory::Infinite,
603 (0, 0) => FpCategory::Zero,
604 (_, 0) => FpCategory::Subnormal,
605 _ => FpCategory::Normal,
609 // This operates on bits, and only bits, so it can ignore concerns about weird FPUs.
610 // FIXME(jubilee): In a just world, this would be the entire impl for classify,
611 // plus a transmute. We do not live in a just world, but we can make it more so.
612 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
613 const fn classify_bits(b: u64) -> FpCategory {
614 const EXP_MASK: u64 = 0x7ff0000000000000;
615 const MAN_MASK: u64 = 0x000fffffffffffff;
617 match (b & MAN_MASK, b & EXP_MASK) {
618 (0, EXP_MASK) => FpCategory::Infinite,
619 (_, EXP_MASK) => FpCategory::Nan,
620 (0, 0) => FpCategory::Zero,
621 (_, 0) => FpCategory::Subnormal,
622 _ => FpCategory::Normal,
626 /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with
627 /// positive sign bit and positive infinity. Note that IEEE 754 doesn't assign any
628 /// meaning to the sign bit in case of a NaN, and as Rust doesn't guarantee that
629 /// the bit pattern of NaNs are conserved over arithmetic operations, the result of
630 /// `is_sign_positive` on a NaN might produce an unexpected result in some cases.
631 /// See [explanation of NaN as a special value](f32) for more info.
635 /// let g = -7.0_f64;
637 /// assert!(f.is_sign_positive());
638 /// assert!(!g.is_sign_positive());
641 #[stable(feature = "rust1", since = "1.0.0")]
642 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
644 pub const fn is_sign_positive(self) -> bool {
645 !self.is_sign_negative()
649 #[stable(feature = "rust1", since = "1.0.0")]
650 #[deprecated(since = "1.0.0", note = "renamed to is_sign_positive")]
653 pub fn is_positive(self) -> bool {
654 self.is_sign_positive()
657 /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with
658 /// negative sign bit and negative infinity. Note that IEEE 754 doesn't assign any
659 /// meaning to the sign bit in case of a NaN, and as Rust doesn't guarantee that
660 /// the bit pattern of NaNs are conserved over arithmetic operations, the result of
661 /// `is_sign_negative` on a NaN might produce an unexpected result in some cases.
662 /// See [explanation of NaN as a special value](f32) for more info.
666 /// let g = -7.0_f64;
668 /// assert!(!f.is_sign_negative());
669 /// assert!(g.is_sign_negative());
672 #[stable(feature = "rust1", since = "1.0.0")]
673 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
675 pub const fn is_sign_negative(self) -> bool {
676 // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
677 // applies to zeros and NaNs as well.
678 // SAFETY: This is just transmuting to get the sign bit, it's fine.
679 unsafe { mem::transmute::<f64, u64>(self) & 0x8000_0000_0000_0000 != 0 }
683 #[stable(feature = "rust1", since = "1.0.0")]
684 #[deprecated(since = "1.0.0", note = "renamed to is_sign_negative")]
687 pub fn is_negative(self) -> bool {
688 self.is_sign_negative()
691 /// Returns the least number greater than `self`.
693 /// Let `TINY` be the smallest representable positive `f64`. Then,
694 /// - if `self.is_nan()`, this returns `self`;
695 /// - if `self` is [`NEG_INFINITY`], this returns [`MIN`];
696 /// - if `self` is `-TINY`, this returns -0.0;
697 /// - if `self` is -0.0 or +0.0, this returns `TINY`;
698 /// - if `self` is [`MAX`] or [`INFINITY`], this returns [`INFINITY`];
699 /// - otherwise the unique least value greater than `self` is returned.
701 /// The identity `x.next_up() == -(-x).next_down()` holds for all non-NaN `x`. When `x`
702 /// is finite `x == x.next_up().next_down()` also holds.
705 /// #![feature(float_next_up_down)]
706 /// // f64::EPSILON is the difference between 1.0 and the next number up.
707 /// assert_eq!(1.0f64.next_up(), 1.0 + f64::EPSILON);
708 /// // But not for most numbers.
709 /// assert!(0.1f64.next_up() < 0.1 + f64::EPSILON);
710 /// assert_eq!(9007199254740992f64.next_up(), 9007199254740994.0);
713 /// [`NEG_INFINITY`]: Self::NEG_INFINITY
714 /// [`INFINITY`]: Self::INFINITY
715 /// [`MIN`]: Self::MIN
716 /// [`MAX`]: Self::MAX
717 #[unstable(feature = "float_next_up_down", issue = "91399")]
718 #[rustc_const_unstable(feature = "float_next_up_down", issue = "91399")]
719 pub const fn next_up(self) -> Self {
720 // We must use strictly integer arithmetic to prevent denormals from
721 // flushing to zero after an arithmetic operation on some platforms.
722 const TINY_BITS: u64 = 0x1; // Smallest positive f64.
723 const CLEAR_SIGN_MASK: u64 = 0x7fff_ffff_ffff_ffff;
725 let bits = self.to_bits();
726 if self.is_nan() || bits == Self::INFINITY.to_bits() {
730 let abs = bits & CLEAR_SIGN_MASK;
731 let next_bits = if abs == 0 {
733 } else if bits == abs {
738 Self::from_bits(next_bits)
741 /// Returns the greatest number less than `self`.
743 /// Let `TINY` be the smallest representable positive `f64`. Then,
744 /// - if `self.is_nan()`, this returns `self`;
745 /// - if `self` is [`INFINITY`], this returns [`MAX`];
746 /// - if `self` is `TINY`, this returns 0.0;
747 /// - if `self` is -0.0 or +0.0, this returns `-TINY`;
748 /// - if `self` is [`MIN`] or [`NEG_INFINITY`], this returns [`NEG_INFINITY`];
749 /// - otherwise the unique greatest value less than `self` is returned.
751 /// The identity `x.next_down() == -(-x).next_up()` holds for all non-NaN `x`. When `x`
752 /// is finite `x == x.next_down().next_up()` also holds.
755 /// #![feature(float_next_up_down)]
757 /// // Clamp value into range [0, 1).
758 /// let clamped = x.clamp(0.0, 1.0f64.next_down());
759 /// assert!(clamped < 1.0);
760 /// assert_eq!(clamped.next_up(), 1.0);
763 /// [`NEG_INFINITY`]: Self::NEG_INFINITY
764 /// [`INFINITY`]: Self::INFINITY
765 /// [`MIN`]: Self::MIN
766 /// [`MAX`]: Self::MAX
767 #[unstable(feature = "float_next_up_down", issue = "91399")]
768 #[rustc_const_unstable(feature = "float_next_up_down", issue = "91399")]
769 pub const fn next_down(self) -> Self {
770 // We must use strictly integer arithmetic to prevent denormals from
771 // flushing to zero after an arithmetic operation on some platforms.
772 const NEG_TINY_BITS: u64 = 0x8000_0000_0000_0001; // Smallest (in magnitude) negative f64.
773 const CLEAR_SIGN_MASK: u64 = 0x7fff_ffff_ffff_ffff;
775 let bits = self.to_bits();
776 if self.is_nan() || bits == Self::NEG_INFINITY.to_bits() {
780 let abs = bits & CLEAR_SIGN_MASK;
781 let next_bits = if abs == 0 {
783 } else if bits == abs {
788 Self::from_bits(next_bits)
791 /// Takes the reciprocal (inverse) of a number, `1/x`.
795 /// let abs_difference = (x.recip() - (1.0 / x)).abs();
797 /// assert!(abs_difference < 1e-10);
799 #[must_use = "this returns the result of the operation, without modifying the original"]
800 #[stable(feature = "rust1", since = "1.0.0")]
802 pub fn recip(self) -> f64 {
806 /// Converts radians to degrees.
809 /// let angle = std::f64::consts::PI;
811 /// let abs_difference = (angle.to_degrees() - 180.0).abs();
813 /// assert!(abs_difference < 1e-10);
815 #[must_use = "this returns the result of the operation, \
816 without modifying the original"]
817 #[stable(feature = "rust1", since = "1.0.0")]
819 pub fn to_degrees(self) -> f64 {
820 // The division here is correctly rounded with respect to the true
821 // value of 180/π. (This differs from f32, where a constant must be
822 // used to ensure a correctly rounded result.)
823 self * (180.0f64 / consts::PI)
826 /// Converts degrees to radians.
829 /// let angle = 180.0_f64;
831 /// let abs_difference = (angle.to_radians() - std::f64::consts::PI).abs();
833 /// assert!(abs_difference < 1e-10);
835 #[must_use = "this returns the result of the operation, \
836 without modifying the original"]
837 #[stable(feature = "rust1", since = "1.0.0")]
839 pub fn to_radians(self) -> f64 {
840 let value: f64 = consts::PI;
841 self * (value / 180.0)
844 /// Returns the maximum of the two numbers, ignoring NaN.
846 /// If one of the arguments is NaN, then the other argument is returned.
847 /// This follows the IEEE 754-2008 semantics for maxNum, except for handling of signaling NaNs;
848 /// this function handles all NaNs the same way and avoids maxNum's problems with associativity.
849 /// This also matches the behavior of libm’s fmax.
855 /// assert_eq!(x.max(y), y);
857 #[must_use = "this returns the result of the comparison, without modifying either input"]
858 #[stable(feature = "rust1", since = "1.0.0")]
860 pub fn max(self, other: f64) -> f64 {
861 intrinsics::maxnumf64(self, other)
864 /// Returns the minimum of the two numbers, ignoring NaN.
866 /// If one of the arguments is NaN, then the other argument is returned.
867 /// This follows the IEEE 754-2008 semantics for minNum, except for handling of signaling NaNs;
868 /// this function handles all NaNs the same way and avoids minNum's problems with associativity.
869 /// This also matches the behavior of libm’s fmin.
875 /// assert_eq!(x.min(y), x);
877 #[must_use = "this returns the result of the comparison, without modifying either input"]
878 #[stable(feature = "rust1", since = "1.0.0")]
880 pub fn min(self, other: f64) -> f64 {
881 intrinsics::minnumf64(self, other)
884 /// Returns the maximum of the two numbers, propagating NaN.
886 /// This returns NaN when *either* argument is NaN, as opposed to
887 /// [`f64::max`] which only returns NaN when *both* arguments are NaN.
890 /// #![feature(float_minimum_maximum)]
894 /// assert_eq!(x.maximum(y), y);
895 /// assert!(x.maximum(f64::NAN).is_nan());
898 /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the greater
899 /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
900 /// Note that this follows the semantics specified in IEEE 754-2019.
902 /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
903 /// operand is conserved; see [explanation of NaN as a special value](f32) for more info.
904 #[must_use = "this returns the result of the comparison, without modifying either input"]
905 #[unstable(feature = "float_minimum_maximum", issue = "91079")]
907 pub fn maximum(self, other: f64) -> f64 {
910 } else if other > self {
912 } else if self == other {
913 if self.is_sign_positive() && other.is_sign_negative() { self } else { other }
919 /// Returns the minimum of the two numbers, propagating NaN.
921 /// This returns NaN when *either* argument is NaN, as opposed to
922 /// [`f64::min`] which only returns NaN when *both* arguments are NaN.
925 /// #![feature(float_minimum_maximum)]
929 /// assert_eq!(x.minimum(y), x);
930 /// assert!(x.minimum(f64::NAN).is_nan());
933 /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the lesser
934 /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
935 /// Note that this follows the semantics specified in IEEE 754-2019.
937 /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
938 /// operand is conserved; see [explanation of NaN as a special value](f32) for more info.
939 #[must_use = "this returns the result of the comparison, without modifying either input"]
940 #[unstable(feature = "float_minimum_maximum", issue = "91079")]
942 pub fn minimum(self, other: f64) -> f64 {
945 } else if other < self {
947 } else if self == other {
948 if self.is_sign_negative() && other.is_sign_positive() { self } else { other }
954 /// Rounds toward zero and converts to any primitive integer type,
955 /// assuming that the value is finite and fits in that type.
958 /// let value = 4.6_f64;
959 /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
960 /// assert_eq!(rounded, 4);
962 /// let value = -128.9_f64;
963 /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
964 /// assert_eq!(rounded, i8::MIN);
972 /// * Not be infinite
973 /// * Be representable in the return type `Int`, after truncating off its fractional part
974 #[must_use = "this returns the result of the operation, \
975 without modifying the original"]
976 #[stable(feature = "float_approx_unchecked_to", since = "1.44.0")]
978 pub unsafe fn to_int_unchecked<Int>(self) -> Int
980 Self: FloatToInt<Int>,
982 // SAFETY: the caller must uphold the safety contract for
983 // `FloatToInt::to_int_unchecked`.
984 unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
987 /// Raw transmutation to `u64`.
989 /// This is currently identical to `transmute::<f64, u64>(self)` on all platforms.
991 /// See [`from_bits`](Self::from_bits) for some discussion of the
992 /// portability of this operation (there are almost no issues).
994 /// Note that this function is distinct from `as` casting, which attempts to
995 /// preserve the *numeric* value, and not the bitwise value.
1000 /// assert!((1f64).to_bits() != 1f64 as u64); // to_bits() is not casting!
1001 /// assert_eq!((12.5f64).to_bits(), 0x4029000000000000);
1004 #[must_use = "this returns the result of the operation, \
1005 without modifying the original"]
1006 #[stable(feature = "float_bits_conv", since = "1.20.0")]
1007 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1009 pub const fn to_bits(self) -> u64 {
1010 // SAFETY: `u64` is a plain old datatype so we can always transmute to it.
1013 // See the SAFETY comment in f64::from_bits for more.
1014 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1015 const fn ct_f64_to_u64(ct: f64) -> u64 {
1016 match ct.classify() {
1017 FpCategory::Nan => {
1018 panic!("const-eval error: cannot use f64::to_bits on a NaN")
1020 FpCategory::Subnormal => {
1021 panic!("const-eval error: cannot use f64::to_bits on a subnormal number")
1023 FpCategory::Infinite | FpCategory::Normal | FpCategory::Zero => {
1024 // SAFETY: We have a normal floating point number. Now we transmute, i.e. do a bitcopy.
1025 unsafe { mem::transmute::<f64, u64>(ct) }
1030 #[inline(always)] // See https://github.com/rust-lang/compiler-builtins/issues/491
1031 fn rt_f64_to_u64(rt: f64) -> u64 {
1032 // SAFETY: `u64` is a plain old datatype so we can always... uh...
1033 // ...look, just pretend you forgot what you just read.
1034 // Stability concerns.
1035 unsafe { mem::transmute::<f64, u64>(rt) }
1037 // SAFETY: We use internal implementations that either always work or fail at compile time.
1038 unsafe { intrinsics::const_eval_select((self,), ct_f64_to_u64, rt_f64_to_u64) }
1041 /// Raw transmutation from `u64`.
1043 /// This is currently identical to `transmute::<u64, f64>(v)` on all platforms.
1044 /// It turns out this is incredibly portable, for two reasons:
1046 /// * Floats and Ints have the same endianness on all supported platforms.
1047 /// * IEEE 754 very precisely specifies the bit layout of floats.
1049 /// However there is one caveat: prior to the 2008 version of IEEE 754, how
1050 /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
1051 /// (notably x86 and ARM) picked the interpretation that was ultimately
1052 /// standardized in 2008, but some didn't (notably MIPS). As a result, all
1053 /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
1055 /// Rather than trying to preserve signaling-ness cross-platform, this
1056 /// implementation favors preserving the exact bits. This means that
1057 /// any payloads encoded in NaNs will be preserved even if the result of
1058 /// this method is sent over the network from an x86 machine to a MIPS one.
1060 /// If the results of this method are only manipulated by the same
1061 /// architecture that produced them, then there is no portability concern.
1063 /// If the input isn't NaN, then there is no portability concern.
1065 /// If you don't care about signaling-ness (very likely), then there is no
1066 /// portability concern.
1068 /// Note that this function is distinct from `as` casting, which attempts to
1069 /// preserve the *numeric* value, and not the bitwise value.
1074 /// let v = f64::from_bits(0x4029000000000000);
1075 /// assert_eq!(v, 12.5);
1077 #[stable(feature = "float_bits_conv", since = "1.20.0")]
1078 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1081 pub const fn from_bits(v: u64) -> Self {
1082 // It turns out the safety issues with sNaN were overblown! Hooray!
1083 // SAFETY: `u64` is a plain old datatype so we can always transmute from it
1086 // It turns out that at runtime, it is possible for a floating point number
1087 // to be subject to floating point modes that alter nonzero subnormal numbers
1088 // to zero on reads and writes, aka "denormals are zero" and "flush to zero".
1089 // This is not a problem usually, but at least one tier2 platform for Rust
1090 // actually exhibits an FTZ behavior by default: thumbv7neon
1091 // aka "the Neon FPU in AArch32 state"
1093 // Even with this, not all instructions exhibit the FTZ behaviors on thumbv7neon,
1094 // so this should load the same bits if LLVM emits the "correct" instructions,
1095 // but LLVM sometimes makes interesting choices about float optimization,
1096 // and other FPUs may do similar. Thus, it is wise to indulge luxuriously in caution.
1098 // In addition, on x86 targets with SSE or SSE2 disabled and the x87 FPU enabled,
1099 // i.e. not soft-float, the way Rust does parameter passing can actually alter
1100 // a number that is "not infinity" to have the same exponent as infinity,
1101 // in a slightly unpredictable manner.
1103 // And, of course evaluating to a NaN value is fairly nondeterministic.
1104 // More precisely: when NaN should be returned is knowable, but which NaN?
1105 // So far that's defined by a combination of LLVM and the CPU, not Rust.
1106 // This function, however, allows observing the bitstring of a NaN,
1107 // thus introspection on CTFE.
1109 // In order to preserve, at least for the moment, const-to-runtime equivalence,
1110 // reject any of these possible situations from happening.
1111 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1112 const fn ct_u64_to_f64(ct: u64) -> f64 {
1113 match f64::classify_bits(ct) {
1114 FpCategory::Subnormal => {
1115 panic!("const-eval error: cannot use f64::from_bits on a subnormal number")
1117 FpCategory::Nan => {
1118 panic!("const-eval error: cannot use f64::from_bits on NaN")
1120 FpCategory::Infinite | FpCategory::Normal | FpCategory::Zero => {
1121 // SAFETY: It's not a frumious number
1122 unsafe { mem::transmute::<u64, f64>(ct) }
1127 #[inline(always)] // See https://github.com/rust-lang/compiler-builtins/issues/491
1128 fn rt_u64_to_f64(rt: u64) -> f64 {
1129 // SAFETY: `u64` is a plain old datatype so we can always... uh...
1130 // ...look, just pretend you forgot what you just read.
1131 // Stability concerns.
1132 unsafe { mem::transmute::<u64, f64>(rt) }
1134 // SAFETY: We use internal implementations that either always work or fail at compile time.
1135 unsafe { intrinsics::const_eval_select((v,), ct_u64_to_f64, rt_u64_to_f64) }
1138 /// Return the memory representation of this floating point number as a byte array in
1139 /// big-endian (network) byte order.
1141 /// See [`from_bits`](Self::from_bits) for some discussion of the
1142 /// portability of this operation (there are almost no issues).
1147 /// let bytes = 12.5f64.to_be_bytes();
1148 /// assert_eq!(bytes, [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1150 #[must_use = "this returns the result of the operation, \
1151 without modifying the original"]
1152 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1153 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1155 pub const fn to_be_bytes(self) -> [u8; 8] {
1156 self.to_bits().to_be_bytes()
1159 /// Return the memory representation of this floating point number as a byte array in
1160 /// little-endian byte order.
1162 /// See [`from_bits`](Self::from_bits) for some discussion of the
1163 /// portability of this operation (there are almost no issues).
1168 /// let bytes = 12.5f64.to_le_bytes();
1169 /// assert_eq!(bytes, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]);
1171 #[must_use = "this returns the result of the operation, \
1172 without modifying the original"]
1173 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1174 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1176 pub const fn to_le_bytes(self) -> [u8; 8] {
1177 self.to_bits().to_le_bytes()
1180 /// Return the memory representation of this floating point number as a byte array in
1181 /// native byte order.
1183 /// As the target platform's native endianness is used, portable code
1184 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1186 /// [`to_be_bytes`]: f64::to_be_bytes
1187 /// [`to_le_bytes`]: f64::to_le_bytes
1189 /// See [`from_bits`](Self::from_bits) for some discussion of the
1190 /// portability of this operation (there are almost no issues).
1195 /// let bytes = 12.5f64.to_ne_bytes();
1198 /// if cfg!(target_endian = "big") {
1199 /// [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1201 /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]
1205 #[must_use = "this returns the result of the operation, \
1206 without modifying the original"]
1207 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1208 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1210 pub const fn to_ne_bytes(self) -> [u8; 8] {
1211 self.to_bits().to_ne_bytes()
1214 /// Create a floating point value from its representation as a byte array in big endian.
1216 /// See [`from_bits`](Self::from_bits) for some discussion of the
1217 /// portability of this operation (there are almost no issues).
1222 /// let value = f64::from_be_bytes([0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1223 /// assert_eq!(value, 12.5);
1225 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1226 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1229 pub const fn from_be_bytes(bytes: [u8; 8]) -> Self {
1230 Self::from_bits(u64::from_be_bytes(bytes))
1233 /// Create a floating point value from its representation as a byte array in little endian.
1235 /// See [`from_bits`](Self::from_bits) for some discussion of the
1236 /// portability of this operation (there are almost no issues).
1241 /// let value = f64::from_le_bytes([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]);
1242 /// assert_eq!(value, 12.5);
1244 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1245 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1248 pub const fn from_le_bytes(bytes: [u8; 8]) -> Self {
1249 Self::from_bits(u64::from_le_bytes(bytes))
1252 /// Create a floating point value from its representation as a byte array in native endian.
1254 /// As the target platform's native endianness is used, portable code
1255 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1256 /// appropriate instead.
1258 /// [`from_be_bytes`]: f64::from_be_bytes
1259 /// [`from_le_bytes`]: f64::from_le_bytes
1261 /// See [`from_bits`](Self::from_bits) for some discussion of the
1262 /// portability of this operation (there are almost no issues).
1267 /// let value = f64::from_ne_bytes(if cfg!(target_endian = "big") {
1268 /// [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1270 /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]
1272 /// assert_eq!(value, 12.5);
1274 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1275 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1278 pub const fn from_ne_bytes(bytes: [u8; 8]) -> Self {
1279 Self::from_bits(u64::from_ne_bytes(bytes))
1282 /// Return the ordering between `self` and `other`.
1284 /// Unlike the standard partial comparison between floating point numbers,
1285 /// this comparison always produces an ordering in accordance to
1286 /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1287 /// floating point standard. The values are ordered in the following sequence:
1289 /// - negative quiet NaN
1290 /// - negative signaling NaN
1291 /// - negative infinity
1292 /// - negative numbers
1293 /// - negative subnormal numbers
1296 /// - positive subnormal numbers
1297 /// - positive numbers
1298 /// - positive infinity
1299 /// - positive signaling NaN
1300 /// - positive quiet NaN.
1302 /// The ordering established by this function does not always agree with the
1303 /// [`PartialOrd`] and [`PartialEq`] implementations of `f64`. For example,
1304 /// they consider negative and positive zero equal, while `total_cmp`
1307 /// The interpretation of the signaling NaN bit follows the definition in
1308 /// the IEEE 754 standard, which may not match the interpretation by some of
1309 /// the older, non-conformant (e.g. MIPS) hardware implementations.
1314 /// struct GoodBoy {
1319 /// let mut bois = vec![
1320 /// GoodBoy { name: "Pucci".to_owned(), weight: 0.1 },
1321 /// GoodBoy { name: "Woofer".to_owned(), weight: 99.0 },
1322 /// GoodBoy { name: "Yapper".to_owned(), weight: 10.0 },
1323 /// GoodBoy { name: "Chonk".to_owned(), weight: f64::INFINITY },
1324 /// GoodBoy { name: "Abs. Unit".to_owned(), weight: f64::NAN },
1325 /// GoodBoy { name: "Floaty".to_owned(), weight: -5.0 },
1328 /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1329 /// # assert!(bois.into_iter().map(|b| b.weight)
1330 /// # .zip([-5.0, 0.1, 10.0, 99.0, f64::INFINITY, f64::NAN].iter())
1331 /// # .all(|(a, b)| a.to_bits() == b.to_bits()))
1333 #[stable(feature = "total_cmp", since = "1.62.0")]
1336 pub fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1337 let mut left = self.to_bits() as i64;
1338 let mut right = other.to_bits() as i64;
1340 // In case of negatives, flip all the bits except the sign
1341 // to achieve a similar layout as two's complement integers
1343 // Why does this work? IEEE 754 floats consist of three fields:
1344 // Sign bit, exponent and mantissa. The set of exponent and mantissa
1345 // fields as a whole have the property that their bitwise order is
1346 // equal to the numeric magnitude where the magnitude is defined.
1347 // The magnitude is not normally defined on NaN values, but
1348 // IEEE 754 totalOrder defines the NaN values also to follow the
1349 // bitwise order. This leads to order explained in the doc comment.
1350 // However, the representation of magnitude is the same for negative
1351 // and positive numbers – only the sign bit is different.
1352 // To easily compare the floats as signed integers, we need to
1353 // flip the exponent and mantissa bits in case of negative numbers.
1354 // We effectively convert the numbers to "two's complement" form.
1356 // To do the flipping, we construct a mask and XOR against it.
1357 // We branchlessly calculate an "all-ones except for the sign bit"
1358 // mask from negative-signed values: right shifting sign-extends
1359 // the integer, so we "fill" the mask with sign bits, and then
1360 // convert to unsigned to push one more zero bit.
1361 // On positive values, the mask is all zeros, so it's a no-op.
1362 left ^= (((left >> 63) as u64) >> 1) as i64;
1363 right ^= (((right >> 63) as u64) >> 1) as i64;
1368 /// Restrict a value to a certain interval unless it is NaN.
1370 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1371 /// less than `min`. Otherwise this returns `self`.
1373 /// Note that this function returns NaN if the initial value was NaN as
1378 /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1383 /// assert!((-3.0f64).clamp(-2.0, 1.0) == -2.0);
1384 /// assert!((0.0f64).clamp(-2.0, 1.0) == 0.0);
1385 /// assert!((2.0f64).clamp(-2.0, 1.0) == 1.0);
1386 /// assert!((f64::NAN).clamp(-2.0, 1.0).is_nan());
1388 #[must_use = "method returns a new number and does not mutate the original value"]
1389 #[stable(feature = "clamp", since = "1.50.0")]
1391 pub fn clamp(mut self, min: f64, max: f64) -> f64 {
1392 assert!(min <= max);