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