1 //! Constants specific to the `f64` double-precision floating point type. 2 //! 3 //! *[See also the `f64` primitive type][f64].* 4 //! 5 //! Mathematically significant numbers are provided in the `consts` sub-module. 6 //! 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. 11 12 #![stable(feature = "rust1", since = "1.0.0")] 13 14 use crate::convert::FloatToInt; 15 #[cfg(not(test))] 16 use crate::intrinsics; 17 use crate::mem; 18 use crate::num::FpCategory; 19 20 /// The radix or base of the internal representation of `f64`. 21 /// Use [`f64::RADIX`] instead. 22 /// 23 /// # Examples 24 /// 25 /// ```rust 26 /// // deprecated way 27 /// # #[allow(deprecated, deprecated_in_future)] 28 /// let r = std::f64::RADIX; 29 /// 30 /// // intended way 31 /// let r = f64::RADIX; 32 /// ``` 33 #[stable(feature = "rust1", since = "1.0.0")] 34 #[rustc_deprecated(since = "TBD", reason = "replaced by the `RADIX` associated constant on `f64`")] 35 pub const RADIX: u32 = f64::RADIX; 36 37 /// Number of significant digits in base 2. 38 /// Use [`f64::MANTISSA_DIGITS`] instead. 39 /// 40 /// # Examples 41 /// 42 /// ```rust 43 /// // deprecated way 44 /// # #[allow(deprecated, deprecated_in_future)] 45 /// let d = std::f64::MANTISSA_DIGITS; 46 /// 47 /// // intended way 48 /// let d = f64::MANTISSA_DIGITS; 49 /// ``` 50 #[stable(feature = "rust1", since = "1.0.0")] 51 #[rustc_deprecated( 52 since = "TBD", 53 reason = "replaced by the `MANTISSA_DIGITS` associated constant on `f64`" 54 )] 55 pub const MANTISSA_DIGITS: u32 = f64::MANTISSA_DIGITS; 56 57 /// Approximate number of significant digits in base 10. 58 /// Use [`f64::DIGITS`] instead. 59 /// 60 /// # Examples 61 /// 62 /// ```rust 63 /// // deprecated way 64 /// # #[allow(deprecated, deprecated_in_future)] 65 /// let d = std::f64::DIGITS; 66 /// 67 /// // intended way 68 /// let d = f64::DIGITS; 69 /// ``` 70 #[stable(feature = "rust1", since = "1.0.0")] 71 #[rustc_deprecated(since = "TBD", reason = "replaced by the `DIGITS` associated constant on `f64`")] 72 pub const DIGITS: u32 = f64::DIGITS; 73 74 /// [Machine epsilon] value for `f64`. 75 /// Use [`f64::EPSILON`] instead. 76 /// 77 /// This is the difference between `1.0` and the next larger representable number. 78 /// 79 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon 80 /// 81 /// # Examples 82 /// 83 /// ```rust 84 /// // deprecated way 85 /// # #[allow(deprecated, deprecated_in_future)] 86 /// let e = std::f64::EPSILON; 87 /// 88 /// // intended way 89 /// let e = f64::EPSILON; 90 /// ``` 91 #[stable(feature = "rust1", since = "1.0.0")] 92 #[rustc_deprecated( 93 since = "TBD", 94 reason = "replaced by the `EPSILON` associated constant on `f64`" 95 )] 96 pub const EPSILON: f64 = f64::EPSILON; 97 98 /// Smallest finite `f64` value. 99 /// Use [`f64::MIN`] instead. 100 /// 101 /// # Examples 102 /// 103 /// ```rust 104 /// // deprecated way 105 /// # #[allow(deprecated, deprecated_in_future)] 106 /// let min = std::f64::MIN; 107 /// 108 /// // intended way 109 /// let min = f64::MIN; 110 /// ``` 111 #[stable(feature = "rust1", since = "1.0.0")] 112 #[rustc_deprecated(since = "TBD", reason = "replaced by the `MIN` associated constant on `f64`")] 113 pub const MIN: f64 = f64::MIN; 114 115 /// Smallest positive normal `f64` value. 116 /// Use [`f64::MIN_POSITIVE`] instead. 117 /// 118 /// # Examples 119 /// 120 /// ```rust 121 /// // deprecated way 122 /// # #[allow(deprecated, deprecated_in_future)] 123 /// let min = std::f64::MIN_POSITIVE; 124 /// 125 /// // intended way 126 /// let min = f64::MIN_POSITIVE; 127 /// ``` 128 #[stable(feature = "rust1", since = "1.0.0")] 129 #[rustc_deprecated( 130 since = "TBD", 131 reason = "replaced by the `MIN_POSITIVE` associated constant on `f64`" 132 )] 133 pub const MIN_POSITIVE: f64 = f64::MIN_POSITIVE; 134 135 /// Largest finite `f64` value. 136 /// Use [`f64::MAX`] instead. 137 /// 138 /// # Examples 139 /// 140 /// ```rust 141 /// // deprecated way 142 /// # #[allow(deprecated, deprecated_in_future)] 143 /// let max = std::f64::MAX; 144 /// 145 /// // intended way 146 /// let max = f64::MAX; 147 /// ``` 148 #[stable(feature = "rust1", since = "1.0.0")] 149 #[rustc_deprecated(since = "TBD", reason = "replaced by the `MAX` associated constant on `f64`")] 150 pub const MAX: f64 = f64::MAX; 151 152 /// One greater than the minimum possible normal power of 2 exponent. 153 /// Use [`f64::MIN_EXP`] instead. 154 /// 155 /// # Examples 156 /// 157 /// ```rust 158 /// // deprecated way 159 /// # #[allow(deprecated, deprecated_in_future)] 160 /// let min = std::f64::MIN_EXP; 161 /// 162 /// // intended way 163 /// let min = f64::MIN_EXP; 164 /// ``` 165 #[stable(feature = "rust1", since = "1.0.0")] 166 #[rustc_deprecated( 167 since = "TBD", 168 reason = "replaced by the `MIN_EXP` associated constant on `f64`" 169 )] 170 pub const MIN_EXP: i32 = f64::MIN_EXP; 171 172 /// Maximum possible power of 2 exponent. 173 /// Use [`f64::MAX_EXP`] instead. 174 /// 175 /// # Examples 176 /// 177 /// ```rust 178 /// // deprecated way 179 /// # #[allow(deprecated, deprecated_in_future)] 180 /// let max = std::f64::MAX_EXP; 181 /// 182 /// // intended way 183 /// let max = f64::MAX_EXP; 184 /// ``` 185 #[stable(feature = "rust1", since = "1.0.0")] 186 #[rustc_deprecated( 187 since = "TBD", 188 reason = "replaced by the `MAX_EXP` associated constant on `f64`" 189 )] 190 pub const MAX_EXP: i32 = f64::MAX_EXP; 191 192 /// Minimum possible normal power of 10 exponent. 193 /// Use [`f64::MIN_10_EXP`] instead. 194 /// 195 /// # Examples 196 /// 197 /// ```rust 198 /// // deprecated way 199 /// # #[allow(deprecated, deprecated_in_future)] 200 /// let min = std::f64::MIN_10_EXP; 201 /// 202 /// // intended way 203 /// let min = f64::MIN_10_EXP; 204 /// ``` 205 #[stable(feature = "rust1", since = "1.0.0")] 206 #[rustc_deprecated( 207 since = "TBD", 208 reason = "replaced by the `MIN_10_EXP` associated constant on `f64`" 209 )] 210 pub const MIN_10_EXP: i32 = f64::MIN_10_EXP; 211 212 /// Maximum possible power of 10 exponent. 213 /// Use [`f64::MAX_10_EXP`] instead. 214 /// 215 /// # Examples 216 /// 217 /// ```rust 218 /// // deprecated way 219 /// # #[allow(deprecated, deprecated_in_future)] 220 /// let max = std::f64::MAX_10_EXP; 221 /// 222 /// // intended way 223 /// let max = f64::MAX_10_EXP; 224 /// ``` 225 #[stable(feature = "rust1", since = "1.0.0")] 226 #[rustc_deprecated( 227 since = "TBD", 228 reason = "replaced by the `MAX_10_EXP` associated constant on `f64`" 229 )] 230 pub const MAX_10_EXP: i32 = f64::MAX_10_EXP; 231 232 /// Not a Number (NaN). 233 /// Use [`f64::NAN`] instead. 234 /// 235 /// # Examples 236 /// 237 /// ```rust 238 /// // deprecated way 239 /// # #[allow(deprecated, deprecated_in_future)] 240 /// let nan = std::f64::NAN; 241 /// 242 /// // intended way 243 /// let nan = f64::NAN; 244 /// ``` 245 #[stable(feature = "rust1", since = "1.0.0")] 246 #[rustc_deprecated(since = "TBD", reason = "replaced by the `NAN` associated constant on `f64`")] 247 pub const NAN: f64 = f64::NAN; 248 249 /// Infinity (∞). 250 /// Use [`f64::INFINITY`] instead. 251 /// 252 /// # Examples 253 /// 254 /// ```rust 255 /// // deprecated way 256 /// # #[allow(deprecated, deprecated_in_future)] 257 /// let inf = std::f64::INFINITY; 258 /// 259 /// // intended way 260 /// let inf = f64::INFINITY; 261 /// ``` 262 #[stable(feature = "rust1", since = "1.0.0")] 263 #[rustc_deprecated( 264 since = "TBD", 265 reason = "replaced by the `INFINITY` associated constant on `f64`" 266 )] 267 pub const INFINITY: f64 = f64::INFINITY; 268 269 /// Negative infinity (−∞). 270 /// Use [`f64::NEG_INFINITY`] instead. 271 /// 272 /// # Examples 273 /// 274 /// ```rust 275 /// // deprecated way 276 /// # #[allow(deprecated, deprecated_in_future)] 277 /// let ninf = std::f64::NEG_INFINITY; 278 /// 279 /// // intended way 280 /// let ninf = f64::NEG_INFINITY; 281 /// ``` 282 #[stable(feature = "rust1", since = "1.0.0")] 283 #[rustc_deprecated( 284 since = "TBD", 285 reason = "replaced by the `NEG_INFINITY` associated constant on `f64`" 286 )] 287 pub const NEG_INFINITY: f64 = f64::NEG_INFINITY; 288 289 /// Basic mathematical constants. 290 #[stable(feature = "rust1", since = "1.0.0")] 291 pub mod consts { 292 // FIXME: replace with mathematical constants from cmath. 293 294 /// Archimedes' constant (π) 295 #[stable(feature = "rust1", since = "1.0.0")] 296 pub const PI: f64 = 3.14159265358979323846264338327950288_f64; 297 298 /// The full circle constant (τ) 299 /// 300 /// Equal to 2π. 301 #[stable(feature = "tau_constant", since = "1.47.0")] 302 pub const TAU: f64 = 6.28318530717958647692528676655900577_f64; 303 304 /// π/2 305 #[stable(feature = "rust1", since = "1.0.0")] 306 pub const FRAC_PI_2: f64 = 1.57079632679489661923132169163975144_f64; 307 308 /// π/3 309 #[stable(feature = "rust1", since = "1.0.0")] 310 pub const FRAC_PI_3: f64 = 1.04719755119659774615421446109316763_f64; 311 312 /// π/4 313 #[stable(feature = "rust1", since = "1.0.0")] 314 pub const FRAC_PI_4: f64 = 0.785398163397448309615660845819875721_f64; 315 316 /// π/6 317 #[stable(feature = "rust1", since = "1.0.0")] 318 pub const FRAC_PI_6: f64 = 0.52359877559829887307710723054658381_f64; 319 320 /// π/8 321 #[stable(feature = "rust1", since = "1.0.0")] 322 pub const FRAC_PI_8: f64 = 0.39269908169872415480783042290993786_f64; 323 324 /// 1/π 325 #[stable(feature = "rust1", since = "1.0.0")] 326 pub const FRAC_1_PI: f64 = 0.318309886183790671537767526745028724_f64; 327 328 /// 2/π 329 #[stable(feature = "rust1", since = "1.0.0")] 330 pub const FRAC_2_PI: f64 = 0.636619772367581343075535053490057448_f64; 331 332 /// 2/sqrt(π) 333 #[stable(feature = "rust1", since = "1.0.0")] 334 pub const FRAC_2_SQRT_PI: f64 = 1.12837916709551257389615890312154517_f64; 335 336 /// sqrt(2) 337 #[stable(feature = "rust1", since = "1.0.0")] 338 pub const SQRT_2: f64 = 1.41421356237309504880168872420969808_f64; 339 340 /// 1/sqrt(2) 341 #[stable(feature = "rust1", since = "1.0.0")] 342 pub const FRAC_1_SQRT_2: f64 = 0.707106781186547524400844362104849039_f64; 343 344 /// Euler's number (e) 345 #[stable(feature = "rust1", since = "1.0.0")] 346 pub const E: f64 = 2.71828182845904523536028747135266250_f64; 347 348 /// log<sub>2</sub>(10) 349 #[stable(feature = "extra_log_consts", since = "1.43.0")] 350 pub const LOG2_10: f64 = 3.32192809488736234787031942948939018_f64; 351 352 /// log<sub>2</sub>(e) 353 #[stable(feature = "rust1", since = "1.0.0")] 354 pub const LOG2_E: f64 = 1.44269504088896340735992468100189214_f64; 355 356 /// log<sub>10</sub>(2) 357 #[stable(feature = "extra_log_consts", since = "1.43.0")] 358 pub const LOG10_2: f64 = 0.301029995663981195213738894724493027_f64; 359 360 /// log<sub>10</sub>(e) 361 #[stable(feature = "rust1", since = "1.0.0")] 362 pub const LOG10_E: f64 = 0.434294481903251827651128918916605082_f64; 363 364 /// ln(2) 365 #[stable(feature = "rust1", since = "1.0.0")] 366 pub const LN_2: f64 = 0.693147180559945309417232121458176568_f64; 367 368 /// ln(10) 369 #[stable(feature = "rust1", since = "1.0.0")] 370 pub const LN_10: f64 = 2.30258509299404568401799145468436421_f64; 371 } 372 373 #[lang = "f64"] 374 #[cfg(not(test))] 375 impl f64 { 376 /// The radix or base of the internal representation of `f64`. 377 #[stable(feature = "assoc_int_consts", since = "1.43.0")] 378 pub const RADIX: u32 = 2; 379 380 /// Number of significant digits in base 2. 381 #[stable(feature = "assoc_int_consts", since = "1.43.0")] 382 pub const MANTISSA_DIGITS: u32 = 53; 383 /// Approximate number of significant digits in base 10. 384 #[stable(feature = "assoc_int_consts", since = "1.43.0")] 385 pub const DIGITS: u32 = 15; 386 387 /// [Machine epsilon] value for `f64`. 388 /// 389 /// This is the difference between `1.0` and the next larger representable number. 390 /// 391 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon 392 #[stable(feature = "assoc_int_consts", since = "1.43.0")] 393 pub const EPSILON: f64 = 2.2204460492503131e-16_f64; 394 395 /// Smallest finite `f64` value. 396 #[stable(feature = "assoc_int_consts", since = "1.43.0")] 397 pub const MIN: f64 = -1.7976931348623157e+308_f64; 398 /// Smallest positive normal `f64` value. 399 #[stable(feature = "assoc_int_consts", since = "1.43.0")] 400 pub const MIN_POSITIVE: f64 = 2.2250738585072014e-308_f64; 401 /// Largest finite `f64` value. 402 #[stable(feature = "assoc_int_consts", since = "1.43.0")] 403 pub const MAX: f64 = 1.7976931348623157e+308_f64; 404 405 /// One greater than the minimum possible normal power of 2 exponent. 406 #[stable(feature = "assoc_int_consts", since = "1.43.0")] 407 pub const MIN_EXP: i32 = -1021; 408 /// Maximum possible power of 2 exponent. 409 #[stable(feature = "assoc_int_consts", since = "1.43.0")] 410 pub const MAX_EXP: i32 = 1024; 411 412 /// Minimum possible normal power of 10 exponent. 413 #[stable(feature = "assoc_int_consts", since = "1.43.0")] 414 pub const MIN_10_EXP: i32 = -307; 415 /// Maximum possible power of 10 exponent. 416 #[stable(feature = "assoc_int_consts", since = "1.43.0")] 417 pub const MAX_10_EXP: i32 = 308; 418 419 /// Not a Number (NaN). 420 #[stable(feature = "assoc_int_consts", since = "1.43.0")] 421 pub const NAN: f64 = 0.0_f64 / 0.0_f64; 422 /// Infinity (∞). 423 #[stable(feature = "assoc_int_consts", since = "1.43.0")] 424 pub const INFINITY: f64 = 1.0_f64 / 0.0_f64; 425 /// Negative infinity (−∞). 426 #[stable(feature = "assoc_int_consts", since = "1.43.0")] 427 pub const NEG_INFINITY: f64 = -1.0_f64 / 0.0_f64; 428 429 /// Returns `true` if this value is `NaN`. 430 /// 431 /// ``` 432 /// let nan = f64::NAN; 433 /// let f = 7.0_f64; 434 /// 435 /// assert!(nan.is_nan()); 436 /// assert!(!f.is_nan()); 437 /// ``` 438 #[must_use] 439 #[stable(feature = "rust1", since = "1.0.0")] 440 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] 441 #[inline] is_nan(self) -> bool442 pub const fn is_nan(self) -> bool { 443 self != self 444 } 445 446 // FIXME(#50145): `abs` is publicly unavailable in libcore due to 447 // concerns about portability, so this implementation is for 448 // private use internally. 449 #[inline] 450 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] abs_private(self) -> f64451 pub(crate) const fn abs_private(self) -> f64 { 452 f64::from_bits(self.to_bits() & 0x7fff_ffff_ffff_ffff) 453 } 454 455 /// Returns `true` if this value is positive infinity or negative infinity, and 456 /// `false` otherwise. 457 /// 458 /// ``` 459 /// let f = 7.0f64; 460 /// let inf = f64::INFINITY; 461 /// let neg_inf = f64::NEG_INFINITY; 462 /// let nan = f64::NAN; 463 /// 464 /// assert!(!f.is_infinite()); 465 /// assert!(!nan.is_infinite()); 466 /// 467 /// assert!(inf.is_infinite()); 468 /// assert!(neg_inf.is_infinite()); 469 /// ``` 470 #[must_use] 471 #[stable(feature = "rust1", since = "1.0.0")] 472 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] 473 #[inline] is_infinite(self) -> bool474 pub const fn is_infinite(self) -> bool { 475 self.abs_private() == Self::INFINITY 476 } 477 478 /// Returns `true` if this number is neither infinite nor `NaN`. 479 /// 480 /// ``` 481 /// let f = 7.0f64; 482 /// let inf: f64 = f64::INFINITY; 483 /// let neg_inf: f64 = f64::NEG_INFINITY; 484 /// let nan: f64 = f64::NAN; 485 /// 486 /// assert!(f.is_finite()); 487 /// 488 /// assert!(!nan.is_finite()); 489 /// assert!(!inf.is_finite()); 490 /// assert!(!neg_inf.is_finite()); 491 /// ``` 492 #[must_use] 493 #[stable(feature = "rust1", since = "1.0.0")] 494 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] 495 #[inline] is_finite(self) -> bool496 pub const fn is_finite(self) -> bool { 497 // There's no need to handle NaN separately: if self is NaN, 498 // the comparison is not true, exactly as desired. 499 self.abs_private() < Self::INFINITY 500 } 501 502 /// Returns `true` if the number is [subnormal]. 503 /// 504 /// ``` 505 /// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308_f64 506 /// let max = f64::MAX; 507 /// let lower_than_min = 1.0e-308_f64; 508 /// let zero = 0.0_f64; 509 /// 510 /// assert!(!min.is_subnormal()); 511 /// assert!(!max.is_subnormal()); 512 /// 513 /// assert!(!zero.is_subnormal()); 514 /// assert!(!f64::NAN.is_subnormal()); 515 /// assert!(!f64::INFINITY.is_subnormal()); 516 /// // Values between `0` and `min` are Subnormal. 517 /// assert!(lower_than_min.is_subnormal()); 518 /// ``` 519 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number 520 #[must_use] 521 #[stable(feature = "is_subnormal", since = "1.53.0")] 522 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] 523 #[inline] is_subnormal(self) -> bool524 pub const fn is_subnormal(self) -> bool { 525 matches!(self.classify(), FpCategory::Subnormal) 526 } 527 528 /// Returns `true` if the number is neither zero, infinite, 529 /// [subnormal], or `NaN`. 530 /// 531 /// ``` 532 /// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308f64 533 /// let max = f64::MAX; 534 /// let lower_than_min = 1.0e-308_f64; 535 /// let zero = 0.0f64; 536 /// 537 /// assert!(min.is_normal()); 538 /// assert!(max.is_normal()); 539 /// 540 /// assert!(!zero.is_normal()); 541 /// assert!(!f64::NAN.is_normal()); 542 /// assert!(!f64::INFINITY.is_normal()); 543 /// // Values between `0` and `min` are Subnormal. 544 /// assert!(!lower_than_min.is_normal()); 545 /// ``` 546 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number 547 #[must_use] 548 #[stable(feature = "rust1", since = "1.0.0")] 549 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] 550 #[inline] is_normal(self) -> bool551 pub const fn is_normal(self) -> bool { 552 matches!(self.classify(), FpCategory::Normal) 553 } 554 555 /// Returns the floating point category of the number. If only one property 556 /// is going to be tested, it is generally faster to use the specific 557 /// predicate instead. 558 /// 559 /// ``` 560 /// use std::num::FpCategory; 561 /// 562 /// let num = 12.4_f64; 563 /// let inf = f64::INFINITY; 564 /// 565 /// assert_eq!(num.classify(), FpCategory::Normal); 566 /// assert_eq!(inf.classify(), FpCategory::Infinite); 567 /// ``` 568 #[stable(feature = "rust1", since = "1.0.0")] 569 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] classify(self) -> FpCategory570 pub const fn classify(self) -> FpCategory { 571 const EXP_MASK: u64 = 0x7ff0000000000000; 572 const MAN_MASK: u64 = 0x000fffffffffffff; 573 574 let bits = self.to_bits(); 575 match (bits & MAN_MASK, bits & EXP_MASK) { 576 (0, 0) => FpCategory::Zero, 577 (_, 0) => FpCategory::Subnormal, 578 (0, EXP_MASK) => FpCategory::Infinite, 579 (_, EXP_MASK) => FpCategory::Nan, 580 _ => FpCategory::Normal, 581 } 582 } 583 584 /// Returns `true` if `self` has a positive sign, including `+0.0`, `NaN`s with 585 /// positive sign bit and positive infinity. 586 /// 587 /// ``` 588 /// let f = 7.0_f64; 589 /// let g = -7.0_f64; 590 /// 591 /// assert!(f.is_sign_positive()); 592 /// assert!(!g.is_sign_positive()); 593 /// ``` 594 #[must_use] 595 #[stable(feature = "rust1", since = "1.0.0")] 596 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] 597 #[inline] is_sign_positive(self) -> bool598 pub const fn is_sign_positive(self) -> bool { 599 !self.is_sign_negative() 600 } 601 602 #[must_use] 603 #[stable(feature = "rust1", since = "1.0.0")] 604 #[rustc_deprecated(since = "1.0.0", reason = "renamed to is_sign_positive")] 605 #[inline] 606 #[doc(hidden)] is_positive(self) -> bool607 pub fn is_positive(self) -> bool { 608 self.is_sign_positive() 609 } 610 611 /// Returns `true` if `self` has a negative sign, including `-0.0`, `NaN`s with 612 /// negative sign bit and negative infinity. 613 /// 614 /// ``` 615 /// let f = 7.0_f64; 616 /// let g = -7.0_f64; 617 /// 618 /// assert!(!f.is_sign_negative()); 619 /// assert!(g.is_sign_negative()); 620 /// ``` 621 #[must_use] 622 #[stable(feature = "rust1", since = "1.0.0")] 623 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] 624 #[inline] is_sign_negative(self) -> bool625 pub const fn is_sign_negative(self) -> bool { 626 self.to_bits() & 0x8000_0000_0000_0000 != 0 627 } 628 629 #[must_use] 630 #[stable(feature = "rust1", since = "1.0.0")] 631 #[rustc_deprecated(since = "1.0.0", reason = "renamed to is_sign_negative")] 632 #[inline] 633 #[doc(hidden)] is_negative(self) -> bool634 pub fn is_negative(self) -> bool { 635 self.is_sign_negative() 636 } 637 638 /// Takes the reciprocal (inverse) of a number, `1/x`. 639 /// 640 /// ``` 641 /// let x = 2.0_f64; 642 /// let abs_difference = (x.recip() - (1.0 / x)).abs(); 643 /// 644 /// assert!(abs_difference < 1e-10); 645 /// ``` 646 #[stable(feature = "rust1", since = "1.0.0")] 647 #[inline] recip(self) -> f64648 pub fn recip(self) -> f64 { 649 1.0 / self 650 } 651 652 /// Converts radians to degrees. 653 /// 654 /// ``` 655 /// let angle = std::f64::consts::PI; 656 /// 657 /// let abs_difference = (angle.to_degrees() - 180.0).abs(); 658 /// 659 /// assert!(abs_difference < 1e-10); 660 /// ``` 661 #[must_use = "this returns the result of the operation, \ 662 without modifying the original"] 663 #[stable(feature = "rust1", since = "1.0.0")] 664 #[inline] to_degrees(self) -> f64665 pub fn to_degrees(self) -> f64 { 666 // The division here is correctly rounded with respect to the true 667 // value of 180/π. (This differs from f32, where a constant must be 668 // used to ensure a correctly rounded result.) 669 self * (180.0f64 / consts::PI) 670 } 671 672 /// Converts degrees to radians. 673 /// 674 /// ``` 675 /// let angle = 180.0_f64; 676 /// 677 /// let abs_difference = (angle.to_radians() - std::f64::consts::PI).abs(); 678 /// 679 /// assert!(abs_difference < 1e-10); 680 /// ``` 681 #[must_use = "this returns the result of the operation, \ 682 without modifying the original"] 683 #[stable(feature = "rust1", since = "1.0.0")] 684 #[inline] to_radians(self) -> f64685 pub fn to_radians(self) -> f64 { 686 let value: f64 = consts::PI; 687 self * (value / 180.0) 688 } 689 690 /// Returns the maximum of the two numbers. 691 /// 692 /// Follows the IEEE-754 2008 semantics for maxNum, except for handling of signaling NaNs. 693 /// This matches the behavior of libm’s fmin. 694 /// 695 /// ``` 696 /// let x = 1.0_f64; 697 /// let y = 2.0_f64; 698 /// 699 /// assert_eq!(x.max(y), y); 700 /// ``` 701 /// 702 /// If one of the arguments is NaN, then the other argument is returned. 703 #[stable(feature = "rust1", since = "1.0.0")] 704 #[inline] max(self, other: f64) -> f64705 pub fn max(self, other: f64) -> f64 { 706 intrinsics::maxnumf64(self, other) 707 } 708 709 /// Returns the minimum of the two numbers. 710 /// 711 /// Follows the IEEE-754 2008 semantics for minNum, except for handling of signaling NaNs. 712 /// This matches the behavior of libm’s fmin. 713 /// 714 /// ``` 715 /// let x = 1.0_f64; 716 /// let y = 2.0_f64; 717 /// 718 /// assert_eq!(x.min(y), x); 719 /// ``` 720 /// 721 /// If one of the arguments is NaN, then the other argument is returned. 722 #[stable(feature = "rust1", since = "1.0.0")] 723 #[inline] min(self, other: f64) -> f64724 pub fn min(self, other: f64) -> f64 { 725 intrinsics::minnumf64(self, other) 726 } 727 728 /// Returns the maximum of the two numbers, propagating NaNs. 729 /// 730 /// This returns NaN when *either* argument is NaN, as opposed to 731 /// [`f64::max`] which only returns NaN when *both* arguments are NaN. 732 /// 733 /// ``` 734 /// #![feature(float_minimum_maximum)] 735 /// let x = 1.0_f64; 736 /// let y = 2.0_f64; 737 /// 738 /// assert_eq!(x.maximum(y), y); 739 /// assert!(x.maximum(f64::NAN).is_nan()); 740 /// ``` 741 /// 742 /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the greater 743 /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0. 744 /// Note that this follows the semantics specified in IEEE 754-2019. 745 #[unstable(feature = "float_minimum_maximum", issue = "91079")] 746 #[inline] maximum(self, other: f64) -> f64747 pub fn maximum(self, other: f64) -> f64 { 748 if self > other { 749 self 750 } else if other > self { 751 other 752 } else if self == other { 753 if self.is_sign_positive() && other.is_sign_negative() { self } else { other } 754 } else { 755 self + other 756 } 757 } 758 759 /// Returns the minimum of the two numbers, propagating NaNs. 760 /// 761 /// This returns NaN when *either* argument is NaN, as opposed to 762 /// [`f64::min`] which only returns NaN when *both* arguments are NaN. 763 /// 764 /// ``` 765 /// #![feature(float_minimum_maximum)] 766 /// let x = 1.0_f64; 767 /// let y = 2.0_f64; 768 /// 769 /// assert_eq!(x.minimum(y), x); 770 /// assert!(x.minimum(f64::NAN).is_nan()); 771 /// ``` 772 /// 773 /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the lesser 774 /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0. 775 /// Note that this follows the semantics specified in IEEE 754-2019. 776 #[unstable(feature = "float_minimum_maximum", issue = "91079")] 777 #[inline] minimum(self, other: f64) -> f64778 pub fn minimum(self, other: f64) -> f64 { 779 if self < other { 780 self 781 } else if other < self { 782 other 783 } else if self == other { 784 if self.is_sign_negative() && other.is_sign_positive() { self } else { other } 785 } else { 786 self + other 787 } 788 } 789 790 /// Rounds toward zero and converts to any primitive integer type, 791 /// assuming that the value is finite and fits in that type. 792 /// 793 /// ``` 794 /// let value = 4.6_f64; 795 /// let rounded = unsafe { value.to_int_unchecked::<u16>() }; 796 /// assert_eq!(rounded, 4); 797 /// 798 /// let value = -128.9_f64; 799 /// let rounded = unsafe { value.to_int_unchecked::<i8>() }; 800 /// assert_eq!(rounded, i8::MIN); 801 /// ``` 802 /// 803 /// # Safety 804 /// 805 /// The value must: 806 /// 807 /// * Not be `NaN` 808 /// * Not be infinite 809 /// * Be representable in the return type `Int`, after truncating off its fractional part 810 #[must_use = "this returns the result of the operation, \ 811 without modifying the original"] 812 #[stable(feature = "float_approx_unchecked_to", since = "1.44.0")] 813 #[inline] to_int_unchecked<Int>(self) -> Int where Self: FloatToInt<Int>,814 pub unsafe fn to_int_unchecked<Int>(self) -> Int 815 where 816 Self: FloatToInt<Int>, 817 { 818 // SAFETY: the caller must uphold the safety contract for 819 // `FloatToInt::to_int_unchecked`. 820 unsafe { FloatToInt::<Int>::to_int_unchecked(self) } 821 } 822 823 /// Raw transmutation to `u64`. 824 /// 825 /// This is currently identical to `transmute::<f64, u64>(self)` on all platforms. 826 /// 827 /// See [`from_bits`](Self::from_bits) for some discussion of the 828 /// portability of this operation (there are almost no issues). 829 /// 830 /// Note that this function is distinct from `as` casting, which attempts to 831 /// preserve the *numeric* value, and not the bitwise value. 832 /// 833 /// # Examples 834 /// 835 /// ``` 836 /// assert!((1f64).to_bits() != 1f64 as u64); // to_bits() is not casting! 837 /// assert_eq!((12.5f64).to_bits(), 0x4029000000000000); 838 /// 839 /// ``` 840 #[must_use = "this returns the result of the operation, \ 841 without modifying the original"] 842 #[stable(feature = "float_bits_conv", since = "1.20.0")] 843 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")] 844 #[inline] to_bits(self) -> u64845 pub const fn to_bits(self) -> u64 { 846 // SAFETY: `u64` is a plain old datatype so we can always transmute to it 847 unsafe { mem::transmute(self) } 848 } 849 850 /// Raw transmutation from `u64`. 851 /// 852 /// This is currently identical to `transmute::<u64, f64>(v)` on all platforms. 853 /// It turns out this is incredibly portable, for two reasons: 854 /// 855 /// * Floats and Ints have the same endianness on all supported platforms. 856 /// * IEEE-754 very precisely specifies the bit layout of floats. 857 /// 858 /// However there is one caveat: prior to the 2008 version of IEEE-754, how 859 /// to interpret the NaN signaling bit wasn't actually specified. Most platforms 860 /// (notably x86 and ARM) picked the interpretation that was ultimately 861 /// standardized in 2008, but some didn't (notably MIPS). As a result, all 862 /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa. 863 /// 864 /// Rather than trying to preserve signaling-ness cross-platform, this 865 /// implementation favors preserving the exact bits. This means that 866 /// any payloads encoded in NaNs will be preserved even if the result of 867 /// this method is sent over the network from an x86 machine to a MIPS one. 868 /// 869 /// If the results of this method are only manipulated by the same 870 /// architecture that produced them, then there is no portability concern. 871 /// 872 /// If the input isn't NaN, then there is no portability concern. 873 /// 874 /// If you don't care about signaling-ness (very likely), then there is no 875 /// portability concern. 876 /// 877 /// Note that this function is distinct from `as` casting, which attempts to 878 /// preserve the *numeric* value, and not the bitwise value. 879 /// 880 /// # Examples 881 /// 882 /// ``` 883 /// let v = f64::from_bits(0x4029000000000000); 884 /// assert_eq!(v, 12.5); 885 /// ``` 886 #[stable(feature = "float_bits_conv", since = "1.20.0")] 887 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")] 888 #[must_use] 889 #[inline] from_bits(v: u64) -> Self890 pub const fn from_bits(v: u64) -> Self { 891 // SAFETY: `u64` is a plain old datatype so we can always transmute from it 892 // It turns out the safety issues with sNaN were overblown! Hooray! 893 unsafe { mem::transmute(v) } 894 } 895 896 /// Return the memory representation of this floating point number as a byte array in 897 /// big-endian (network) byte order. 898 /// 899 /// # Examples 900 /// 901 /// ``` 902 /// let bytes = 12.5f64.to_be_bytes(); 903 /// assert_eq!(bytes, [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); 904 /// ``` 905 #[must_use = "this returns the result of the operation, \ 906 without modifying the original"] 907 #[stable(feature = "float_to_from_bytes", since = "1.40.0")] 908 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")] 909 #[inline] to_be_bytes(self) -> [u8; 8]910 pub const fn to_be_bytes(self) -> [u8; 8] { 911 self.to_bits().to_be_bytes() 912 } 913 914 /// Return the memory representation of this floating point number as a byte array in 915 /// little-endian byte order. 916 /// 917 /// # Examples 918 /// 919 /// ``` 920 /// let bytes = 12.5f64.to_le_bytes(); 921 /// assert_eq!(bytes, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]); 922 /// ``` 923 #[must_use = "this returns the result of the operation, \ 924 without modifying the original"] 925 #[stable(feature = "float_to_from_bytes", since = "1.40.0")] 926 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")] 927 #[inline] to_le_bytes(self) -> [u8; 8]928 pub const fn to_le_bytes(self) -> [u8; 8] { 929 self.to_bits().to_le_bytes() 930 } 931 932 /// Return the memory representation of this floating point number as a byte array in 933 /// native byte order. 934 /// 935 /// As the target platform's native endianness is used, portable code 936 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead. 937 /// 938 /// [`to_be_bytes`]: f64::to_be_bytes 939 /// [`to_le_bytes`]: f64::to_le_bytes 940 /// 941 /// # Examples 942 /// 943 /// ``` 944 /// let bytes = 12.5f64.to_ne_bytes(); 945 /// assert_eq!( 946 /// bytes, 947 /// if cfg!(target_endian = "big") { 948 /// [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] 949 /// } else { 950 /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40] 951 /// } 952 /// ); 953 /// ``` 954 #[must_use = "this returns the result of the operation, \ 955 without modifying the original"] 956 #[stable(feature = "float_to_from_bytes", since = "1.40.0")] 957 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")] 958 #[inline] to_ne_bytes(self) -> [u8; 8]959 pub const fn to_ne_bytes(self) -> [u8; 8] { 960 self.to_bits().to_ne_bytes() 961 } 962 963 /// Create a floating point value from its representation as a byte array in big endian. 964 /// 965 /// # Examples 966 /// 967 /// ``` 968 /// let value = f64::from_be_bytes([0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); 969 /// assert_eq!(value, 12.5); 970 /// ``` 971 #[stable(feature = "float_to_from_bytes", since = "1.40.0")] 972 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")] 973 #[must_use] 974 #[inline] from_be_bytes(bytes: [u8; 8]) -> Self975 pub const fn from_be_bytes(bytes: [u8; 8]) -> Self { 976 Self::from_bits(u64::from_be_bytes(bytes)) 977 } 978 979 /// Create a floating point value from its representation as a byte array in little endian. 980 /// 981 /// # Examples 982 /// 983 /// ``` 984 /// let value = f64::from_le_bytes([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]); 985 /// assert_eq!(value, 12.5); 986 /// ``` 987 #[stable(feature = "float_to_from_bytes", since = "1.40.0")] 988 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")] 989 #[must_use] 990 #[inline] from_le_bytes(bytes: [u8; 8]) -> Self991 pub const fn from_le_bytes(bytes: [u8; 8]) -> Self { 992 Self::from_bits(u64::from_le_bytes(bytes)) 993 } 994 995 /// Create a floating point value from its representation as a byte array in native endian. 996 /// 997 /// As the target platform's native endianness is used, portable code 998 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as 999 /// appropriate instead. 1000 /// 1001 /// [`from_be_bytes`]: f64::from_be_bytes 1002 /// [`from_le_bytes`]: f64::from_le_bytes 1003 /// 1004 /// # Examples 1005 /// 1006 /// ``` 1007 /// let value = f64::from_ne_bytes(if cfg!(target_endian = "big") { 1008 /// [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] 1009 /// } else { 1010 /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40] 1011 /// }); 1012 /// assert_eq!(value, 12.5); 1013 /// ``` 1014 #[stable(feature = "float_to_from_bytes", since = "1.40.0")] 1015 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")] 1016 #[must_use] 1017 #[inline] from_ne_bytes(bytes: [u8; 8]) -> Self1018 pub const fn from_ne_bytes(bytes: [u8; 8]) -> Self { 1019 Self::from_bits(u64::from_ne_bytes(bytes)) 1020 } 1021 1022 /// Returns an ordering between self and other values. 1023 /// Unlike the standard partial comparison between floating point numbers, 1024 /// this comparison always produces an ordering in accordance to 1025 /// the totalOrder predicate as defined in IEEE 754 (2008 revision) 1026 /// floating point standard. The values are ordered in following order: 1027 /// - Negative quiet NaN 1028 /// - Negative signaling NaN 1029 /// - Negative infinity 1030 /// - Negative numbers 1031 /// - Negative subnormal numbers 1032 /// - Negative zero 1033 /// - Positive zero 1034 /// - Positive subnormal numbers 1035 /// - Positive numbers 1036 /// - Positive infinity 1037 /// - Positive signaling NaN 1038 /// - Positive quiet NaN 1039 /// 1040 /// Note that this function does not always agree with the [`PartialOrd`] 1041 /// and [`PartialEq`] implementations of `f64`. In particular, they regard 1042 /// negative and positive zero as equal, while `total_cmp` doesn't. 1043 /// 1044 /// # Example 1045 /// ``` 1046 /// #![feature(total_cmp)] 1047 /// struct GoodBoy { 1048 /// name: String, 1049 /// weight: f64, 1050 /// } 1051 /// 1052 /// let mut bois = vec![ 1053 /// GoodBoy { name: "Pucci".to_owned(), weight: 0.1 }, 1054 /// GoodBoy { name: "Woofer".to_owned(), weight: 99.0 }, 1055 /// GoodBoy { name: "Yapper".to_owned(), weight: 10.0 }, 1056 /// GoodBoy { name: "Chonk".to_owned(), weight: f64::INFINITY }, 1057 /// GoodBoy { name: "Abs. Unit".to_owned(), weight: f64::NAN }, 1058 /// GoodBoy { name: "Floaty".to_owned(), weight: -5.0 }, 1059 /// ]; 1060 /// 1061 /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight)); 1062 /// # assert!(bois.into_iter().map(|b| b.weight) 1063 /// # .zip([-5.0, 0.1, 10.0, 99.0, f64::INFINITY, f64::NAN].iter()) 1064 /// # .all(|(a, b)| a.to_bits() == b.to_bits())) 1065 /// ``` 1066 #[unstable(feature = "total_cmp", issue = "72599")] 1067 #[must_use] 1068 #[inline] total_cmp(&self, other: &Self) -> crate::cmp::Ordering1069 pub fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering { 1070 let mut left = self.to_bits() as i64; 1071 let mut right = other.to_bits() as i64; 1072 1073 // In case of negatives, flip all the bits except the sign 1074 // to achieve a similar layout as two's complement integers 1075 // 1076 // Why does this work? IEEE 754 floats consist of three fields: 1077 // Sign bit, exponent and mantissa. The set of exponent and mantissa 1078 // fields as a whole have the property that their bitwise order is 1079 // equal to the numeric magnitude where the magnitude is defined. 1080 // The magnitude is not normally defined on NaN values, but 1081 // IEEE 754 totalOrder defines the NaN values also to follow the 1082 // bitwise order. This leads to order explained in the doc comment. 1083 // However, the representation of magnitude is the same for negative 1084 // and positive numbers – only the sign bit is different. 1085 // To easily compare the floats as signed integers, we need to 1086 // flip the exponent and mantissa bits in case of negative numbers. 1087 // We effectively convert the numbers to "two's complement" form. 1088 // 1089 // To do the flipping, we construct a mask and XOR against it. 1090 // We branchlessly calculate an "all-ones except for the sign bit" 1091 // mask from negative-signed values: right shifting sign-extends 1092 // the integer, so we "fill" the mask with sign bits, and then 1093 // convert to unsigned to push one more zero bit. 1094 // On positive values, the mask is all zeros, so it's a no-op. 1095 left ^= (((left >> 63) as u64) >> 1) as i64; 1096 right ^= (((right >> 63) as u64) >> 1) as i64; 1097 1098 left.cmp(&right) 1099 } 1100 1101 /// Restrict a value to a certain interval unless it is NaN. 1102 /// 1103 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is 1104 /// less than `min`. Otherwise this returns `self`. 1105 /// 1106 /// Note that this function returns NaN if the initial value was NaN as 1107 /// well. 1108 /// 1109 /// # Panics 1110 /// 1111 /// Panics if `min > max`, `min` is NaN, or `max` is NaN. 1112 /// 1113 /// # Examples 1114 /// 1115 /// ``` 1116 /// assert!((-3.0f64).clamp(-2.0, 1.0) == -2.0); 1117 /// assert!((0.0f64).clamp(-2.0, 1.0) == 0.0); 1118 /// assert!((2.0f64).clamp(-2.0, 1.0) == 1.0); 1119 /// assert!((f64::NAN).clamp(-2.0, 1.0).is_nan()); 1120 /// ``` 1121 #[must_use = "method returns a new number and does not mutate the original value"] 1122 #[stable(feature = "clamp", since = "1.50.0")] 1123 #[inline] clamp(self, min: f64, max: f64) -> f641124 pub fn clamp(self, min: f64, max: f64) -> f64 { 1125 assert!(min <= max); 1126 let mut x = self; 1127 if x < min { 1128 x = min; 1129 } 1130 if x > max { 1131 x = max; 1132 } 1133 x 1134 } 1135 } 1136