]> git.proxmox.com Git - rustc.git/blame - library/core/src/num/f64.rs
New upstream version 1.60.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 /// ```
c295e0f8 438 #[must_use]
83c7162d 439 #[stable(feature = "rust1", since = "1.0.0")]
3dfed10e 440 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
83c7162d 441 #[inline]
3dfed10e 442 pub const fn is_nan(self) -> bool {
94b46f34
XL
443 self != self
444 }
83c7162d 445
0731742a
XL
446 // FIXME(#50145): `abs` is publicly unavailable in libcore due to
447 // concerns about portability, so this implementation is for
448 // private use internally.
449 #[inline]
3dfed10e 450 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
3c0e092e 451 pub(crate) const fn abs_private(self) -> f64 {
0731742a
XL
452 f64::from_bits(self.to_bits() & 0x7fff_ffff_ffff_ffff)
453 }
454
9fa01778
XL
455 /// Returns `true` if this value is positive infinity or negative infinity, and
456 /// `false` otherwise.
83c7162d
XL
457 ///
458 /// ```
83c7162d
XL
459 /// let f = 7.0f64;
460 /// let inf = f64::INFINITY;
461 /// let neg_inf = f64::NEG_INFINITY;
462 /// let nan = f64::NAN;
463 ///
464 /// assert!(!f.is_infinite());
465 /// assert!(!nan.is_infinite());
466 ///
467 /// assert!(inf.is_infinite());
468 /// assert!(neg_inf.is_infinite());
469 /// ```
c295e0f8 470 #[must_use]
83c7162d 471 #[stable(feature = "rust1", since = "1.0.0")]
3dfed10e 472 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
83c7162d 473 #[inline]
3dfed10e 474 pub const fn is_infinite(self) -> bool {
f9f354fc 475 self.abs_private() == Self::INFINITY
94b46f34 476 }
83c7162d
XL
477
478 /// Returns `true` if this number is neither infinite nor `NaN`.
479 ///
480 /// ```
83c7162d
XL
481 /// let f = 7.0f64;
482 /// let inf: f64 = f64::INFINITY;
483 /// let neg_inf: f64 = f64::NEG_INFINITY;
484 /// let nan: f64 = f64::NAN;
485 ///
486 /// assert!(f.is_finite());
487 ///
488 /// assert!(!nan.is_finite());
489 /// assert!(!inf.is_finite());
490 /// assert!(!neg_inf.is_finite());
491 /// ```
c295e0f8 492 #[must_use]
83c7162d 493 #[stable(feature = "rust1", since = "1.0.0")]
3dfed10e 494 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
83c7162d 495 #[inline]
3dfed10e 496 pub const fn is_finite(self) -> bool {
0731742a
XL
497 // There's no need to handle NaN separately: if self is NaN,
498 // the comparison is not true, exactly as desired.
f9f354fc 499 self.abs_private() < Self::INFINITY
94b46f34 500 }
83c7162d 501
fc512014
XL
502 /// Returns `true` if the number is [subnormal].
503 ///
504 /// ```
fc512014
XL
505 /// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308_f64
506 /// let max = f64::MAX;
507 /// let lower_than_min = 1.0e-308_f64;
508 /// let zero = 0.0_f64;
509 ///
510 /// assert!(!min.is_subnormal());
511 /// assert!(!max.is_subnormal());
512 ///
513 /// assert!(!zero.is_subnormal());
514 /// assert!(!f64::NAN.is_subnormal());
515 /// assert!(!f64::INFINITY.is_subnormal());
516 /// // Values between `0` and `min` are Subnormal.
517 /// assert!(lower_than_min.is_subnormal());
518 /// ```
519 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
c295e0f8 520 #[must_use]
cdc7bbd5 521 #[stable(feature = "is_subnormal", since = "1.53.0")]
fc512014
XL
522 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
523 #[inline]
524 pub const fn is_subnormal(self) -> bool {
525 matches!(self.classify(), FpCategory::Subnormal)
526 }
527
83c7162d 528 /// Returns `true` if the number is neither zero, infinite,
dfeec247 529 /// [subnormal], or `NaN`.
83c7162d
XL
530 ///
531 /// ```
83c7162d
XL
532 /// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308f64
533 /// let max = f64::MAX;
534 /// let lower_than_min = 1.0e-308_f64;
535 /// let zero = 0.0f64;
536 ///
537 /// assert!(min.is_normal());
538 /// assert!(max.is_normal());
539 ///
540 /// assert!(!zero.is_normal());
541 /// assert!(!f64::NAN.is_normal());
542 /// assert!(!f64::INFINITY.is_normal());
543 /// // Values between `0` and `min` are Subnormal.
544 /// assert!(!lower_than_min.is_normal());
545 /// ```
546 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
c295e0f8 547 #[must_use]
83c7162d 548 #[stable(feature = "rust1", since = "1.0.0")]
3dfed10e 549 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
83c7162d 550 #[inline]
3dfed10e
XL
551 pub const fn is_normal(self) -> bool {
552 matches!(self.classify(), FpCategory::Normal)
94b46f34 553 }
83c7162d
XL
554
555 /// Returns the floating point category of the number. If only one property
556 /// is going to be tested, it is generally faster to use the specific
557 /// predicate instead.
558 ///
559 /// ```
560 /// use std::num::FpCategory;
83c7162d
XL
561 ///
562 /// let num = 12.4_f64;
563 /// let inf = f64::INFINITY;
564 ///
565 /// assert_eq!(num.classify(), FpCategory::Normal);
566 /// assert_eq!(inf.classify(), FpCategory::Infinite);
567 /// ```
568 #[stable(feature = "rust1", since = "1.0.0")]
3dfed10e
XL
569 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
570 pub const fn classify(self) -> FpCategory {
94b46f34
XL
571 const EXP_MASK: u64 = 0x7ff0000000000000;
572 const MAN_MASK: u64 = 0x000fffffffffffff;
573
574 let bits = self.to_bits();
575 match (bits & MAN_MASK, bits & EXP_MASK) {
576 (0, 0) => FpCategory::Zero,
577 (_, 0) => FpCategory::Subnormal,
578 (0, EXP_MASK) => FpCategory::Infinite,
579 (_, EXP_MASK) => FpCategory::Nan,
580 _ => FpCategory::Normal,
581 }
582 }
83c7162d 583
9fa01778 584 /// Returns `true` if `self` has a positive sign, including `+0.0`, `NaN`s with
83c7162d
XL
585 /// positive sign bit and positive infinity.
586 ///
587 /// ```
588 /// let f = 7.0_f64;
589 /// let g = -7.0_f64;
590 ///
591 /// assert!(f.is_sign_positive());
592 /// assert!(!g.is_sign_positive());
593 /// ```
c295e0f8 594 #[must_use]
83c7162d 595 #[stable(feature = "rust1", since = "1.0.0")]
3dfed10e 596 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
83c7162d 597 #[inline]
3dfed10e 598 pub const fn is_sign_positive(self) -> bool {
94b46f34
XL
599 !self.is_sign_negative()
600 }
83c7162d 601
c295e0f8 602 #[must_use]
83c7162d
XL
603 #[stable(feature = "rust1", since = "1.0.0")]
604 #[rustc_deprecated(since = "1.0.0", reason = "renamed to is_sign_positive")]
605 #[inline]
606 #[doc(hidden)]
94b46f34
XL
607 pub fn is_positive(self) -> bool {
608 self.is_sign_positive()
609 }
83c7162d 610
9fa01778 611 /// Returns `true` if `self` has a negative sign, including `-0.0`, `NaN`s with
83c7162d
XL
612 /// negative sign bit and negative infinity.
613 ///
614 /// ```
615 /// let f = 7.0_f64;
616 /// let g = -7.0_f64;
617 ///
618 /// assert!(!f.is_sign_negative());
619 /// assert!(g.is_sign_negative());
620 /// ```
c295e0f8 621 #[must_use]
83c7162d 622 #[stable(feature = "rust1", since = "1.0.0")]
3dfed10e 623 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
83c7162d 624 #[inline]
3dfed10e 625 pub const fn is_sign_negative(self) -> bool {
94b46f34
XL
626 self.to_bits() & 0x8000_0000_0000_0000 != 0
627 }
83c7162d 628
c295e0f8 629 #[must_use]
83c7162d
XL
630 #[stable(feature = "rust1", since = "1.0.0")]
631 #[rustc_deprecated(since = "1.0.0", reason = "renamed to is_sign_negative")]
632 #[inline]
633 #[doc(hidden)]
94b46f34
XL
634 pub fn is_negative(self) -> bool {
635 self.is_sign_negative()
636 }
83c7162d
XL
637
638 /// Takes the reciprocal (inverse) of a number, `1/x`.
639 ///
640 /// ```
641 /// let x = 2.0_f64;
e1599b0c 642 /// let abs_difference = (x.recip() - (1.0 / x)).abs();
83c7162d
XL
643 ///
644 /// assert!(abs_difference < 1e-10);
645 /// ```
a2a8927a 646 #[must_use = "this returns the result of the operation, without modifying the original"]
83c7162d
XL
647 #[stable(feature = "rust1", since = "1.0.0")]
648 #[inline]
94b46f34
XL
649 pub fn recip(self) -> f64 {
650 1.0 / self
651 }
83c7162d
XL
652
653 /// Converts radians to degrees.
654 ///
655 /// ```
ba9703b0 656 /// let angle = std::f64::consts::PI;
83c7162d
XL
657 ///
658 /// let abs_difference = (angle.to_degrees() - 180.0).abs();
659 ///
660 /// assert!(abs_difference < 1e-10);
661 /// ```
c295e0f8
XL
662 #[must_use = "this returns the result of the operation, \
663 without modifying the original"]
83c7162d
XL
664 #[stable(feature = "rust1", since = "1.0.0")]
665 #[inline]
94b46f34
XL
666 pub fn to_degrees(self) -> f64 {
667 // The division here is correctly rounded with respect to the true
668 // value of 180/π. (This differs from f32, where a constant must be
669 // used to ensure a correctly rounded result.)
670 self * (180.0f64 / consts::PI)
671 }
83c7162d
XL
672
673 /// Converts degrees to radians.
674 ///
675 /// ```
83c7162d
XL
676 /// let angle = 180.0_f64;
677 ///
ba9703b0 678 /// let abs_difference = (angle.to_radians() - std::f64::consts::PI).abs();
83c7162d
XL
679 ///
680 /// assert!(abs_difference < 1e-10);
681 /// ```
c295e0f8
XL
682 #[must_use = "this returns the result of the operation, \
683 without modifying the original"]
83c7162d
XL
684 #[stable(feature = "rust1", since = "1.0.0")]
685 #[inline]
94b46f34
XL
686 pub fn to_radians(self) -> f64 {
687 let value: f64 = consts::PI;
688 self * (value / 180.0)
689 }
83c7162d
XL
690
691 /// Returns the maximum of the two numbers.
692 ///
3c0e092e 693 /// Follows the IEEE-754 2008 semantics for maxNum, except for handling of signaling NaNs.
5099ac24 694 /// This matches the behavior of libm’s fmax.
3c0e092e 695 ///
83c7162d
XL
696 /// ```
697 /// let x = 1.0_f64;
698 /// let y = 2.0_f64;
699 ///
700 /// assert_eq!(x.max(y), y);
701 /// ```
702 ///
703 /// If one of the arguments is NaN, then the other argument is returned.
a2a8927a 704 #[must_use = "this returns the result of the comparison, without modifying either input"]
83c7162d
XL
705 #[stable(feature = "rust1", since = "1.0.0")]
706 #[inline]
707 pub fn max(self, other: f64) -> f64 {
dc9dc135 708 intrinsics::maxnumf64(self, other)
83c7162d
XL
709 }
710
711 /// Returns the minimum of the two numbers.
712 ///
3c0e092e
XL
713 /// Follows the IEEE-754 2008 semantics for minNum, except for handling of signaling NaNs.
714 /// This matches the behavior of libm’s fmin.
715 ///
83c7162d
XL
716 /// ```
717 /// let x = 1.0_f64;
718 /// let y = 2.0_f64;
719 ///
720 /// assert_eq!(x.min(y), x);
721 /// ```
722 ///
723 /// If one of the arguments is NaN, then the other argument is returned.
a2a8927a 724 #[must_use = "this returns the result of the comparison, without modifying either input"]
83c7162d
XL
725 #[stable(feature = "rust1", since = "1.0.0")]
726 #[inline]
727 pub fn min(self, other: f64) -> f64 {
dc9dc135 728 intrinsics::minnumf64(self, other)
83c7162d
XL
729 }
730
3c0e092e
XL
731 /// Returns the maximum of the two numbers, propagating NaNs.
732 ///
733 /// This returns NaN when *either* argument is NaN, as opposed to
734 /// [`f64::max`] which only returns NaN when *both* arguments are NaN.
735 ///
736 /// ```
737 /// #![feature(float_minimum_maximum)]
738 /// let x = 1.0_f64;
739 /// let y = 2.0_f64;
740 ///
741 /// assert_eq!(x.maximum(y), y);
742 /// assert!(x.maximum(f64::NAN).is_nan());
743 /// ```
744 ///
745 /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the greater
746 /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
747 /// Note that this follows the semantics specified in IEEE 754-2019.
a2a8927a 748 #[must_use = "this returns the result of the comparison, without modifying either input"]
3c0e092e
XL
749 #[unstable(feature = "float_minimum_maximum", issue = "91079")]
750 #[inline]
751 pub fn maximum(self, other: f64) -> f64 {
752 if self > other {
753 self
754 } else if other > self {
755 other
756 } else if self == other {
757 if self.is_sign_positive() && other.is_sign_negative() { self } else { other }
758 } else {
759 self + other
760 }
761 }
762
763 /// Returns the minimum of the two numbers, propagating NaNs.
764 ///
765 /// This returns NaN when *either* argument is NaN, as opposed to
766 /// [`f64::min`] which only returns NaN when *both* arguments are NaN.
767 ///
768 /// ```
769 /// #![feature(float_minimum_maximum)]
770 /// let x = 1.0_f64;
771 /// let y = 2.0_f64;
772 ///
773 /// assert_eq!(x.minimum(y), x);
774 /// assert!(x.minimum(f64::NAN).is_nan());
775 /// ```
776 ///
777 /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the lesser
778 /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
779 /// Note that this follows the semantics specified in IEEE 754-2019.
a2a8927a 780 #[must_use = "this returns the result of the comparison, without modifying either input"]
3c0e092e
XL
781 #[unstable(feature = "float_minimum_maximum", issue = "91079")]
782 #[inline]
783 pub fn minimum(self, other: f64) -> f64 {
784 if self < other {
785 self
786 } else if other < self {
787 other
788 } else if self == other {
789 if self.is_sign_negative() && other.is_sign_positive() { self } else { other }
790 } else {
791 self + other
792 }
793 }
794
60c5eb7d
XL
795 /// Rounds toward zero and converts to any primitive integer type,
796 /// assuming that the value is finite and fits in that type.
797 ///
798 /// ```
f9f354fc 799 /// let value = 4.6_f64;
ba9703b0 800 /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
60c5eb7d
XL
801 /// assert_eq!(rounded, 4);
802 ///
f9f354fc 803 /// let value = -128.9_f64;
ba9703b0
XL
804 /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
805 /// assert_eq!(rounded, i8::MIN);
60c5eb7d
XL
806 /// ```
807 ///
808 /// # Safety
809 ///
810 /// The value must:
811 ///
812 /// * Not be `NaN`
813 /// * Not be infinite
814 /// * Be representable in the return type `Int`, after truncating off its fractional part
c295e0f8
XL
815 #[must_use = "this returns the result of the operation, \
816 without modifying the original"]
ba9703b0 817 #[stable(feature = "float_approx_unchecked_to", since = "1.44.0")]
60c5eb7d 818 #[inline]
ba9703b0 819 pub unsafe fn to_int_unchecked<Int>(self) -> Int
60c5eb7d
XL
820 where
821 Self: FloatToInt<Int>,
822 {
f035d41b
XL
823 // SAFETY: the caller must uphold the safety contract for
824 // `FloatToInt::to_int_unchecked`.
825 unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
60c5eb7d
XL
826 }
827
83c7162d
XL
828 /// Raw transmutation to `u64`.
829 ///
830 /// This is currently identical to `transmute::<f64, u64>(self)` on all platforms.
831 ///
17df50a5
XL
832 /// See [`from_bits`](Self::from_bits) for some discussion of the
833 /// portability of this operation (there are almost no issues).
83c7162d
XL
834 ///
835 /// Note that this function is distinct from `as` casting, which attempts to
836 /// preserve the *numeric* value, and not the bitwise value.
837 ///
838 /// # Examples
839 ///
840 /// ```
841 /// assert!((1f64).to_bits() != 1f64 as u64); // to_bits() is not casting!
842 /// assert_eq!((12.5f64).to_bits(), 0x4029000000000000);
843 ///
844 /// ```
c295e0f8
XL
845 #[must_use = "this returns the result of the operation, \
846 without modifying the original"]
83c7162d 847 #[stable(feature = "float_bits_conv", since = "1.20.0")]
3dfed10e 848 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
83c7162d 849 #[inline]
3dfed10e 850 pub const fn to_bits(self) -> u64 {
60c5eb7d 851 // SAFETY: `u64` is a plain old datatype so we can always transmute to it
94b46f34 852 unsafe { mem::transmute(self) }
83c7162d
XL
853 }
854
855 /// Raw transmutation from `u64`.
856 ///
857 /// This is currently identical to `transmute::<u64, f64>(v)` on all platforms.
858 /// It turns out this is incredibly portable, for two reasons:
859 ///
860 /// * Floats and Ints have the same endianness on all supported platforms.
861 /// * IEEE-754 very precisely specifies the bit layout of floats.
862 ///
863 /// However there is one caveat: prior to the 2008 version of IEEE-754, how
864 /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
865 /// (notably x86 and ARM) picked the interpretation that was ultimately
866 /// standardized in 2008, but some didn't (notably MIPS). As a result, all
867 /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
868 ///
869 /// Rather than trying to preserve signaling-ness cross-platform, this
3dfed10e 870 /// implementation favors preserving the exact bits. This means that
83c7162d
XL
871 /// any payloads encoded in NaNs will be preserved even if the result of
872 /// this method is sent over the network from an x86 machine to a MIPS one.
873 ///
874 /// If the results of this method are only manipulated by the same
875 /// architecture that produced them, then there is no portability concern.
876 ///
877 /// If the input isn't NaN, then there is no portability concern.
878 ///
3dfed10e 879 /// If you don't care about signaling-ness (very likely), then there is no
83c7162d
XL
880 /// portability concern.
881 ///
882 /// Note that this function is distinct from `as` casting, which attempts to
883 /// preserve the *numeric* value, and not the bitwise value.
884 ///
885 /// # Examples
886 ///
887 /// ```
83c7162d 888 /// let v = f64::from_bits(0x4029000000000000);
416331ca 889 /// assert_eq!(v, 12.5);
83c7162d
XL
890 /// ```
891 #[stable(feature = "float_bits_conv", since = "1.20.0")]
3dfed10e 892 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
c295e0f8 893 #[must_use]
83c7162d 894 #[inline]
3dfed10e 895 pub const fn from_bits(v: u64) -> Self {
60c5eb7d 896 // SAFETY: `u64` is a plain old datatype so we can always transmute from it
94b46f34
XL
897 // It turns out the safety issues with sNaN were overblown! Hooray!
898 unsafe { mem::transmute(v) }
83c7162d 899 }
416331ca
XL
900
901 /// Return the memory representation of this floating point number as a byte array in
902 /// big-endian (network) byte order.
903 ///
904 /// # Examples
905 ///
906 /// ```
416331ca
XL
907 /// let bytes = 12.5f64.to_be_bytes();
908 /// assert_eq!(bytes, [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
909 /// ```
c295e0f8
XL
910 #[must_use = "this returns the result of the operation, \
911 without modifying the original"]
e74abb32 912 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
3dfed10e 913 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
416331ca 914 #[inline]
3dfed10e 915 pub const fn to_be_bytes(self) -> [u8; 8] {
416331ca
XL
916 self.to_bits().to_be_bytes()
917 }
918
919 /// Return the memory representation of this floating point number as a byte array in
920 /// little-endian byte order.
921 ///
922 /// # Examples
923 ///
924 /// ```
416331ca
XL
925 /// let bytes = 12.5f64.to_le_bytes();
926 /// assert_eq!(bytes, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]);
927 /// ```
c295e0f8
XL
928 #[must_use = "this returns the result of the operation, \
929 without modifying the original"]
e74abb32 930 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
3dfed10e 931 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
416331ca 932 #[inline]
3dfed10e 933 pub const fn to_le_bytes(self) -> [u8; 8] {
416331ca
XL
934 self.to_bits().to_le_bytes()
935 }
936
937 /// Return the memory representation of this floating point number as a byte array in
938 /// native byte order.
939 ///
940 /// As the target platform's native endianness is used, portable code
941 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
942 ///
6a06907d
XL
943 /// [`to_be_bytes`]: f64::to_be_bytes
944 /// [`to_le_bytes`]: f64::to_le_bytes
416331ca
XL
945 ///
946 /// # Examples
947 ///
948 /// ```
416331ca
XL
949 /// let bytes = 12.5f64.to_ne_bytes();
950 /// assert_eq!(
951 /// bytes,
952 /// if cfg!(target_endian = "big") {
953 /// [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
954 /// } else {
955 /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]
956 /// }
957 /// );
958 /// ```
c295e0f8
XL
959 #[must_use = "this returns the result of the operation, \
960 without modifying the original"]
e74abb32 961 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
3dfed10e 962 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
416331ca 963 #[inline]
3dfed10e 964 pub const fn to_ne_bytes(self) -> [u8; 8] {
416331ca
XL
965 self.to_bits().to_ne_bytes()
966 }
967
968 /// Create a floating point value from its representation as a byte array in big endian.
969 ///
970 /// # Examples
971 ///
972 /// ```
416331ca
XL
973 /// let value = f64::from_be_bytes([0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
974 /// assert_eq!(value, 12.5);
975 /// ```
e74abb32 976 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
3dfed10e 977 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
c295e0f8 978 #[must_use]
416331ca 979 #[inline]
3dfed10e 980 pub const fn from_be_bytes(bytes: [u8; 8]) -> Self {
416331ca
XL
981 Self::from_bits(u64::from_be_bytes(bytes))
982 }
983
984 /// Create a floating point value from its representation as a byte array in little endian.
985 ///
986 /// # Examples
987 ///
988 /// ```
416331ca
XL
989 /// let value = f64::from_le_bytes([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]);
990 /// assert_eq!(value, 12.5);
991 /// ```
e74abb32 992 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
3dfed10e 993 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
c295e0f8 994 #[must_use]
416331ca 995 #[inline]
3dfed10e 996 pub const fn from_le_bytes(bytes: [u8; 8]) -> Self {
416331ca
XL
997 Self::from_bits(u64::from_le_bytes(bytes))
998 }
999
1000 /// Create a floating point value from its representation as a byte array in native endian.
1001 ///
1002 /// As the target platform's native endianness is used, portable code
1003 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1004 /// appropriate instead.
1005 ///
6a06907d
XL
1006 /// [`from_be_bytes`]: f64::from_be_bytes
1007 /// [`from_le_bytes`]: f64::from_le_bytes
416331ca
XL
1008 ///
1009 /// # Examples
1010 ///
1011 /// ```
416331ca
XL
1012 /// let value = f64::from_ne_bytes(if cfg!(target_endian = "big") {
1013 /// [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1014 /// } else {
1015 /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]
1016 /// });
1017 /// assert_eq!(value, 12.5);
1018 /// ```
e74abb32 1019 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
3dfed10e 1020 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
c295e0f8 1021 #[must_use]
416331ca 1022 #[inline]
3dfed10e 1023 pub const fn from_ne_bytes(bytes: [u8; 8]) -> Self {
416331ca
XL
1024 Self::from_bits(u64::from_ne_bytes(bytes))
1025 }
f9f354fc 1026
5099ac24
FG
1027 /// Return the ordering between `self` and `other`.
1028 ///
f9f354fc
XL
1029 /// Unlike the standard partial comparison between floating point numbers,
1030 /// this comparison always produces an ordering in accordance to
5099ac24
FG
1031 /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1032 /// floating point standard. The values are ordered in the following sequence:
1033 ///
1034 /// - negative quiet NaN
1035 /// - negative signaling NaN
1036 /// - negative infinity
1037 /// - negative numbers
1038 /// - negative subnormal numbers
1039 /// - negative zero
1040 /// - positive zero
1041 /// - positive subnormal numbers
1042 /// - positive numbers
1043 /// - positive infinity
1044 /// - positive signaling NaN
1045 /// - positive quiet NaN.
1046 ///
1047 /// The ordering established by this function does not always agree with the
1048 /// [`PartialOrd`] and [`PartialEq`] implementations of `f64`. For example,
1049 /// they consider negative and positive zero equal, while `total_cmp`
1050 /// doesn't.
1051 ///
1052 /// The interpretation of the signaling NaN bit follows the definition in
1053 /// the IEEE 754 standard, which may not match the interpretation by some of
1054 /// the older, non-conformant (e.g. MIPS) hardware implementations.
29967ef6 1055 ///
f9f354fc 1056 /// # Example
5099ac24 1057 ///
f9f354fc
XL
1058 /// ```
1059 /// #![feature(total_cmp)]
1060 /// struct GoodBoy {
1061 /// name: String,
1062 /// weight: f64,
1063 /// }
1064 ///
1065 /// let mut bois = vec![
1066 /// GoodBoy { name: "Pucci".to_owned(), weight: 0.1 },
1067 /// GoodBoy { name: "Woofer".to_owned(), weight: 99.0 },
1068 /// GoodBoy { name: "Yapper".to_owned(), weight: 10.0 },
1069 /// GoodBoy { name: "Chonk".to_owned(), weight: f64::INFINITY },
1070 /// GoodBoy { name: "Abs. Unit".to_owned(), weight: f64::NAN },
1071 /// GoodBoy { name: "Floaty".to_owned(), weight: -5.0 },
1072 /// ];
1073 ///
1074 /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1075 /// # assert!(bois.into_iter().map(|b| b.weight)
1076 /// # .zip([-5.0, 0.1, 10.0, 99.0, f64::INFINITY, f64::NAN].iter())
1077 /// # .all(|(a, b)| a.to_bits() == b.to_bits()))
1078 /// ```
1079 #[unstable(feature = "total_cmp", issue = "72599")]
3c0e092e 1080 #[must_use]
f9f354fc
XL
1081 #[inline]
1082 pub fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1083 let mut left = self.to_bits() as i64;
1084 let mut right = other.to_bits() as i64;
1085
1086 // In case of negatives, flip all the bits except the sign
1087 // to achieve a similar layout as two's complement integers
1088 //
1089 // Why does this work? IEEE 754 floats consist of three fields:
1090 // Sign bit, exponent and mantissa. The set of exponent and mantissa
1091 // fields as a whole have the property that their bitwise order is
1092 // equal to the numeric magnitude where the magnitude is defined.
1093 // The magnitude is not normally defined on NaN values, but
1094 // IEEE 754 totalOrder defines the NaN values also to follow the
1095 // bitwise order. This leads to order explained in the doc comment.
1096 // However, the representation of magnitude is the same for negative
1097 // and positive numbers – only the sign bit is different.
1098 // To easily compare the floats as signed integers, we need to
1099 // flip the exponent and mantissa bits in case of negative numbers.
1100 // We effectively convert the numbers to "two's complement" form.
1101 //
1102 // To do the flipping, we construct a mask and XOR against it.
1103 // We branchlessly calculate an "all-ones except for the sign bit"
1104 // mask from negative-signed values: right shifting sign-extends
1105 // the integer, so we "fill" the mask with sign bits, and then
1106 // convert to unsigned to push one more zero bit.
1107 // On positive values, the mask is all zeros, so it's a no-op.
1108 left ^= (((left >> 63) as u64) >> 1) as i64;
1109 right ^= (((right >> 63) as u64) >> 1) as i64;
1110
1111 left.cmp(&right)
1112 }
fc512014
XL
1113
1114 /// Restrict a value to a certain interval unless it is NaN.
1115 ///
1116 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1117 /// less than `min`. Otherwise this returns `self`.
1118 ///
1119 /// Note that this function returns NaN if the initial value was NaN as
1120 /// well.
1121 ///
1122 /// # Panics
1123 ///
1124 /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1125 ///
1126 /// # Examples
1127 ///
1128 /// ```
1129 /// assert!((-3.0f64).clamp(-2.0, 1.0) == -2.0);
1130 /// assert!((0.0f64).clamp(-2.0, 1.0) == 0.0);
1131 /// assert!((2.0f64).clamp(-2.0, 1.0) == 1.0);
1132 /// assert!((f64::NAN).clamp(-2.0, 1.0).is_nan());
1133 /// ```
1134 #[must_use = "method returns a new number and does not mutate the original value"]
1135 #[stable(feature = "clamp", since = "1.50.0")]
1136 #[inline]
1137 pub fn clamp(self, min: f64, max: f64) -> f64 {
1138 assert!(min <= max);
1139 let mut x = self;
1140 if x < min {
1141 x = min;
1142 }
1143 if x > max {
1144 x = max;
1145 }
1146 x
1147 }
83c7162d 1148}