library/core/src/num/f64.rs
This is Rust standard-library source from the compiler version used in the run.
1 //! Constants for 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 module8 //! (as distinct from those defined in the `consts` sub-module),9 //! new code should instead use the associated constants10 //! defined directly on the `f64` type.11 12 #![stable(feature = "rust1", since = "1.0.0")]13 14 use crate::convert::FloatToInt;15 use crate::num::FpCategory;16 use crate::panic::const_assert;17 use crate::{intrinsics, mem};18 19 /// The radix or base of the internal representation of `f64`.20 /// Use [`f64::RADIX`] instead.21 ///22 /// # Examples23 ///24 /// ```rust25 /// // deprecated way26 /// # #[allow(deprecated, deprecated_in_future)]27 /// let r = std::f64::RADIX;28 ///29 /// // intended way30 /// let r = f64::RADIX;31 /// ```32 #[stable(feature = "rust1", since = "1.0.0")]33 #[deprecated(since = "TBD", note = "replaced by the `RADIX` associated constant on `f64`")]34 #[rustc_diagnostic_item = "f64_legacy_const_radix"]35 pub const RADIX: u32 = f64::RADIX;36 37 /// Number of significant digits in base 2.38 /// Use [`f64::MANTISSA_DIGITS`] instead.39 ///40 /// # Examples41 ///42 /// ```rust43 /// // deprecated way44 /// # #[allow(deprecated, deprecated_in_future)]45 /// let d = std::f64::MANTISSA_DIGITS;46 ///47 /// // intended way48 /// let d = f64::MANTISSA_DIGITS;49 /// ```50 #[stable(feature = "rust1", since = "1.0.0")]51 #[deprecated(52 since = "TBD",53 note = "replaced by the `MANTISSA_DIGITS` associated constant on `f64`"54 )]55 #[rustc_diagnostic_item = "f64_legacy_const_mantissa_dig"]56 pub const MANTISSA_DIGITS: u32 = f64::MANTISSA_DIGITS;57 58 /// Approximate number of significant digits in base 10.59 /// Use [`f64::DIGITS`] instead.60 ///61 /// # Examples62 ///63 /// ```rust64 /// // deprecated way65 /// # #[allow(deprecated, deprecated_in_future)]66 /// let d = std::f64::DIGITS;67 ///68 /// // intended way69 /// let d = f64::DIGITS;70 /// ```71 #[stable(feature = "rust1", since = "1.0.0")]72 #[deprecated(since = "TBD", note = "replaced by the `DIGITS` associated constant on `f64`")]73 #[rustc_diagnostic_item = "f64_legacy_const_digits"]74 pub const DIGITS: u32 = f64::DIGITS;75 76 /// [Machine epsilon] value for `f64`.77 /// Use [`f64::EPSILON`] instead.78 ///79 /// This is the difference between `1.0` and the next larger representable number.80 ///81 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon82 ///83 /// # Examples84 ///85 /// ```rust86 /// // deprecated way87 /// # #[allow(deprecated, deprecated_in_future)]88 /// let e = std::f64::EPSILON;89 ///90 /// // intended way91 /// let e = f64::EPSILON;92 /// ```93 #[stable(feature = "rust1", since = "1.0.0")]94 #[deprecated(since = "TBD", note = "replaced by the `EPSILON` associated constant on `f64`")]95 #[rustc_diagnostic_item = "f64_legacy_const_epsilon"]96 pub const EPSILON: f64 = f64::EPSILON;97 98 /// Smallest finite `f64` value.99 /// Use [`f64::MIN`] instead.100 ///101 /// # Examples102 ///103 /// ```rust104 /// // deprecated way105 /// # #[allow(deprecated, deprecated_in_future)]106 /// let min = std::f64::MIN;107 ///108 /// // intended way109 /// let min = f64::MIN;110 /// ```111 #[stable(feature = "rust1", since = "1.0.0")]112 #[deprecated(since = "TBD", note = "replaced by the `MIN` associated constant on `f64`")]113 #[rustc_diagnostic_item = "f64_legacy_const_min"]114 pub const MIN: f64 = f64::MIN;115 116 /// Smallest positive normal `f64` value.117 /// Use [`f64::MIN_POSITIVE`] instead.118 ///119 /// # Examples120 ///121 /// ```rust122 /// // deprecated way123 /// # #[allow(deprecated, deprecated_in_future)]124 /// let min = std::f64::MIN_POSITIVE;125 ///126 /// // intended way127 /// let min = f64::MIN_POSITIVE;128 /// ```129 #[stable(feature = "rust1", since = "1.0.0")]130 #[deprecated(since = "TBD", note = "replaced by the `MIN_POSITIVE` associated constant on `f64`")]131 #[rustc_diagnostic_item = "f64_legacy_const_min_positive"]132 pub const MIN_POSITIVE: f64 = f64::MIN_POSITIVE;133 134 /// Largest finite `f64` value.135 /// Use [`f64::MAX`] instead.136 ///137 /// # Examples138 ///139 /// ```rust140 /// // deprecated way141 /// # #[allow(deprecated, deprecated_in_future)]142 /// let max = std::f64::MAX;143 ///144 /// // intended way145 /// let max = f64::MAX;146 /// ```147 #[stable(feature = "rust1", since = "1.0.0")]148 #[deprecated(since = "TBD", note = "replaced by the `MAX` associated constant on `f64`")]149 #[rustc_diagnostic_item = "f64_legacy_const_max"]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 /// # Examples156 ///157 /// ```rust158 /// // deprecated way159 /// # #[allow(deprecated, deprecated_in_future)]160 /// let min = std::f64::MIN_EXP;161 ///162 /// // intended way163 /// let min = f64::MIN_EXP;164 /// ```165 #[stable(feature = "rust1", since = "1.0.0")]166 #[deprecated(since = "TBD", note = "replaced by the `MIN_EXP` associated constant on `f64`")]167 #[rustc_diagnostic_item = "f64_legacy_const_min_exp"]168 pub const MIN_EXP: i32 = f64::MIN_EXP;169 170 /// Maximum possible power of 2 exponent.171 /// Use [`f64::MAX_EXP`] instead.172 ///173 /// # Examples174 ///175 /// ```rust176 /// // deprecated way177 /// # #[allow(deprecated, deprecated_in_future)]178 /// let max = std::f64::MAX_EXP;179 ///180 /// // intended way181 /// let max = f64::MAX_EXP;182 /// ```183 #[stable(feature = "rust1", since = "1.0.0")]184 #[deprecated(since = "TBD", note = "replaced by the `MAX_EXP` associated constant on `f64`")]185 #[rustc_diagnostic_item = "f64_legacy_const_max_exp"]186 pub const MAX_EXP: i32 = f64::MAX_EXP;187 188 /// Minimum possible normal power of 10 exponent.189 /// Use [`f64::MIN_10_EXP`] instead.190 ///191 /// # Examples192 ///193 /// ```rust194 /// // deprecated way195 /// # #[allow(deprecated, deprecated_in_future)]196 /// let min = std::f64::MIN_10_EXP;197 ///198 /// // intended way199 /// let min = f64::MIN_10_EXP;200 /// ```201 #[stable(feature = "rust1", since = "1.0.0")]202 #[deprecated(since = "TBD", note = "replaced by the `MIN_10_EXP` associated constant on `f64`")]203 #[rustc_diagnostic_item = "f64_legacy_const_min_10_exp"]204 pub const MIN_10_EXP: i32 = f64::MIN_10_EXP;205 206 /// Maximum possible power of 10 exponent.207 /// Use [`f64::MAX_10_EXP`] instead.208 ///209 /// # Examples210 ///211 /// ```rust212 /// // deprecated way213 /// # #[allow(deprecated, deprecated_in_future)]214 /// let max = std::f64::MAX_10_EXP;215 ///216 /// // intended way217 /// let max = f64::MAX_10_EXP;218 /// ```219 #[stable(feature = "rust1", since = "1.0.0")]220 #[deprecated(since = "TBD", note = "replaced by the `MAX_10_EXP` associated constant on `f64`")]221 #[rustc_diagnostic_item = "f64_legacy_const_max_10_exp"]222 pub const MAX_10_EXP: i32 = f64::MAX_10_EXP;223 224 /// Not a Number (NaN).225 /// Use [`f64::NAN`] instead.226 ///227 /// # Examples228 ///229 /// ```rust230 /// // deprecated way231 /// # #[allow(deprecated, deprecated_in_future)]232 /// let nan = std::f64::NAN;233 ///234 /// // intended way235 /// let nan = f64::NAN;236 /// ```237 #[stable(feature = "rust1", since = "1.0.0")]238 #[deprecated(since = "TBD", note = "replaced by the `NAN` associated constant on `f64`")]239 #[rustc_diagnostic_item = "f64_legacy_const_nan"]240 pub const NAN: f64 = f64::NAN;241 242 /// Infinity (∞).243 /// Use [`f64::INFINITY`] instead.244 ///245 /// # Examples246 ///247 /// ```rust248 /// // deprecated way249 /// # #[allow(deprecated, deprecated_in_future)]250 /// let inf = std::f64::INFINITY;251 ///252 /// // intended way253 /// let inf = f64::INFINITY;254 /// ```255 #[stable(feature = "rust1", since = "1.0.0")]256 #[deprecated(since = "TBD", note = "replaced by the `INFINITY` associated constant on `f64`")]257 #[rustc_diagnostic_item = "f64_legacy_const_infinity"]258 pub const INFINITY: f64 = f64::INFINITY;259 260 /// Negative infinity (−∞).261 /// Use [`f64::NEG_INFINITY`] instead.262 ///263 /// # Examples264 ///265 /// ```rust266 /// // deprecated way267 /// # #[allow(deprecated, deprecated_in_future)]268 /// let ninf = std::f64::NEG_INFINITY;269 ///270 /// // intended way271 /// let ninf = f64::NEG_INFINITY;272 /// ```273 #[stable(feature = "rust1", since = "1.0.0")]274 #[deprecated(since = "TBD", note = "replaced by the `NEG_INFINITY` associated constant on `f64`")]275 #[rustc_diagnostic_item = "f64_legacy_const_neg_infinity"]276 pub const NEG_INFINITY: f64 = f64::NEG_INFINITY;277 278 /// Basic mathematical constants.279 #[stable(feature = "rust1", since = "1.0.0")]280 #[rustc_diagnostic_item = "f64_consts_mod"]281 pub mod consts {282 // FIXME: replace with mathematical constants from cmath.283 284 /// Archimedes' constant (π)285 #[stable(feature = "rust1", since = "1.0.0")]286 pub const PI: f64 = 3.14159265358979323846264338327950288_f64;287 288 /// The full circle constant (τ)289 ///290 /// Equal to 2π.291 #[stable(feature = "tau_constant", since = "1.47.0")]292 pub const TAU: f64 = 6.28318530717958647692528676655900577_f64;293 294 /// The golden ratio (φ)295 #[doc(alias = "phi")]296 #[stable(feature = "euler_gamma_golden_ratio", since = "1.94.0")]297 pub const GOLDEN_RATIO: f64 = 1.618033988749894848204586834365638118_f64;298 299 /// The Euler-Mascheroni constant (γ)300 #[stable(feature = "euler_gamma_golden_ratio", since = "1.94.0")]301 pub const EULER_GAMMA: f64 = 0.577215664901532860606512090082402431_f64;302 303 /// π/2304 #[stable(feature = "rust1", since = "1.0.0")]305 pub const FRAC_PI_2: f64 = 1.57079632679489661923132169163975144_f64;306 307 /// π/3308 #[stable(feature = "rust1", since = "1.0.0")]309 pub const FRAC_PI_3: f64 = 1.04719755119659774615421446109316763_f64;310 311 /// π/4312 #[stable(feature = "rust1", since = "1.0.0")]313 pub const FRAC_PI_4: f64 = 0.785398163397448309615660845819875721_f64;314 315 /// π/6316 #[stable(feature = "rust1", since = "1.0.0")]317 pub const FRAC_PI_6: f64 = 0.52359877559829887307710723054658381_f64;318 319 /// π/8320 #[stable(feature = "rust1", since = "1.0.0")]321 pub const FRAC_PI_8: f64 = 0.39269908169872415480783042290993786_f64;322 323 /// 1/π324 #[stable(feature = "rust1", since = "1.0.0")]325 pub const FRAC_1_PI: f64 = 0.318309886183790671537767526745028724_f64;326 327 /// 1/sqrt(π)328 #[unstable(feature = "more_float_constants", issue = "146939")]329 pub const FRAC_1_SQRT_PI: f64 = 0.564189583547756286948079451560772586_f64;330 331 /// 1/sqrt(2π)332 #[doc(alias = "FRAC_1_SQRT_TAU")]333 #[unstable(feature = "more_float_constants", issue = "146939")]334 pub const FRAC_1_SQRT_2PI: f64 = 0.398942280401432677939946059934381868_f64;335 336 /// 2/π337 #[stable(feature = "rust1", since = "1.0.0")]338 pub const FRAC_2_PI: f64 = 0.636619772367581343075535053490057448_f64;339 340 /// 2/sqrt(π)341 #[stable(feature = "rust1", since = "1.0.0")]342 pub const FRAC_2_SQRT_PI: f64 = 1.12837916709551257389615890312154517_f64;343 344 /// sqrt(2)345 #[stable(feature = "rust1", since = "1.0.0")]346 pub const SQRT_2: f64 = 1.41421356237309504880168872420969808_f64;347 348 /// 1/sqrt(2)349 #[stable(feature = "rust1", since = "1.0.0")]350 pub const FRAC_1_SQRT_2: f64 = 0.707106781186547524400844362104849039_f64;351 352 /// sqrt(3)353 #[unstable(feature = "more_float_constants", issue = "146939")]354 pub const SQRT_3: f64 = 1.732050807568877293527446341505872367_f64;355 356 /// 1/sqrt(3)357 #[unstable(feature = "more_float_constants", issue = "146939")]358 pub const FRAC_1_SQRT_3: f64 = 0.577350269189625764509148780501957456_f64;359 360 /// sqrt(5)361 #[unstable(feature = "more_float_constants", issue = "146939")]362 pub const SQRT_5: f64 = 2.23606797749978969640917366873127623_f64;363 364 /// 1/sqrt(5)365 #[unstable(feature = "more_float_constants", issue = "146939")]366 pub const FRAC_1_SQRT_5: f64 = 0.44721359549995793928183473374625524_f64;367 368 /// Euler's number (e)369 #[stable(feature = "rust1", since = "1.0.0")]370 pub const E: f64 = 2.71828182845904523536028747135266250_f64;371 372 /// log<sub>2</sub>(10)373 #[stable(feature = "extra_log_consts", since = "1.43.0")]374 pub const LOG2_10: f64 = 3.32192809488736234787031942948939018_f64;375 376 /// log<sub>2</sub>(e)377 #[stable(feature = "rust1", since = "1.0.0")]378 pub const LOG2_E: f64 = 1.44269504088896340735992468100189214_f64;379 380 /// log<sub>10</sub>(2)381 #[stable(feature = "extra_log_consts", since = "1.43.0")]382 pub const LOG10_2: f64 = 0.301029995663981195213738894724493027_f64;383 384 /// log<sub>10</sub>(e)385 #[stable(feature = "rust1", since = "1.0.0")]386 pub const LOG10_E: f64 = 0.434294481903251827651128918916605082_f64;387 388 /// ln(2)389 #[stable(feature = "rust1", since = "1.0.0")]390 pub const LN_2: f64 = 0.693147180559945309417232121458176568_f64;391 392 /// ln(10)393 #[stable(feature = "rust1", since = "1.0.0")]394 pub const LN_10: f64 = 2.30258509299404568401799145468436421_f64;395 }396 397 #[doc(test(attr(allow(unused_features))))]398 impl f64 {399 /// The radix or base of the internal representation of `f64`.400 #[stable(feature = "assoc_int_consts", since = "1.43.0")]401 pub const RADIX: u32 = 2;402 403 /// The size of this float type in bits.404 #[unstable(feature = "float_bits_const", issue = "151073")]405 pub const BITS: u32 = 64;406 407 /// Number of significant digits in base 2.408 ///409 /// Note that the size of the mantissa in the bitwise representation is one410 /// smaller than this since the leading 1 is not stored explicitly.411 #[stable(feature = "assoc_int_consts", since = "1.43.0")]412 pub const MANTISSA_DIGITS: u32 = 53;413 /// Approximate number of significant digits in base 10.414 ///415 /// This is the maximum <i>x</i> such that any decimal number with <i>x</i>416 /// significant digits can be converted to `f64` and back without loss.417 ///418 /// Equal to floor(log<sub>10</sub> 2<sup>[`MANTISSA_DIGITS`] − 1</sup>).419 ///420 /// [`MANTISSA_DIGITS`]: f64::MANTISSA_DIGITS421 #[stable(feature = "assoc_int_consts", since = "1.43.0")]422 pub const DIGITS: u32 = 15;423 424 /// [Machine epsilon] value for `f64`.425 ///426 /// This is the difference between `1.0` and the next larger representable number.427 ///428 /// Equal to 2<sup>1 − [`MANTISSA_DIGITS`]</sup>.429 ///430 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon431 /// [`MANTISSA_DIGITS`]: f64::MANTISSA_DIGITS432 #[stable(feature = "assoc_int_consts", since = "1.43.0")]433 #[rustc_diagnostic_item = "f64_epsilon"]434 pub const EPSILON: f64 = 2.2204460492503131e-16_f64;435 436 /// Smallest finite `f64` value.437 ///438 /// Equal to −[`MAX`].439 ///440 /// [`MAX`]: f64::MAX441 #[stable(feature = "assoc_int_consts", since = "1.43.0")]442 pub const MIN: f64 = -1.7976931348623157e+308_f64;443 /// Smallest positive normal `f64` value.444 ///445 /// Equal to 2<sup>[`MIN_EXP`] − 1</sup>.446 ///447 /// [`MIN_EXP`]: f64::MIN_EXP448 #[stable(feature = "assoc_int_consts", since = "1.43.0")]449 pub const MIN_POSITIVE: f64 = 2.2250738585072014e-308_f64;450 /// Largest finite `f64` value.451 ///452 /// Equal to453 /// (1 − 2<sup>−[`MANTISSA_DIGITS`]</sup>) 2<sup>[`MAX_EXP`]</sup>.454 ///455 /// [`MANTISSA_DIGITS`]: f64::MANTISSA_DIGITS456 /// [`MAX_EXP`]: f64::MAX_EXP457 #[stable(feature = "assoc_int_consts", since = "1.43.0")]458 pub const MAX: f64 = 1.7976931348623157e+308_f64;459 460 /// One greater than the minimum possible *normal* power of 2 exponent461 /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).462 ///463 /// This corresponds to the exact minimum possible *normal* power of 2 exponent464 /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).465 /// In other words, all normal numbers representable by this type are466 /// greater than or equal to 0.5 × 2<sup><i>MIN_EXP</i></sup>.467 #[stable(feature = "assoc_int_consts", since = "1.43.0")]468 pub const MIN_EXP: i32 = -1021;469 /// One greater than the maximum possible power of 2 exponent470 /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).471 ///472 /// This corresponds to the exact maximum possible power of 2 exponent473 /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).474 /// In other words, all numbers representable by this type are475 /// strictly less than 2<sup><i>MAX_EXP</i></sup>.476 #[stable(feature = "assoc_int_consts", since = "1.43.0")]477 pub const MAX_EXP: i32 = 1024;478 479 /// Minimum <i>x</i> for which 10<sup><i>x</i></sup> is normal.480 ///481 /// Equal to ceil(log<sub>10</sub> [`MIN_POSITIVE`]).482 ///483 /// [`MIN_POSITIVE`]: f64::MIN_POSITIVE484 #[stable(feature = "assoc_int_consts", since = "1.43.0")]485 pub const MIN_10_EXP: i32 = -307;486 /// Maximum <i>x</i> for which 10<sup><i>x</i></sup> is normal.487 ///488 /// Equal to floor(log<sub>10</sub> [`MAX`]).489 ///490 /// [`MAX`]: f64::MAX491 #[stable(feature = "assoc_int_consts", since = "1.43.0")]492 pub const MAX_10_EXP: i32 = 308;493 494 /// Not a Number (NaN).495 ///496 /// Note that IEEE 754 doesn't define just a single NaN value; a plethora of bit patterns are497 /// considered to be NaN. Furthermore, the standard makes a difference between a "signaling" and498 /// a "quiet" NaN, and allows inspecting its "payload" (the unspecified bits in the bit pattern)499 /// and its sign. See the [specification of NaN bit patterns](f32#nan-bit-patterns) for more500 /// info.501 ///502 /// This constant is guaranteed to be a quiet NaN (on targets that follow the Rust assumptions503 /// that the quiet/signaling bit being set to 1 indicates a quiet NaN). Beyond that, nothing is504 /// guaranteed about the specific bit pattern chosen here: both payload and sign are arbitrary.505 /// The concrete bit pattern may change across Rust versions and target platforms.506 #[rustc_diagnostic_item = "f64_nan"]507 #[stable(feature = "assoc_int_consts", since = "1.43.0")]508 #[allow(clippy::eq_op)]509 pub const NAN: f64 = 0.0_f64 / 0.0_f64;510 /// Infinity (∞).511 #[stable(feature = "assoc_int_consts", since = "1.43.0")]512 pub const INFINITY: f64 = 1.0_f64 / 0.0_f64;513 /// Negative infinity (−∞).514 #[stable(feature = "assoc_int_consts", since = "1.43.0")]515 pub const NEG_INFINITY: f64 = -1.0_f64 / 0.0_f64;516 517 /// Maximum integer that can be represented exactly in an [`f64`] value,518 /// with no other integer converting to the same floating point value.519 ///520 /// For an integer `x` which satisfies `MIN_EXACT_INTEGER <= x <= MAX_EXACT_INTEGER`,521 /// there is a "one-to-one" mapping between [`i64`] and [`f64`] values.522 /// `MAX_EXACT_INTEGER + 1` also converts losslessly to [`f64`] and back to523 /// [`i64`], but `MAX_EXACT_INTEGER + 2` converts to the same [`f64`] value524 /// (and back to `MAX_EXACT_INTEGER + 1` as an integer) so there is not a525 /// "one-to-one" mapping.526 ///527 /// [`MAX_EXACT_INTEGER`]: f64::MAX_EXACT_INTEGER528 /// [`MIN_EXACT_INTEGER`]: f64::MIN_EXACT_INTEGER529 /// ```530 /// #![feature(float_exact_integer_constants)]531 /// # // FIXME(#152635): Float rounding on `i586` does not adhere to IEEE 754532 /// # #[cfg(not(all(target_arch = "x86", not(target_feature = "sse"))))] {533 /// let max_exact_int = f64::MAX_EXACT_INTEGER;534 /// assert_eq!(max_exact_int, max_exact_int as f64 as i64);535 /// assert_eq!(max_exact_int + 1, (max_exact_int + 1) as f64 as i64);536 /// assert_ne!(max_exact_int + 2, (max_exact_int + 2) as f64 as i64);537 ///538 /// // Beyond `f64::MAX_EXACT_INTEGER`, multiple integers can map to one float value539 /// assert_eq!((max_exact_int + 1) as f64, (max_exact_int + 2) as f64);540 /// # }541 /// ```542 #[unstable(feature = "float_exact_integer_constants", issue = "152466")]543 pub const MAX_EXACT_INTEGER: i64 = (1 << Self::MANTISSA_DIGITS) - 1;544 545 /// Minimum integer that can be represented exactly in an [`f64`] value,546 /// with no other integer converting to the same floating point value.547 ///548 /// For an integer `x` which satisfies `MIN_EXACT_INTEGER <= x <= MAX_EXACT_INTEGER`,549 /// there is a "one-to-one" mapping between [`i64`] and [`f64`] values.550 /// `MAX_EXACT_INTEGER + 1` also converts losslessly to [`f64`] and back to551 /// [`i64`], but `MAX_EXACT_INTEGER + 2` converts to the same [`f64`] value552 /// (and back to `MAX_EXACT_INTEGER + 1` as an integer) so there is not a553 /// "one-to-one" mapping.554 ///555 /// This constant is equivalent to `-MAX_EXACT_INTEGER`.556 ///557 /// [`MAX_EXACT_INTEGER`]: f64::MAX_EXACT_INTEGER558 /// [`MIN_EXACT_INTEGER`]: f64::MIN_EXACT_INTEGER559 /// ```560 /// #![feature(float_exact_integer_constants)]561 /// # // FIXME(#152635): Float rounding on `i586` does not adhere to IEEE 754562 /// # #[cfg(not(all(target_arch = "x86", not(target_feature = "sse"))))] {563 /// let min_exact_int = f64::MIN_EXACT_INTEGER;564 /// assert_eq!(min_exact_int, min_exact_int as f64 as i64);565 /// assert_eq!(min_exact_int - 1, (min_exact_int - 1) as f64 as i64);566 /// assert_ne!(min_exact_int - 2, (min_exact_int - 2) as f64 as i64);567 ///568 /// // Below `f64::MIN_EXACT_INTEGER`, multiple integers can map to one float value569 /// assert_eq!((min_exact_int - 1) as f64, (min_exact_int - 2) as f64);570 /// # }571 /// ```572 #[unstable(feature = "float_exact_integer_constants", issue = "152466")]573 pub const MIN_EXACT_INTEGER: i64 = -Self::MAX_EXACT_INTEGER;574 575 /// The mask of the bit used to encode the sign of an [`f64`].576 ///577 /// This bit is set when the sign is negative and unset when the sign is578 /// positive.579 /// If you only need to check whether a value is positive or negative,580 /// [`is_sign_positive`] or [`is_sign_negative`] can be used.581 ///582 /// [`is_sign_positive`]: f64::is_sign_positive583 /// [`is_sign_negative`]: f64::is_sign_negative584 /// ```rust585 /// #![feature(float_masks)]586 /// let sign_mask = f64::SIGN_MASK;587 /// let a = 1.6552f64;588 /// let a_bits = a.to_bits();589 ///590 /// assert_eq!(a_bits & sign_mask, 0x0);591 /// assert_eq!(f64::from_bits(a_bits ^ sign_mask), -a);592 /// assert_eq!(sign_mask, (-0.0f64).to_bits());593 /// ```594 #[unstable(feature = "float_masks", issue = "154064")]595 pub const SIGN_MASK: u64 = 0x8000_0000_0000_0000;596 597 /// The mask of the bits used to encode the exponent of an [`f64`].598 ///599 /// Note that the exponent is stored as a biased value, with a bias of 1024 for `f64`.600 ///601 /// ```rust602 /// #![feature(float_masks)]603 /// fn get_exp(a: f64) -> i64 {604 /// let bias = 1023;605 /// let biased = a.to_bits() & f64::EXPONENT_MASK;606 /// (biased >> (f64::MANTISSA_DIGITS - 1)).cast_signed() - bias607 /// }608 ///609 /// assert_eq!(get_exp(0.5), -1);610 /// assert_eq!(get_exp(1.0), 0);611 /// assert_eq!(get_exp(2.0), 1);612 /// assert_eq!(get_exp(4.0), 2);613 /// ```614 #[unstable(feature = "float_masks", issue = "154064")]615 pub const EXPONENT_MASK: u64 = 0x7ff0_0000_0000_0000;616 617 /// The mask of the bits used to encode the mantissa of an [`f64`].618 ///619 /// ```rust620 /// #![feature(float_masks)]621 /// let mantissa_mask = f64::MANTISSA_MASK;622 ///623 /// assert_eq!(0f64.to_bits() & mantissa_mask, 0x0);624 /// assert_eq!(1f64.to_bits() & mantissa_mask, 0x0);625 ///626 /// // multiplying a finite value by a power of 2 doesn't change its mantissa627 /// // unless the result or initial value is not normal.628 /// let a = 1.6552f64;629 /// let b = 4.0 * a;630 /// assert_eq!(a.to_bits() & mantissa_mask, b.to_bits() & mantissa_mask);631 ///632 /// // The maximum and minimum values have a saturated significand633 /// assert_eq!(f64::MAX.to_bits() & f64::MANTISSA_MASK, f64::MANTISSA_MASK);634 /// assert_eq!(f64::MIN.to_bits() & f64::MANTISSA_MASK, f64::MANTISSA_MASK);635 /// ```636 #[unstable(feature = "float_masks", issue = "154064")]637 pub const MANTISSA_MASK: u64 = 0x000f_ffff_ffff_ffff;638 639 /// Minimum representable positive value (min subnormal)640 const TINY_BITS: u64 = 0x1;641 642 /// Minimum representable negative value (min negative subnormal)643 const NEG_TINY_BITS: u64 = Self::TINY_BITS | Self::SIGN_MASK;644 645 /// Returns `true` if this value is NaN.646 ///647 /// ```648 /// let nan = f64::NAN;649 /// let f = 7.0_f64;650 ///651 /// assert!(nan.is_nan());652 /// assert!(!f.is_nan());653 /// ```654 #[must_use]655 #[stable(feature = "rust1", since = "1.0.0")]656 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]657 #[inline]658 #[allow(clippy::eq_op)] // > if you intended to check if the operand is NaN, use `.is_nan()` instead :)659 pub const fn is_nan(self) -> bool {660 self != self661 }662 663 /// Returns `true` if this value is positive infinity or negative infinity, and664 /// `false` otherwise.665 ///666 /// ```667 /// let f = 7.0f64;668 /// let inf = f64::INFINITY;669 /// let neg_inf = f64::NEG_INFINITY;670 /// let nan = f64::NAN;671 ///672 /// assert!(!f.is_infinite());673 /// assert!(!nan.is_infinite());674 ///675 /// assert!(inf.is_infinite());676 /// assert!(neg_inf.is_infinite());677 /// ```678 #[must_use]679 #[stable(feature = "rust1", since = "1.0.0")]680 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]681 #[inline]682 pub const fn is_infinite(self) -> bool {683 // Getting clever with transmutation can result in incorrect answers on some FPUs684 // FIXME: alter the Rust <-> Rust calling convention to prevent this problem.685 // See https://github.com/rust-lang/rust/issues/72327686 (self == f64::INFINITY) | (self == f64::NEG_INFINITY)687 }688 689 /// Returns `true` if this number is neither infinite nor NaN.690 ///691 /// ```692 /// let f = 7.0f64;693 /// let inf: f64 = f64::INFINITY;694 /// let neg_inf: f64 = f64::NEG_INFINITY;695 /// let nan: f64 = f64::NAN;696 ///697 /// assert!(f.is_finite());698 ///699 /// assert!(!nan.is_finite());700 /// assert!(!inf.is_finite());701 /// assert!(!neg_inf.is_finite());702 /// ```703 #[must_use]704 #[stable(feature = "rust1", since = "1.0.0")]705 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]706 #[inline]707 pub const fn is_finite(self) -> bool {708 // There's no need to handle NaN separately: if self is NaN,709 // the comparison is not true, exactly as desired.710 self.abs() < Self::INFINITY711 }712 713 /// Returns `true` if the number is [subnormal].714 ///715 /// ```716 /// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308_f64717 /// let max = f64::MAX;718 /// let lower_than_min = 1.0e-308_f64;719 /// let zero = 0.0_f64;720 ///721 /// assert!(!min.is_subnormal());722 /// assert!(!max.is_subnormal());723 ///724 /// assert!(!zero.is_subnormal());725 /// assert!(!f64::NAN.is_subnormal());726 /// assert!(!f64::INFINITY.is_subnormal());727 /// // Values between `0` and `min` are Subnormal.728 /// assert!(lower_than_min.is_subnormal());729 /// ```730 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number731 #[must_use]732 #[stable(feature = "is_subnormal", since = "1.53.0")]733 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]734 #[inline]735 pub const fn is_subnormal(self) -> bool {736 matches!(self.classify(), FpCategory::Subnormal)737 }738 739 /// Returns `true` if the number is neither zero, infinite,740 /// [subnormal], or NaN.741 ///742 /// ```743 /// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308f64744 /// let max = f64::MAX;745 /// let lower_than_min = 1.0e-308_f64;746 /// let zero = 0.0f64;747 ///748 /// assert!(min.is_normal());749 /// assert!(max.is_normal());750 ///751 /// assert!(!zero.is_normal());752 /// assert!(!f64::NAN.is_normal());753 /// assert!(!f64::INFINITY.is_normal());754 /// // Values between `0` and `min` are Subnormal.755 /// assert!(!lower_than_min.is_normal());756 /// ```757 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number758 #[must_use]759 #[stable(feature = "rust1", since = "1.0.0")]760 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]761 #[inline]762 pub const fn is_normal(self) -> bool {763 matches!(self.classify(), FpCategory::Normal)764 }765 766 /// Returns the floating point category of the number. If only one property767 /// is going to be tested, it is generally faster to use the specific768 /// predicate instead.769 ///770 /// ```771 /// use std::num::FpCategory;772 ///773 /// let num = 12.4_f64;774 /// let inf = f64::INFINITY;775 ///776 /// assert_eq!(num.classify(), FpCategory::Normal);777 /// assert_eq!(inf.classify(), FpCategory::Infinite);778 /// ```779 #[stable(feature = "rust1", since = "1.0.0")]780 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]781 #[must_use]782 pub const fn classify(self) -> FpCategory {783 // We used to have complicated logic here that avoids the simple bit-based tests to work784 // around buggy codegen for x87 targets (see785 // https://github.com/rust-lang/rust/issues/114479). However, some LLVM versions later, none786 // of our tests is able to find any difference between the complicated and the naive787 // version, so now we are back to the naive version.788 let b = self.to_bits();789 match (b & Self::MANTISSA_MASK, b & Self::EXPONENT_MASK) {790 (0, Self::EXPONENT_MASK) => FpCategory::Infinite,791 (_, Self::EXPONENT_MASK) => FpCategory::Nan,792 (0, 0) => FpCategory::Zero,793 (_, 0) => FpCategory::Subnormal,794 _ => FpCategory::Normal,795 }796 }797 798 /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with799 /// positive sign bit and positive infinity.800 ///801 /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of802 /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are803 /// conserved over arithmetic operations, the result of `is_sign_positive` on804 /// a NaN might produce an unexpected or non-portable result. See the [specification805 /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == 1.0`806 /// if you need fully portable behavior (will return `false` for all NaNs).807 ///808 /// ```809 /// let f = 7.0_f64;810 /// let g = -7.0_f64;811 ///812 /// assert!(f.is_sign_positive());813 /// assert!(!g.is_sign_positive());814 /// ```815 #[must_use]816 #[stable(feature = "rust1", since = "1.0.0")]817 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]818 #[inline]819 pub const fn is_sign_positive(self) -> bool {820 !self.is_sign_negative()821 }822 823 /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with824 /// negative sign bit and negative infinity.825 ///826 /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of827 /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are828 /// conserved over arithmetic operations, the result of `is_sign_negative` on829 /// a NaN might produce an unexpected or non-portable result. See the [specification830 /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == -1.0`831 /// if you need fully portable behavior (will return `false` for all NaNs).832 ///833 /// ```834 /// let f = 7.0_f64;835 /// let g = -7.0_f64;836 ///837 /// assert!(!f.is_sign_negative());838 /// assert!(g.is_sign_negative());839 /// ```840 #[must_use]841 #[stable(feature = "rust1", since = "1.0.0")]842 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]843 #[inline]844 pub const fn is_sign_negative(self) -> bool {845 // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus846 // applies to zeros and NaNs as well.847 self.to_bits() & Self::SIGN_MASK != 0848 }849 850 /// Returns the least number greater than `self`.851 ///852 /// Let `TINY` be the smallest representable positive `f64`. Then,853 /// - if `self.is_nan()`, this returns `self`;854 /// - if `self` is [`NEG_INFINITY`], this returns [`MIN`];855 /// - if `self` is `-TINY`, this returns -0.0;856 /// - if `self` is -0.0 or +0.0, this returns `TINY`;857 /// - if `self` is [`MAX`] or [`INFINITY`], this returns [`INFINITY`];858 /// - otherwise the unique least value greater than `self` is returned.859 ///860 /// The identity `x.next_up() == -(-x).next_down()` holds for all non-NaN `x`. When `x`861 /// is finite `x == x.next_up().next_down()` also holds.862 ///863 /// ```rust864 /// // f64::EPSILON is the difference between 1.0 and the next number up.865 /// assert_eq!(1.0f64.next_up(), 1.0 + f64::EPSILON);866 /// // But not for most numbers.867 /// assert!(0.1f64.next_up() < 0.1 + f64::EPSILON);868 /// assert_eq!(9007199254740992f64.next_up(), 9007199254740994.0);869 /// ```870 ///871 /// This operation corresponds to IEEE-754 `nextUp`.872 ///873 /// [`NEG_INFINITY`]: Self::NEG_INFINITY874 /// [`INFINITY`]: Self::INFINITY875 /// [`MIN`]: Self::MIN876 /// [`MAX`]: Self::MAX877 #[inline]878 #[doc(alias = "nextUp")]879 #[stable(feature = "float_next_up_down", since = "1.86.0")]880 #[rustc_const_stable(feature = "float_next_up_down", since = "1.86.0")]881 #[must_use = "method returns a new number and does not mutate the original value"]882 pub const fn next_up(self) -> Self {883 // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing884 // denormals to zero. This is in general unsound and unsupported, but here885 // we do our best to still produce the correct result on such targets.886 let bits = self.to_bits();887 if self.is_nan() || bits == Self::INFINITY.to_bits() {888 return self;889 }890 891 let abs = bits & !Self::SIGN_MASK;892 let next_bits = if abs == 0 {893 Self::TINY_BITS894 } else if bits == abs {895 bits + 1896 } else {897 bits - 1898 };899 Self::from_bits(next_bits)900 }901 902 /// Returns the greatest number less than `self`.903 ///904 /// Let `TINY` be the smallest representable positive `f64`. Then,905 /// - if `self.is_nan()`, this returns `self`;906 /// - if `self` is [`INFINITY`], this returns [`MAX`];907 /// - if `self` is `TINY`, this returns 0.0;908 /// - if `self` is -0.0 or +0.0, this returns `-TINY`;909 /// - if `self` is [`MIN`] or [`NEG_INFINITY`], this returns [`NEG_INFINITY`];910 /// - otherwise the unique greatest value less than `self` is returned.911 ///912 /// The identity `x.next_down() == -(-x).next_up()` holds for all non-NaN `x`. When `x`913 /// is finite `x == x.next_down().next_up()` also holds.914 ///915 /// ```rust916 /// let x = 1.0f64;917 /// // Clamp value into range [0, 1).918 /// let clamped = x.clamp(0.0, 1.0f64.next_down());919 /// assert!(clamped < 1.0);920 /// assert_eq!(clamped.next_up(), 1.0);921 /// ```922 ///923 /// This operation corresponds to IEEE-754 `nextDown`.924 ///925 /// [`NEG_INFINITY`]: Self::NEG_INFINITY926 /// [`INFINITY`]: Self::INFINITY927 /// [`MIN`]: Self::MIN928 /// [`MAX`]: Self::MAX929 #[inline]930 #[doc(alias = "nextDown")]931 #[stable(feature = "float_next_up_down", since = "1.86.0")]932 #[rustc_const_stable(feature = "float_next_up_down", since = "1.86.0")]933 #[must_use = "method returns a new number and does not mutate the original value"]934 pub const fn next_down(self) -> Self {935 // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing936 // denormals to zero. This is in general unsound and unsupported, but here937 // we do our best to still produce the correct result on such targets.938 let bits = self.to_bits();939 if self.is_nan() || bits == Self::NEG_INFINITY.to_bits() {940 return self;941 }942 943 let abs = bits & !Self::SIGN_MASK;944 let next_bits = if abs == 0 {945 Self::NEG_TINY_BITS946 } else if bits == abs {947 bits - 1948 } else {949 bits + 1950 };951 Self::from_bits(next_bits)952 }953 954 /// Takes the reciprocal (inverse) of a number, `1/x`.955 ///956 /// ```957 /// let x = 2.0_f64;958 /// let abs_difference = (x.recip() - (1.0 / x)).abs();959 ///960 /// assert!(abs_difference < 1e-10);961 /// ```962 #[must_use = "this returns the result of the operation, without modifying the original"]963 #[stable(feature = "rust1", since = "1.0.0")]964 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]965 #[inline]966 pub const fn recip(self) -> f64 {967 1.0 / self968 }969 970 /// Converts radians to degrees.971 ///972 /// # Unspecified precision973 ///974 /// The precision of this function is non-deterministic. This means it varies by platform,975 /// Rust version, and can even differ within the same execution from one invocation to the next.976 ///977 /// # Examples978 ///979 /// ```980 /// let angle = std::f64::consts::PI;981 ///982 /// let abs_difference = (angle.to_degrees() - 180.0).abs();983 ///984 /// assert!(abs_difference < 1e-10);985 /// ```986 #[must_use = "this returns the result of the operation, \987 without modifying the original"]988 #[stable(feature = "rust1", since = "1.0.0")]989 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]990 #[inline]991 pub const fn to_degrees(self) -> f64 {992 // The division here is correctly rounded with respect to the true value of 180/π.993 // Although π is irrational and already rounded, the double rounding happens994 // to produce correct result for f64.995 const PIS_IN_180: f64 = 180.0 / consts::PI;996 self * PIS_IN_180997 }998 999 /// Converts degrees to radians.1000 ///1001 /// # Unspecified precision1002 ///1003 /// The precision of this function is non-deterministic. This means it varies by platform,1004 /// Rust version, and can even differ within the same execution from one invocation to the next.1005 ///1006 /// # Examples1007 ///1008 /// ```1009 /// let angle = 180.0_f64;1010 ///1011 /// let abs_difference = (angle.to_radians() - std::f64::consts::PI).abs();1012 ///1013 /// assert!(abs_difference < 1e-10);1014 /// ```1015 #[must_use = "this returns the result of the operation, \1016 without modifying the original"]1017 #[stable(feature = "rust1", since = "1.0.0")]1018 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]1019 #[inline]1020 pub const fn to_radians(self) -> f64 {1021 // The division here is correctly rounded with respect to the true value of π/180.1022 // Although π is irrational and already rounded, the double rounding happens1023 // to produce correct result for f64.1024 const RADS_PER_DEG: f64 = consts::PI / 180.0;1025 self * RADS_PER_DEG1026 }1027 1028 /// Returns the maximum of the two numbers, ignoring NaN.1029 ///1030 /// If exactly one of the arguments is NaN (quiet or signaling), then the other argument is1031 /// returned. If both arguments are NaN, the return value is NaN, with the bit pattern picked1032 /// using the usual [rules for arithmetic operations](f32#nan-bit-patterns). If the inputs1033 /// compare equal (such as for the case of `+0.0` and `-0.0`), either input may be returned1034 /// non-deterministically.1035 ///1036 /// The handling of NaNs follows the IEEE 754-2019 semantics for `maximumNumber`, treating all1037 /// NaNs the same way to ensure the operation is associative. The handling of signed zeros1038 /// follows the IEEE 754-2008 semantics for `maxNum`.1039 ///1040 /// ```1041 /// let x = 1.0_f64;1042 /// let y = 2.0_f64;1043 ///1044 /// assert_eq!(x.max(y), y);1045 /// assert_eq!(x.max(f64::NAN), x);1046 /// ```1047 #[must_use = "this returns the result of the comparison, without modifying either input"]1048 #[stable(feature = "rust1", since = "1.0.0")]1049 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]1050 #[inline]1051 pub const fn max(self, other: f64) -> f64 {1052 intrinsics::maximum_number_nsz_f64(self, other)1053 }1054 1055 /// Returns the minimum of the two numbers, ignoring NaN.1056 ///1057 /// If exactly one of the arguments is NaN (quiet or signaling), then the other argument is1058 /// returned. If both arguments are NaN, the return value is NaN, with the bit pattern picked1059 /// using the usual [rules for arithmetic operations](f32#nan-bit-patterns). If the inputs1060 /// compare equal (such as for the case of `+0.0` and `-0.0`), either input may be returned1061 /// non-deterministically.1062 ///1063 /// The handling of NaNs follows the IEEE 754-2019 semantics for `minimumNumber`, treating all1064 /// NaNs the same way to ensure the operation is associative. The handling of signed zeros1065 /// follows the IEEE 754-2008 semantics for `minNum`.1066 ///1067 /// ```1068 /// let x = 1.0_f64;1069 /// let y = 2.0_f64;1070 ///1071 /// assert_eq!(x.min(y), x);1072 /// assert_eq!(x.min(f64::NAN), x);1073 /// ```1074 #[must_use = "this returns the result of the comparison, without modifying either input"]1075 #[stable(feature = "rust1", since = "1.0.0")]1076 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]1077 #[inline]1078 pub const fn min(self, other: f64) -> f64 {1079 intrinsics::minimum_number_nsz_f64(self, other)1080 }1081 1082 /// Returns the maximum of the two numbers, propagating NaN.1083 ///1084 /// If at least one of the arguments is NaN, the return value is NaN, with the bit pattern1085 /// picked using the usual [rules for arithmetic operations](f32#nan-bit-patterns). Furthermore,1086 /// `-0.0` is considered to be less than `+0.0`, making this function fully deterministic for1087 /// non-NaN inputs.1088 ///1089 /// This is in contrast to [`f64::max`] which only returns NaN when *both* arguments are NaN,1090 /// and which does not reliably order `-0.0` and `+0.0`.1091 ///1092 /// This follows the IEEE 754-2019 semantics for `maximum`.1093 ///1094 /// ```1095 /// #![feature(float_minimum_maximum)]1096 /// let x = 1.0_f64;1097 /// let y = 2.0_f64;1098 ///1099 /// assert_eq!(x.maximum(y), y);1100 /// assert!(x.maximum(f64::NAN).is_nan());1101 /// ```1102 #[must_use = "this returns the result of the comparison, without modifying either input"]1103 #[unstable(feature = "float_minimum_maximum", issue = "91079")]1104 #[inline]1105 pub const fn maximum(self, other: f64) -> f64 {1106 intrinsics::maximumf64(self, other)1107 }1108 1109 /// Returns the minimum of the two numbers, propagating NaN.1110 ///1111 /// If at least one of the arguments is NaN, the return value is NaN, with the bit pattern1112 /// picked using the usual [rules for arithmetic operations](f32#nan-bit-patterns). Furthermore,1113 /// `-0.0` is considered to be less than `+0.0`, making this function fully deterministic for1114 /// non-NaN inputs.1115 ///1116 /// This is in contrast to [`f64::min`] which only returns NaN when *both* arguments are NaN,1117 /// and which does not reliably order `-0.0` and `+0.0`.1118 ///1119 /// This follows the IEEE 754-2019 semantics for `minimum`.1120 ///1121 /// ```1122 /// #![feature(float_minimum_maximum)]1123 /// let x = 1.0_f64;1124 /// let y = 2.0_f64;1125 ///1126 /// assert_eq!(x.minimum(y), x);1127 /// assert!(x.minimum(f64::NAN).is_nan());1128 /// ```1129 #[must_use = "this returns the result of the comparison, without modifying either input"]1130 #[unstable(feature = "float_minimum_maximum", issue = "91079")]1131 #[inline]1132 pub const fn minimum(self, other: f64) -> f64 {1133 intrinsics::minimumf64(self, other)1134 }1135 1136 /// Calculates the midpoint (average) between `self` and `rhs`.1137 ///1138 /// This returns NaN when *either* argument is NaN or if a combination of1139 /// +inf and -inf is provided as arguments.1140 ///1141 /// # Examples1142 ///1143 /// ```1144 /// assert_eq!(1f64.midpoint(4.0), 2.5);1145 /// assert_eq!((-5.5f64).midpoint(8.0), 1.25);1146 /// ```1147 #[inline]1148 #[doc(alias = "average")]1149 #[stable(feature = "num_midpoint", since = "1.85.0")]1150 #[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]1151 #[must_use = "this returns the result of the operation, \1152 without modifying the original"]1153 pub const fn midpoint(self, other: f64) -> f64 {1154 const HI: f64 = f64::MAX * 0.5;1155 1156 let (a, b) = (self, other);1157 let abs_a = a.abs();1158 let abs_b = b.abs();1159 1160 if abs_a <= HI && abs_b <= HI {1161 // Overflow is impossible1162 (a + b) * 0.51163 } else {1164 (a * 0.5) + (b * 0.5)1165 }1166 }1167 1168 /// Rounds toward zero and converts to any primitive integer type,1169 /// assuming that the value is finite and fits in that type.1170 ///1171 /// ```1172 /// let value = 4.6_f64;1173 /// let rounded = unsafe { value.to_int_unchecked::<u16>() };1174 /// assert_eq!(rounded, 4);1175 ///1176 /// let value = -128.9_f64;1177 /// let rounded = unsafe { value.to_int_unchecked::<i8>() };1178 /// assert_eq!(rounded, i8::MIN);1179 /// ```1180 ///1181 /// # Safety1182 ///1183 /// The value must:1184 ///1185 /// * Not be `NaN`1186 /// * Not be infinite1187 /// * Be representable in the return type `Int`, after truncating off its fractional part1188 #[must_use = "this returns the result of the operation, \1189 without modifying the original"]1190 #[stable(feature = "float_approx_unchecked_to", since = "1.44.0")]1191 #[inline]1192 pub unsafe fn to_int_unchecked<Int>(self) -> Int1193 where1194 Self: FloatToInt<Int>,1195 {1196 // SAFETY: the caller must uphold the safety contract for1197 // `FloatToInt::to_int_unchecked`.1198 unsafe { FloatToInt::<Int>::to_int_unchecked(self) }1199 }1200 1201 /// Raw transmutation to `u64`.1202 ///1203 /// This is currently identical to `transmute::<f64, u64>(self)` on all platforms.1204 ///1205 /// See [`from_bits`](Self::from_bits) for some discussion of the1206 /// portability of this operation (there are almost no issues).1207 ///1208 /// Note that this function is distinct from `as` casting, which attempts to1209 /// preserve the *numeric* value, and not the bitwise value.1210 ///1211 /// # Examples1212 ///1213 /// ```1214 /// assert!((1f64).to_bits() != 1f64 as u64); // to_bits() is not casting!1215 /// assert_eq!((12.5f64).to_bits(), 0x4029000000000000);1216 /// ```1217 #[must_use = "this returns the result of the operation, \1218 without modifying the original"]1219 #[stable(feature = "float_bits_conv", since = "1.20.0")]1220 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]1221 #[allow(unnecessary_transmutes)]1222 #[inline]1223 pub const fn to_bits(self) -> u64 {1224 // SAFETY: `u64` is a plain old datatype so we can always transmute to it.1225 unsafe { mem::transmute(self) }1226 }1227 1228 /// Raw transmutation from `u64`.1229 ///1230 /// This is currently identical to `transmute::<u64, f64>(v)` on all platforms.1231 /// It turns out this is incredibly portable, for two reasons:1232 ///1233 /// * Floats and Ints have the same endianness on all supported platforms.1234 /// * IEEE 754 very precisely specifies the bit layout of floats.1235 ///1236 /// However there is one caveat: prior to the 2008 version of IEEE 754, how1237 /// to interpret the NaN signaling bit wasn't actually specified. Most platforms1238 /// (notably x86 and ARM) picked the interpretation that was ultimately1239 /// standardized in 2008, but some didn't (notably MIPS). As a result, all1240 /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.1241 ///1242 /// Rather than trying to preserve signaling-ness cross-platform, this1243 /// implementation favors preserving the exact bits. This means that1244 /// any payloads encoded in NaNs will be preserved even if the result of1245 /// this method is sent over the network from an x86 machine to a MIPS one.1246 ///1247 /// If the results of this method are only manipulated by the same1248 /// architecture that produced them, then there is no portability concern.1249 ///1250 /// If the input isn't NaN, then there is no portability concern.1251 ///1252 /// If you don't care about signaling-ness (very likely), then there is no1253 /// portability concern.1254 ///1255 /// Note that this function is distinct from `as` casting, which attempts to1256 /// preserve the *numeric* value, and not the bitwise value.1257 ///1258 /// # Examples1259 ///1260 /// ```1261 /// let v = f64::from_bits(0x4029000000000000);1262 /// assert_eq!(v, 12.5);1263 /// ```1264 #[stable(feature = "float_bits_conv", since = "1.20.0")]1265 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]1266 #[must_use]1267 #[inline]1268 #[allow(unnecessary_transmutes)]1269 pub const fn from_bits(v: u64) -> Self {1270 // It turns out the safety issues with sNaN were overblown! Hooray!1271 // SAFETY: `u64` is a plain old datatype so we can always transmute from it.1272 unsafe { mem::transmute(v) }1273 }1274 1275 /// Returns the memory representation of this floating point number as a byte array in1276 /// big-endian (network) byte order.1277 ///1278 /// See [`from_bits`](Self::from_bits) for some discussion of the1279 /// portability of this operation (there are almost no issues).1280 ///1281 /// # Examples1282 ///1283 /// ```1284 /// let bytes = 12.5f64.to_be_bytes();1285 /// assert_eq!(bytes, [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);1286 /// ```1287 #[must_use = "this returns the result of the operation, \1288 without modifying the original"]1289 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]1290 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]1291 #[inline]1292 pub const fn to_be_bytes(self) -> [u8; 8] {1293 self.to_bits().to_be_bytes()1294 }1295 1296 /// Returns the memory representation of this floating point number as a byte array in1297 /// little-endian byte order.1298 ///1299 /// See [`from_bits`](Self::from_bits) for some discussion of the1300 /// portability of this operation (there are almost no issues).1301 ///1302 /// # Examples1303 ///1304 /// ```1305 /// let bytes = 12.5f64.to_le_bytes();1306 /// assert_eq!(bytes, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]);1307 /// ```1308 #[must_use = "this returns the result of the operation, \1309 without modifying the original"]1310 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]1311 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]1312 #[inline]1313 pub const fn to_le_bytes(self) -> [u8; 8] {1314 self.to_bits().to_le_bytes()1315 }1316 1317 /// Returns the memory representation of this floating point number as a byte array in1318 /// native byte order.1319 ///1320 /// As the target platform's native endianness is used, portable code1321 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.1322 ///1323 /// [`to_be_bytes`]: f64::to_be_bytes1324 /// [`to_le_bytes`]: f64::to_le_bytes1325 ///1326 /// See [`from_bits`](Self::from_bits) for some discussion of the1327 /// portability of this operation (there are almost no issues).1328 ///1329 /// # Examples1330 ///1331 /// ```1332 /// let bytes = 12.5f64.to_ne_bytes();1333 /// assert_eq!(1334 /// bytes,1335 /// if cfg!(target_endian = "big") {1336 /// [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]1337 /// } else {1338 /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]1339 /// }1340 /// );1341 /// ```1342 #[must_use = "this returns the result of the operation, \1343 without modifying the original"]1344 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]1345 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]1346 #[inline]1347 pub const fn to_ne_bytes(self) -> [u8; 8] {1348 self.to_bits().to_ne_bytes()1349 }1350 1351 /// Creates a floating point value from its representation as a byte array in big endian.1352 ///1353 /// See [`from_bits`](Self::from_bits) for some discussion of the1354 /// portability of this operation (there are almost no issues).1355 ///1356 /// # Examples1357 ///1358 /// ```1359 /// let value = f64::from_be_bytes([0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);1360 /// assert_eq!(value, 12.5);1361 /// ```1362 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]1363 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]1364 #[must_use]1365 #[inline]1366 pub const fn from_be_bytes(bytes: [u8; 8]) -> Self {1367 Self::from_bits(u64::from_be_bytes(bytes))1368 }1369 1370 /// Creates a floating point value from its representation as a byte array in little endian.1371 ///1372 /// See [`from_bits`](Self::from_bits) for some discussion of the1373 /// portability of this operation (there are almost no issues).1374 ///1375 /// # Examples1376 ///1377 /// ```1378 /// let value = f64::from_le_bytes([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]);1379 /// assert_eq!(value, 12.5);1380 /// ```1381 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]1382 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]1383 #[must_use]1384 #[inline]1385 pub const fn from_le_bytes(bytes: [u8; 8]) -> Self {1386 Self::from_bits(u64::from_le_bytes(bytes))1387 }1388 1389 /// Creates a floating point value from its representation as a byte array in native endian.1390 ///1391 /// As the target platform's native endianness is used, portable code1392 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as1393 /// appropriate instead.1394 ///1395 /// [`from_be_bytes`]: f64::from_be_bytes1396 /// [`from_le_bytes`]: f64::from_le_bytes1397 ///1398 /// See [`from_bits`](Self::from_bits) for some discussion of the1399 /// portability of this operation (there are almost no issues).1400 ///1401 /// # Examples1402 ///1403 /// ```1404 /// let value = f64::from_ne_bytes(if cfg!(target_endian = "big") {1405 /// [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]1406 /// } else {1407 /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]1408 /// });1409 /// assert_eq!(value, 12.5);1410 /// ```1411 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]1412 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]1413 #[must_use]1414 #[inline]1415 pub const fn from_ne_bytes(bytes: [u8; 8]) -> Self {1416 Self::from_bits(u64::from_ne_bytes(bytes))1417 }1418 1419 /// Returns the ordering between `self` and `other`.1420 ///1421 /// Unlike the standard partial comparison between floating point numbers,1422 /// this comparison always produces an ordering in accordance to1423 /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)1424 /// floating point standard. The values are ordered in the following sequence:1425 ///1426 /// - negative quiet NaN1427 /// - negative signaling NaN1428 /// - negative infinity1429 /// - negative numbers1430 /// - negative subnormal numbers1431 /// - negative zero1432 /// - positive zero1433 /// - positive subnormal numbers1434 /// - positive numbers1435 /// - positive infinity1436 /// - positive signaling NaN1437 /// - positive quiet NaN.1438 ///1439 /// The ordering established by this function does not always agree with the1440 /// [`PartialOrd`] and [`PartialEq`] implementations of `f64`. For example,1441 /// they consider negative and positive zero equal, while `total_cmp`1442 /// doesn't.1443 ///1444 /// The interpretation of the signaling NaN bit follows the definition in1445 /// the IEEE 754 standard, which may not match the interpretation by some of1446 /// the older, non-conformant (e.g. MIPS) hardware implementations.1447 ///1448 /// # Example1449 ///1450 /// ```1451 /// struct GoodBoy {1452 /// name: String,1453 /// weight: f64,1454 /// }1455 ///1456 /// let mut bois = vec![1457 /// GoodBoy { name: "Pucci".to_owned(), weight: 0.1 },1458 /// GoodBoy { name: "Woofer".to_owned(), weight: 99.0 },1459 /// GoodBoy { name: "Yapper".to_owned(), weight: 10.0 },1460 /// GoodBoy { name: "Chonk".to_owned(), weight: f64::INFINITY },1461 /// GoodBoy { name: "Abs. Unit".to_owned(), weight: f64::NAN },1462 /// GoodBoy { name: "Floaty".to_owned(), weight: -5.0 },1463 /// ];1464 ///1465 /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));1466 ///1467 /// // `f64::NAN` could be positive or negative, which will affect the sort order.1468 /// if f64::NAN.is_sign_negative() {1469 /// assert!(bois.into_iter().map(|b| b.weight)1470 /// .zip([f64::NAN, -5.0, 0.1, 10.0, 99.0, f64::INFINITY].iter())1471 /// .all(|(a, b)| a.to_bits() == b.to_bits()))1472 /// } else {1473 /// assert!(bois.into_iter().map(|b| b.weight)1474 /// .zip([-5.0, 0.1, 10.0, 99.0, f64::INFINITY, f64::NAN].iter())1475 /// .all(|(a, b)| a.to_bits() == b.to_bits()))1476 /// }1477 /// ```1478 #[stable(feature = "total_cmp", since = "1.62.0")]1479 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]1480 #[must_use]1481 #[inline]1482 pub const fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {1483 let mut left = self.to_bits() as i64;1484 let mut right = other.to_bits() as i64;1485 1486 // In case of negatives, flip all the bits except the sign1487 // to achieve a similar layout as two's complement integers1488 //1489 // Why does this work? IEEE 754 floats consist of three fields:1490 // Sign bit, exponent and mantissa. The set of exponent and mantissa1491 // fields as a whole have the property that their bitwise order is1492 // equal to the numeric magnitude where the magnitude is defined.1493 // The magnitude is not normally defined on NaN values, but1494 // IEEE 754 totalOrder defines the NaN values also to follow the1495 // bitwise order. This leads to order explained in the doc comment.1496 // However, the representation of magnitude is the same for negative1497 // and positive numbers – only the sign bit is different.1498 // To easily compare the floats as signed integers, we need to1499 // flip the exponent and mantissa bits in case of negative numbers.1500 // We effectively convert the numbers to "two's complement" form.1501 //1502 // To do the flipping, we construct a mask and XOR against it.1503 // We branchlessly calculate an "all-ones except for the sign bit"1504 // mask from negative-signed values: right shifting sign-extends1505 // the integer, so we "fill" the mask with sign bits, and then1506 // convert to unsigned to push one more zero bit.1507 // On positive values, the mask is all zeros, so it's a no-op.1508 left ^= (((left >> 63) as u64) >> 1) as i64;1509 right ^= (((right >> 63) as u64) >> 1) as i64;1510 1511 left.cmp(&right)1512 }1513 1514 /// Restrict a value to a certain interval unless it is NaN.1515 ///1516 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is1517 /// less than `min`. Otherwise this returns `self`.1518 ///1519 /// Note that this function returns NaN if the initial value was NaN as1520 /// well. If the result is zero and among the three inputs `self`, `min`, and `max` there are1521 /// zeros with different sign, either `0.0` or `-0.0` is returned non-deterministically.1522 ///1523 /// # Panics1524 ///1525 /// Panics if `min > max`, `min` is NaN, or `max` is NaN.1526 ///1527 /// # Examples1528 ///1529 /// ```1530 /// assert!((-3.0f64).clamp(-2.0, 1.0) == -2.0);1531 /// assert!((0.0f64).clamp(-2.0, 1.0) == 0.0);1532 /// assert!((2.0f64).clamp(-2.0, 1.0) == 1.0);1533 /// assert!((f64::NAN).clamp(-2.0, 1.0).is_nan());1534 ///1535 /// // These always returns zero, but the sign (which is ignored by `==`) is non-deterministic.1536 /// assert!((0.0f64).clamp(-0.0, -0.0) == 0.0);1537 /// assert!((1.0f64).clamp(-0.0, 0.0) == 0.0);1538 /// // This is definitely a negative zero.1539 /// assert!((-1.0f64).clamp(-0.0, 1.0).is_sign_negative());1540 /// ```1541 #[must_use = "method returns a new number and does not mutate the original value"]1542 #[stable(feature = "clamp", since = "1.50.0")]1543 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]1544 #[inline]1545 pub const fn clamp(mut self, min: f64, max: f64) -> f64 {1546 const_assert!(1547 min <= max,1548 "min > max, or either was NaN",1549 "min > max, or either was NaN. min = {min:?}, max = {max:?}",1550 min: f64,1551 max: f64,1552 );1553 1554 if self < min {1555 self = min;1556 }1557 if self > max {1558 self = max;1559 }1560 self1561 }1562 1563 /// Clamps this number to a symmetric range centered around zero.1564 ///1565 /// The method clamps the number's magnitude (absolute value) to be at most `limit`.1566 ///1567 /// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more1568 /// explicit about the intent.1569 ///1570 /// # Panics1571 ///1572 /// Panics if `limit` is negative or NaN, as this indicates a logic error.1573 ///1574 /// # Examples1575 ///1576 /// ```1577 /// #![feature(clamp_magnitude)]1578 /// assert_eq!(5.0f64.clamp_magnitude(3.0), 3.0);1579 /// assert_eq!((-5.0f64).clamp_magnitude(3.0), -3.0);1580 /// assert_eq!(2.0f64.clamp_magnitude(3.0), 2.0);1581 /// assert_eq!((-2.0f64).clamp_magnitude(3.0), -2.0);1582 /// ```1583 #[must_use = "this returns the clamped value and does not modify the original"]1584 #[unstable(feature = "clamp_magnitude", issue = "148519")]1585 #[inline]1586 pub fn clamp_magnitude(self, limit: f64) -> f64 {1587 assert!(limit >= 0.0, "limit must be non-negative");1588 let limit = limit.abs(); // Canonicalises -0.0 to 0.01589 self.clamp(-limit, limit)1590 }1591 1592 /// Computes the absolute value of `self`.1593 ///1594 /// This function always returns the precise result.1595 ///1596 /// # Examples1597 ///1598 /// ```1599 /// let x = 3.5_f64;1600 /// let y = -3.5_f64;1601 ///1602 /// assert_eq!(x.abs(), x);1603 /// assert_eq!(y.abs(), -y);1604 ///1605 /// assert!(f64::NAN.abs().is_nan());1606 /// ```1607 #[must_use = "method returns a new number and does not mutate the original value"]1608 #[stable(feature = "rust1", since = "1.0.0")]1609 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]1610 #[inline]1611 pub const fn abs(self) -> f64 {1612 intrinsics::fabs(self)1613 }1614 1615 /// Returns a number that represents the sign of `self`.1616 ///1617 /// - `1.0` if the number is positive, `+0.0` or `INFINITY`1618 /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`1619 /// - NaN if the number is NaN1620 ///1621 /// # Examples1622 ///1623 /// ```1624 /// let f = 3.5_f64;1625 ///1626 /// assert_eq!(f.signum(), 1.0);1627 /// assert_eq!(f64::NEG_INFINITY.signum(), -1.0);1628 ///1629 /// assert!(f64::NAN.signum().is_nan());1630 /// ```1631 #[must_use = "method returns a new number and does not mutate the original value"]1632 #[stable(feature = "rust1", since = "1.0.0")]1633 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]1634 #[inline]1635 pub const fn signum(self) -> f64 {1636 if self.is_nan() { Self::NAN } else { 1.0_f64.copysign(self) }1637 }1638 1639 /// Returns a number composed of the magnitude of `self` and the sign of1640 /// `sign`.1641 ///1642 /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`.1643 /// If `self` is a NaN, then a NaN with the same payload as `self` and the sign bit of `sign` is1644 /// returned.1645 ///1646 /// If `sign` is a NaN, then this operation will still carry over its sign into the result. Note1647 /// that IEEE 754 doesn't assign any meaning to the sign bit in case of a NaN, and as Rust1648 /// doesn't guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the1649 /// result of `copysign` with `sign` being a NaN might produce an unexpected or non-portable1650 /// result. See the [specification of NaN bit patterns](primitive@f32#nan-bit-patterns) for more1651 /// info.1652 ///1653 /// # Examples1654 ///1655 /// ```1656 /// let f = 3.5_f64;1657 ///1658 /// assert_eq!(f.copysign(0.42), 3.5_f64);1659 /// assert_eq!(f.copysign(-0.42), -3.5_f64);1660 /// assert_eq!((-f).copysign(0.42), 3.5_f64);1661 /// assert_eq!((-f).copysign(-0.42), -3.5_f64);1662 ///1663 /// assert!(f64::NAN.copysign(1.0).is_nan());1664 /// ```1665 #[must_use = "method returns a new number and does not mutate the original value"]1666 #[stable(feature = "copysign", since = "1.35.0")]1667 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]1668 #[inline]1669 pub const fn copysign(self, sign: f64) -> f64 {1670 intrinsics::copysignf64(self, sign)1671 }1672 1673 /// Float addition that allows optimizations based on algebraic rules.1674 ///1675 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.1676 #[must_use = "method returns a new number and does not mutate the original value"]1677 #[unstable(feature = "float_algebraic", issue = "136469")]1678 #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]1679 #[inline]1680 pub const fn algebraic_add(self, rhs: f64) -> f64 {1681 intrinsics::fadd_algebraic(self, rhs)1682 }1683 1684 /// Float subtraction that allows optimizations based on algebraic rules.1685 ///1686 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.1687 #[must_use = "method returns a new number and does not mutate the original value"]1688 #[unstable(feature = "float_algebraic", issue = "136469")]1689 #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]1690 #[inline]1691 pub const fn algebraic_sub(self, rhs: f64) -> f64 {1692 intrinsics::fsub_algebraic(self, rhs)1693 }1694 1695 /// Float multiplication that allows optimizations based on algebraic rules.1696 ///1697 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.1698 #[must_use = "method returns a new number and does not mutate the original value"]1699 #[unstable(feature = "float_algebraic", issue = "136469")]1700 #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]1701 #[inline]1702 pub const fn algebraic_mul(self, rhs: f64) -> f64 {1703 intrinsics::fmul_algebraic(self, rhs)1704 }1705 1706 /// Float division that allows optimizations based on algebraic rules.1707 ///1708 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.1709 #[must_use = "method returns a new number and does not mutate the original value"]1710 #[unstable(feature = "float_algebraic", issue = "136469")]1711 #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]1712 #[inline]1713 pub const fn algebraic_div(self, rhs: f64) -> f64 {1714 intrinsics::fdiv_algebraic(self, rhs)1715 }1716 1717 /// Float remainder that allows optimizations based on algebraic rules.1718 ///1719 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.1720 #[must_use = "method returns a new number and does not mutate the original value"]1721 #[unstable(feature = "float_algebraic", issue = "136469")]1722 #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]1723 #[inline]1724 pub const fn algebraic_rem(self, rhs: f64) -> f64 {1725 intrinsics::frem_algebraic(self, rhs)1726 }1727 }1728 1729 #[unstable(feature = "core_float_math", issue = "137578")]1730 /// Experimental implementations of floating point functions in `core`.1731 ///1732 /// _The standalone functions in this module are for testing only.1733 /// They will be stabilized as inherent methods._1734 pub mod math {1735 use crate::intrinsics;1736 use crate::num::imp::libm;1737 1738 /// Experimental version of `floor` in `core`. See [`f64::floor`] for details.1739 ///1740 /// # Examples1741 ///1742 /// ```1743 /// #![feature(core_float_math)]1744 ///1745 /// use core::f64;1746 ///1747 /// let f = 3.7_f64;1748 /// let g = 3.0_f64;1749 /// let h = -3.7_f64;1750 ///1751 /// assert_eq!(f64::math::floor(f), 3.0);1752 /// assert_eq!(f64::math::floor(g), 3.0);1753 /// assert_eq!(f64::math::floor(h), -4.0);1754 /// ```1755 ///1756 /// _This standalone function is for testing only.1757 /// It will be stabilized as an inherent method._1758 ///1759 /// [`f64::floor`]: ../../../std/primitive.f64.html#method.floor1760 #[inline]1761 #[unstable(feature = "core_float_math", issue = "137578")]1762 #[must_use = "method returns a new number and does not mutate the original value"]1763 pub const fn floor(x: f64) -> f64 {1764 intrinsics::floorf64(x)1765 }1766 1767 /// Experimental version of `ceil` in `core`. See [`f64::ceil`] for details.1768 ///1769 /// # Examples1770 ///1771 /// ```1772 /// #![feature(core_float_math)]1773 ///1774 /// use core::f64;1775 ///1776 /// let f = 3.01_f64;1777 /// let g = 4.0_f64;1778 ///1779 /// assert_eq!(f64::math::ceil(f), 4.0);1780 /// assert_eq!(f64::math::ceil(g), 4.0);1781 /// ```1782 ///1783 /// _This standalone function is for testing only.1784 /// It will be stabilized as an inherent method._1785 ///1786 /// [`f64::ceil`]: ../../../std/primitive.f64.html#method.ceil1787 #[inline]1788 #[doc(alias = "ceiling")]1789 #[unstable(feature = "core_float_math", issue = "137578")]1790 #[must_use = "method returns a new number and does not mutate the original value"]1791 pub const fn ceil(x: f64) -> f64 {1792 intrinsics::ceilf64(x)1793 }1794 1795 /// Experimental version of `round` in `core`. See [`f64::round`] for details.1796 ///1797 /// # Examples1798 ///1799 /// ```1800 /// #![feature(core_float_math)]1801 ///1802 /// use core::f64;1803 ///1804 /// let f = 3.3_f64;1805 /// let g = -3.3_f64;1806 /// let h = -3.7_f64;1807 /// let i = 3.5_f64;1808 /// let j = 4.5_f64;1809 ///1810 /// assert_eq!(f64::math::round(f), 3.0);1811 /// assert_eq!(f64::math::round(g), -3.0);1812 /// assert_eq!(f64::math::round(h), -4.0);1813 /// assert_eq!(f64::math::round(i), 4.0);1814 /// assert_eq!(f64::math::round(j), 5.0);1815 /// ```1816 ///1817 /// _This standalone function is for testing only.1818 /// It will be stabilized as an inherent method._1819 ///1820 /// [`f64::round`]: ../../../std/primitive.f64.html#method.round1821 #[inline]1822 #[unstable(feature = "core_float_math", issue = "137578")]1823 #[must_use = "method returns a new number and does not mutate the original value"]1824 pub const fn round(x: f64) -> f64 {1825 intrinsics::roundf64(x)1826 }1827 1828 /// Experimental version of `round_ties_even` in `core`. See [`f64::round_ties_even`] for1829 /// details.1830 ///1831 /// # Examples1832 ///1833 /// ```1834 /// #![feature(core_float_math)]1835 ///1836 /// use core::f64;1837 ///1838 /// let f = 3.3_f64;1839 /// let g = -3.3_f64;1840 /// let h = 3.5_f64;1841 /// let i = 4.5_f64;1842 ///1843 /// assert_eq!(f64::math::round_ties_even(f), 3.0);1844 /// assert_eq!(f64::math::round_ties_even(g), -3.0);1845 /// assert_eq!(f64::math::round_ties_even(h), 4.0);1846 /// assert_eq!(f64::math::round_ties_even(i), 4.0);1847 /// ```1848 ///1849 /// _This standalone function is for testing only.1850 /// It will be stabilized as an inherent method._1851 ///1852 /// [`f64::round_ties_even`]: ../../../std/primitive.f64.html#method.round_ties_even1853 #[inline]1854 #[unstable(feature = "core_float_math", issue = "137578")]1855 #[must_use = "method returns a new number and does not mutate the original value"]1856 pub const fn round_ties_even(x: f64) -> f64 {1857 intrinsics::round_ties_even_f64(x)1858 }1859 1860 /// Experimental version of `trunc` in `core`. See [`f64::trunc`] for details.1861 ///1862 /// # Examples1863 ///1864 /// ```1865 /// #![feature(core_float_math)]1866 ///1867 /// use core::f64;1868 ///1869 /// let f = 3.7_f64;1870 /// let g = 3.0_f64;1871 /// let h = -3.7_f64;1872 ///1873 /// assert_eq!(f64::math::trunc(f), 3.0);1874 /// assert_eq!(f64::math::trunc(g), 3.0);1875 /// assert_eq!(f64::math::trunc(h), -3.0);1876 /// ```1877 ///1878 /// _This standalone function is for testing only.1879 /// It will be stabilized as an inherent method._1880 ///1881 /// [`f64::trunc`]: ../../../std/primitive.f64.html#method.trunc1882 #[inline]1883 #[doc(alias = "truncate")]1884 #[unstable(feature = "core_float_math", issue = "137578")]1885 #[must_use = "method returns a new number and does not mutate the original value"]1886 pub const fn trunc(x: f64) -> f64 {1887 intrinsics::truncf64(x)1888 }1889 1890 /// Experimental version of `fract` in `core`. See [`f64::fract`] for details.1891 ///1892 /// # Examples1893 ///1894 /// ```1895 /// #![feature(core_float_math)]1896 ///1897 /// use core::f64;1898 ///1899 /// let x = 3.6_f64;1900 /// let y = -3.6_f64;1901 /// let abs_difference_x = (f64::math::fract(x) - 0.6).abs();1902 /// let abs_difference_y = (f64::math::fract(y) - (-0.6)).abs();1903 ///1904 /// assert!(abs_difference_x < 1e-10);1905 /// assert!(abs_difference_y < 1e-10);1906 /// ```1907 ///1908 /// _This standalone function is for testing only.1909 /// It will be stabilized as an inherent method._1910 ///1911 /// [`f64::fract`]: ../../../std/primitive.f64.html#method.fract1912 #[inline]1913 #[unstable(feature = "core_float_math", issue = "137578")]1914 #[must_use = "method returns a new number and does not mutate the original value"]1915 pub const fn fract(x: f64) -> f64 {1916 x - trunc(x)1917 }1918 1919 /// Experimental version of `mul_add` in `core`. See [`f64::mul_add`] for details.1920 ///1921 /// # Examples1922 ///1923 /// ```1924 /// # #![allow(unused_features)]1925 /// #![feature(core_float_math)]1926 ///1927 /// # // FIXME(#140515): mingw has an incorrect fma1928 /// # // https://sourceforge.net/p/mingw-w64/bugs/848/1929 /// # #[cfg(all(target_os = "windows", target_env = "gnu", not(target_abi = "llvm")))] {1930 /// use core::f64;1931 ///1932 /// let m = 10.0_f64;1933 /// let x = 4.0_f64;1934 /// let b = 60.0_f64;1935 ///1936 /// assert_eq!(f64::math::mul_add(m, x, b), 100.0);1937 /// assert_eq!(m * x + b, 100.0);1938 ///1939 /// let one_plus_eps = 1.0_f64 + f64::EPSILON;1940 /// let one_minus_eps = 1.0_f64 - f64::EPSILON;1941 /// let minus_one = -1.0_f64;1942 ///1943 /// // The exact result (1 + eps) * (1 - eps) = 1 - eps * eps.1944 /// assert_eq!(1945 /// f64::math::mul_add(one_plus_eps, one_minus_eps, minus_one),1946 /// -f64::EPSILON * f64::EPSILON1947 /// );1948 /// // Different rounding with the non-fused multiply and add.1949 /// assert_eq!(one_plus_eps * one_minus_eps + minus_one, 0.0);1950 /// # }1951 /// ```1952 ///1953 /// _This standalone function is for testing only.1954 /// It will be stabilized as an inherent method._1955 ///1956 /// [`f64::mul_add`]: ../../../std/primitive.f64.html#method.mul_add1957 #[inline]1958 #[doc(alias = "fma", alias = "fusedMultiplyAdd")]1959 #[unstable(feature = "core_float_math", issue = "137578")]1960 #[must_use = "method returns a new number and does not mutate the original value"]1961 pub const fn mul_add(x: f64, a: f64, b: f64) -> f64 {1962 intrinsics::fmaf64(x, a, b)1963 }1964 1965 /// Experimental version of `div_euclid` in `core`. See [`f64::div_euclid`] for details.1966 ///1967 /// # Examples1968 ///1969 /// ```1970 /// #![feature(core_float_math)]1971 ///1972 /// use core::f64;1973 ///1974 /// let a: f64 = 7.0;1975 /// let b = 4.0;1976 /// assert_eq!(f64::math::div_euclid(a, b), 1.0); // 7.0 > 4.0 * 1.01977 /// assert_eq!(f64::math::div_euclid(-a, b), -2.0); // -7.0 >= 4.0 * -2.01978 /// assert_eq!(f64::math::div_euclid(a, -b), -1.0); // 7.0 >= -4.0 * -1.01979 /// assert_eq!(f64::math::div_euclid(-a, -b), 2.0); // -7.0 >= -4.0 * 2.01980 /// ```1981 ///1982 /// _This standalone function is for testing only.1983 /// It will be stabilized as an inherent method._1984 ///1985 /// [`f64::div_euclid`]: ../../../std/primitive.f64.html#method.div_euclid1986 #[inline]1987 #[unstable(feature = "core_float_math", issue = "137578")]1988 #[must_use = "method returns a new number and does not mutate the original value"]1989 pub fn div_euclid(x: f64, rhs: f64) -> f64 {1990 let q = trunc(x / rhs);1991 if x % rhs < 0.0 {1992 return if rhs > 0.0 { q - 1.0 } else { q + 1.0 };1993 }1994 q1995 }1996 1997 /// Experimental version of `rem_euclid` in `core`. See [`f64::rem_euclid`] for details.1998 ///1999 /// # Examples2000 ///2001 /// ```2002 /// #![feature(core_float_math)]2003 ///2004 /// use core::f64;2005 ///2006 /// let a: f64 = 7.0;2007 /// let b = 4.0;2008 /// assert_eq!(f64::math::rem_euclid(a, b), 3.0);2009 /// assert_eq!(f64::math::rem_euclid(-a, b), 1.0);2010 /// assert_eq!(f64::math::rem_euclid(a, -b), 3.0);2011 /// assert_eq!(f64::math::rem_euclid(-a, -b), 1.0);2012 /// // limitation due to round-off error2013 /// assert!(f64::math::rem_euclid(-f64::EPSILON, 3.0) != 0.0);2014 /// ```2015 ///2016 /// _This standalone function is for testing only.2017 /// It will be stabilized as an inherent method._2018 ///2019 /// [`f64::rem_euclid`]: ../../../std/primitive.f64.html#method.rem_euclid2020 #[inline]2021 #[doc(alias = "modulo", alias = "mod")]2022 #[unstable(feature = "core_float_math", issue = "137578")]2023 #[must_use = "method returns a new number and does not mutate the original value"]2024 pub fn rem_euclid(x: f64, rhs: f64) -> f64 {2025 let r = x % rhs;2026 if r < 0.0 { r + rhs.abs() } else { r }2027 }2028 2029 /// Experimental version of `powi` in `core`. See [`f64::powi`] for details.2030 ///2031 /// # Examples2032 ///2033 /// ```2034 /// #![feature(core_float_math)]2035 ///2036 /// use core::f64;2037 ///2038 /// let x = 2.0_f64;2039 /// let abs_difference = (f64::math::powi(x, 2) - (x * x)).abs();2040 /// assert!(abs_difference <= 1e-6);2041 ///2042 /// assert_eq!(f64::math::powi(f64::NAN, 0), 1.0);2043 /// ```2044 ///2045 /// _This standalone function is for testing only.2046 /// It will be stabilized as an inherent method._2047 ///2048 /// [`f64::powi`]: ../../../std/primitive.f64.html#method.powi2049 #[inline]2050 #[unstable(feature = "core_float_math", issue = "137578")]2051 #[must_use = "method returns a new number and does not mutate the original value"]2052 pub fn powi(x: f64, n: i32) -> f64 {2053 intrinsics::powif64(x, n)2054 }2055 2056 /// Experimental version of `sqrt` in `core`. See [`f64::sqrt`] for details.2057 ///2058 /// # Examples2059 ///2060 /// ```2061 /// #![feature(core_float_math)]2062 ///2063 /// use core::f64;2064 ///2065 /// let positive = 4.0_f64;2066 /// let negative = -4.0_f64;2067 /// let negative_zero = -0.0_f64;2068 ///2069 /// assert_eq!(f64::math::sqrt(positive), 2.0);2070 /// assert!(f64::math::sqrt(negative).is_nan());2071 /// assert_eq!(f64::math::sqrt(negative_zero), negative_zero);2072 /// ```2073 ///2074 /// _This standalone function is for testing only.2075 /// It will be stabilized as an inherent method._2076 ///2077 /// [`f64::sqrt`]: ../../../std/primitive.f64.html#method.sqrt2078 #[inline]2079 #[doc(alias = "squareRoot")]2080 #[unstable(feature = "core_float_math", issue = "137578")]2081 #[must_use = "method returns a new number and does not mutate the original value"]2082 pub fn sqrt(x: f64) -> f64 {2083 intrinsics::sqrtf64(x)2084 }2085 2086 /// Experimental version of `abs_sub` in `core`. See [`f64::abs_sub`] for details.2087 ///2088 /// # Examples2089 ///2090 /// ```2091 /// #![feature(core_float_math)]2092 ///2093 /// use core::f64;2094 ///2095 /// let x = 3.0_f64;2096 /// let y = -3.0_f64;2097 ///2098 /// let abs_difference_x = (f64::math::abs_sub(x, 1.0) - 2.0).abs();2099 /// let abs_difference_y = (f64::math::abs_sub(y, 1.0) - 0.0).abs();2100 ///2101 /// assert!(abs_difference_x < 1e-10);2102 /// assert!(abs_difference_y < 1e-10);2103 /// ```2104 ///2105 /// _This standalone function is for testing only.2106 /// It will be stabilized as an inherent method._2107 ///2108 /// [`f64::abs_sub`]: ../../../std/primitive.f64.html#method.abs_sub2109 #[inline]2110 #[unstable(feature = "core_float_math", issue = "137578")]2111 #[deprecated(2112 since = "1.10.0",2113 note = "you probably meant `(self - other).abs()`: \2114 this operation is `(self - other).max(0.0)` \2115 except that `abs_sub` also propagates NaNs (also \2116 known as `fdim` in C). If you truly need the positive \2117 difference, consider using that expression or the C function \2118 `fdim`, depending on how you wish to handle NaN (please consider \2119 filing an issue describing your use-case too)."2120 )]2121 #[must_use = "method returns a new number and does not mutate the original value"]2122 pub fn abs_sub(x: f64, other: f64) -> f64 {2123 libm::fdim(x, other)2124 }2125 2126 /// Experimental version of `cbrt` in `core`. See [`f64::cbrt`] for details.2127 ///2128 /// # Examples2129 ///2130 /// ```2131 /// #![feature(core_float_math)]2132 ///2133 /// use core::f64;2134 ///2135 /// let x = 8.0_f64;2136 ///2137 /// // x^(1/3) - 2 == 02138 /// let abs_difference = (f64::math::cbrt(x) - 2.0).abs();2139 ///2140 /// assert!(abs_difference < 1e-10);2141 /// ```2142 ///2143 /// _This standalone function is for testing only.2144 /// It will be stabilized as an inherent method._2145 ///2146 /// [`f64::cbrt`]: ../../../std/primitive.f64.html#method.cbrt2147 #[inline]2148 #[unstable(feature = "core_float_math", issue = "137578")]2149 #[must_use = "method returns a new number and does not mutate the original value"]2150 pub fn cbrt(x: f64) -> f64 {2151 libm::cbrt(x)2152 }2153 }Reference details
| commit | 14210df0e27ccd7d9e6a05b8085cbd438e4bbc65 |
|---|---|
| sha256 | 84540a6a59e347c63caabe12cf895ba1239c76a50682471567007138fac1c618 |
| url | https://raw.githubusercontent.com/rust-lang/rust/14210df0e27ccd7d9e6a05b8085cbd438e4bbc65/library/core/src/num/f64.rs |