core/num/
f64.rs

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 module
8//! (as distinct from those defined in the `consts` sub-module),
9//! new code should instead use the associated constants
10//! defined directly on the `f64` type.
11
12#![stable(feature = "rust1", since = "1.0.0")]
13
14use crate::convert::FloatToInt;
15use crate::num::FpCategory;
16use crate::panic::const_assert;
17use crate::{intrinsics, mem};
18
19/// The radix or base of the internal representation of `f64`.
20/// Use [`f64::RADIX`] instead.
21///
22/// # Examples
23///
24/// ```rust
25/// // deprecated way
26/// # #[allow(deprecated, deprecated_in_future)]
27/// let r = std::f64::RADIX;
28///
29/// // intended way
30/// 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"]
35pub const RADIX: u32 = f64::RADIX;
36
37/// Number of significant digits in base 2.
38/// Use [`f64::MANTISSA_DIGITS`] instead.
39///
40/// # Examples
41///
42/// ```rust
43/// // deprecated way
44/// # #[allow(deprecated, deprecated_in_future)]
45/// let d = std::f64::MANTISSA_DIGITS;
46///
47/// // intended way
48/// let d = f64::MANTISSA_DIGITS;
49/// ```
50#[stable(feature = "rust1", since = "1.0.0")]
51#[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"]
56pub const MANTISSA_DIGITS: u32 = f64::MANTISSA_DIGITS;
57
58/// Approximate number of significant digits in base 10.
59/// Use [`f64::DIGITS`] instead.
60///
61/// # Examples
62///
63/// ```rust
64/// // deprecated way
65/// # #[allow(deprecated, deprecated_in_future)]
66/// let d = std::f64::DIGITS;
67///
68/// // intended way
69/// 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"]
74pub 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_epsilon
82///
83/// # Examples
84///
85/// ```rust
86/// // deprecated way
87/// # #[allow(deprecated, deprecated_in_future)]
88/// let e = std::f64::EPSILON;
89///
90/// // intended way
91/// 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"]
96pub const EPSILON: f64 = f64::EPSILON;
97
98/// Smallest finite `f64` value.
99/// Use [`f64::MIN`] instead.
100///
101/// # Examples
102///
103/// ```rust
104/// // deprecated way
105/// # #[allow(deprecated, deprecated_in_future)]
106/// let min = std::f64::MIN;
107///
108/// // intended way
109/// let min = f64::MIN;
110/// ```
111#[stable(feature = "rust1", since = "1.0.0")]
112#[deprecated(since = "TBD", note = "replaced by the `MIN` associated constant on `f64`")]
113#[rustc_diagnostic_item = "f64_legacy_const_min"]
114pub const MIN: f64 = f64::MIN;
115
116/// Smallest positive normal `f64` value.
117/// Use [`f64::MIN_POSITIVE`] instead.
118///
119/// # Examples
120///
121/// ```rust
122/// // deprecated way
123/// # #[allow(deprecated, deprecated_in_future)]
124/// let min = std::f64::MIN_POSITIVE;
125///
126/// // intended way
127/// 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"]
132pub const MIN_POSITIVE: f64 = f64::MIN_POSITIVE;
133
134/// Largest finite `f64` value.
135/// Use [`f64::MAX`] instead.
136///
137/// # Examples
138///
139/// ```rust
140/// // deprecated way
141/// # #[allow(deprecated, deprecated_in_future)]
142/// let max = std::f64::MAX;
143///
144/// // intended way
145/// 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"]
150pub const MAX: f64 = f64::MAX;
151
152/// One greater than the minimum possible normal power of 2 exponent.
153/// Use [`f64::MIN_EXP`] instead.
154///
155/// # Examples
156///
157/// ```rust
158/// // deprecated way
159/// # #[allow(deprecated, deprecated_in_future)]
160/// let min = std::f64::MIN_EXP;
161///
162/// // intended way
163/// let min = f64::MIN_EXP;
164/// ```
165#[stable(feature = "rust1", since = "1.0.0")]
166#[deprecated(since = "TBD", note = "replaced by the `MIN_EXP` associated constant on `f64`")]
167#[rustc_diagnostic_item = "f64_legacy_const_min_exp"]
168pub const MIN_EXP: i32 = f64::MIN_EXP;
169
170/// Maximum possible power of 2 exponent.
171/// Use [`f64::MAX_EXP`] instead.
172///
173/// # Examples
174///
175/// ```rust
176/// // deprecated way
177/// # #[allow(deprecated, deprecated_in_future)]
178/// let max = std::f64::MAX_EXP;
179///
180/// // intended way
181/// 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"]
186pub 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/// # Examples
192///
193/// ```rust
194/// // deprecated way
195/// # #[allow(deprecated, deprecated_in_future)]
196/// let min = std::f64::MIN_10_EXP;
197///
198/// // intended way
199/// 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"]
204pub 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/// # Examples
210///
211/// ```rust
212/// // deprecated way
213/// # #[allow(deprecated, deprecated_in_future)]
214/// let max = std::f64::MAX_10_EXP;
215///
216/// // intended way
217/// 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"]
222pub const MAX_10_EXP: i32 = f64::MAX_10_EXP;
223
224/// Not a Number (NaN).
225/// Use [`f64::NAN`] instead.
226///
227/// # Examples
228///
229/// ```rust
230/// // deprecated way
231/// # #[allow(deprecated, deprecated_in_future)]
232/// let nan = std::f64::NAN;
233///
234/// // intended way
235/// 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"]
240pub const NAN: f64 = f64::NAN;
241
242/// Infinity (∞).
243/// Use [`f64::INFINITY`] instead.
244///
245/// # Examples
246///
247/// ```rust
248/// // deprecated way
249/// # #[allow(deprecated, deprecated_in_future)]
250/// let inf = std::f64::INFINITY;
251///
252/// // intended way
253/// 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"]
258pub const INFINITY: f64 = f64::INFINITY;
259
260/// Negative infinity (−∞).
261/// Use [`f64::NEG_INFINITY`] instead.
262///
263/// # Examples
264///
265/// ```rust
266/// // deprecated way
267/// # #[allow(deprecated, deprecated_in_future)]
268/// let ninf = std::f64::NEG_INFINITY;
269///
270/// // intended way
271/// 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"]
276pub const NEG_INFINITY: f64 = f64::NEG_INFINITY;
277
278/// Basic mathematical constants.
279#[stable(feature = "rust1", since = "1.0.0")]
280pub mod consts {
281    // FIXME: replace with mathematical constants from cmath.
282
283    /// Archimedes' constant (π)
284    #[stable(feature = "rust1", since = "1.0.0")]
285    pub const PI: f64 = 3.14159265358979323846264338327950288_f64;
286
287    /// The full circle constant (τ)
288    ///
289    /// Equal to 2π.
290    #[stable(feature = "tau_constant", since = "1.47.0")]
291    pub const TAU: f64 = 6.28318530717958647692528676655900577_f64;
292
293    /// The golden ratio (φ)
294    #[unstable(feature = "more_float_constants", issue = "103883")]
295    pub const PHI: f64 = 1.618033988749894848204586834365638118_f64;
296
297    /// The Euler-Mascheroni constant (γ)
298    #[unstable(feature = "more_float_constants", issue = "103883")]
299    pub const EGAMMA: f64 = 0.577215664901532860606512090082402431_f64;
300
301    /// π/2
302    #[stable(feature = "rust1", since = "1.0.0")]
303    pub const FRAC_PI_2: f64 = 1.57079632679489661923132169163975144_f64;
304
305    /// π/3
306    #[stable(feature = "rust1", since = "1.0.0")]
307    pub const FRAC_PI_3: f64 = 1.04719755119659774615421446109316763_f64;
308
309    /// π/4
310    #[stable(feature = "rust1", since = "1.0.0")]
311    pub const FRAC_PI_4: f64 = 0.785398163397448309615660845819875721_f64;
312
313    /// π/6
314    #[stable(feature = "rust1", since = "1.0.0")]
315    pub const FRAC_PI_6: f64 = 0.52359877559829887307710723054658381_f64;
316
317    /// π/8
318    #[stable(feature = "rust1", since = "1.0.0")]
319    pub const FRAC_PI_8: f64 = 0.39269908169872415480783042290993786_f64;
320
321    /// 1/π
322    #[stable(feature = "rust1", since = "1.0.0")]
323    pub const FRAC_1_PI: f64 = 0.318309886183790671537767526745028724_f64;
324
325    /// 1/sqrt(π)
326    #[unstable(feature = "more_float_constants", issue = "103883")]
327    pub const FRAC_1_SQRT_PI: f64 = 0.564189583547756286948079451560772586_f64;
328
329    /// 1/sqrt(2π)
330    #[doc(alias = "FRAC_1_SQRT_TAU")]
331    #[unstable(feature = "more_float_constants", issue = "103883")]
332    pub const FRAC_1_SQRT_2PI: f64 = 0.398942280401432677939946059934381868_f64;
333
334    /// 2/π
335    #[stable(feature = "rust1", since = "1.0.0")]
336    pub const FRAC_2_PI: f64 = 0.636619772367581343075535053490057448_f64;
337
338    /// 2/sqrt(π)
339    #[stable(feature = "rust1", since = "1.0.0")]
340    pub const FRAC_2_SQRT_PI: f64 = 1.12837916709551257389615890312154517_f64;
341
342    /// sqrt(2)
343    #[stable(feature = "rust1", since = "1.0.0")]
344    pub const SQRT_2: f64 = 1.41421356237309504880168872420969808_f64;
345
346    /// 1/sqrt(2)
347    #[stable(feature = "rust1", since = "1.0.0")]
348    pub const FRAC_1_SQRT_2: f64 = 0.707106781186547524400844362104849039_f64;
349
350    /// sqrt(3)
351    #[unstable(feature = "more_float_constants", issue = "103883")]
352    pub const SQRT_3: f64 = 1.732050807568877293527446341505872367_f64;
353
354    /// 1/sqrt(3)
355    #[unstable(feature = "more_float_constants", issue = "103883")]
356    pub const FRAC_1_SQRT_3: f64 = 0.577350269189625764509148780501957456_f64;
357
358    /// Euler's number (e)
359    #[stable(feature = "rust1", since = "1.0.0")]
360    pub const E: f64 = 2.71828182845904523536028747135266250_f64;
361
362    /// log<sub>2</sub>(10)
363    #[stable(feature = "extra_log_consts", since = "1.43.0")]
364    pub const LOG2_10: f64 = 3.32192809488736234787031942948939018_f64;
365
366    /// log<sub>2</sub>(e)
367    #[stable(feature = "rust1", since = "1.0.0")]
368    pub const LOG2_E: f64 = 1.44269504088896340735992468100189214_f64;
369
370    /// log<sub>10</sub>(2)
371    #[stable(feature = "extra_log_consts", since = "1.43.0")]
372    pub const LOG10_2: f64 = 0.301029995663981195213738894724493027_f64;
373
374    /// log<sub>10</sub>(e)
375    #[stable(feature = "rust1", since = "1.0.0")]
376    pub const LOG10_E: f64 = 0.434294481903251827651128918916605082_f64;
377
378    /// ln(2)
379    #[stable(feature = "rust1", since = "1.0.0")]
380    pub const LN_2: f64 = 0.693147180559945309417232121458176568_f64;
381
382    /// ln(10)
383    #[stable(feature = "rust1", since = "1.0.0")]
384    pub const LN_10: f64 = 2.30258509299404568401799145468436421_f64;
385}
386
387impl f64 {
388    /// The radix or base of the internal representation of `f64`.
389    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
390    pub const RADIX: u32 = 2;
391
392    /// Number of significant digits in base 2.
393    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
394    pub const MANTISSA_DIGITS: u32 = 53;
395    /// Approximate number of significant digits in base 10.
396    ///
397    /// This is the maximum <i>x</i> such that any decimal number with <i>x</i>
398    /// significant digits can be converted to `f64` and back without loss.
399    ///
400    /// Equal to floor(log<sub>10</sub>&nbsp;2<sup>[`MANTISSA_DIGITS`]&nbsp;&minus;&nbsp;1</sup>).
401    ///
402    /// [`MANTISSA_DIGITS`]: f64::MANTISSA_DIGITS
403    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
404    pub const DIGITS: u32 = 15;
405
406    /// [Machine epsilon] value for `f64`.
407    ///
408    /// This is the difference between `1.0` and the next larger representable number.
409    ///
410    /// Equal to 2<sup>1&nbsp;&minus;&nbsp;[`MANTISSA_DIGITS`]</sup>.
411    ///
412    /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
413    /// [`MANTISSA_DIGITS`]: f64::MANTISSA_DIGITS
414    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
415    #[rustc_diagnostic_item = "f64_epsilon"]
416    pub const EPSILON: f64 = 2.2204460492503131e-16_f64;
417
418    /// Smallest finite `f64` value.
419    ///
420    /// Equal to &minus;[`MAX`].
421    ///
422    /// [`MAX`]: f64::MAX
423    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
424    pub const MIN: f64 = -1.7976931348623157e+308_f64;
425    /// Smallest positive normal `f64` value.
426    ///
427    /// Equal to 2<sup>[`MIN_EXP`]&nbsp;&minus;&nbsp;1</sup>.
428    ///
429    /// [`MIN_EXP`]: f64::MIN_EXP
430    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
431    pub const MIN_POSITIVE: f64 = 2.2250738585072014e-308_f64;
432    /// Largest finite `f64` value.
433    ///
434    /// Equal to
435    /// (1&nbsp;&minus;&nbsp;2<sup>&minus;[`MANTISSA_DIGITS`]</sup>)&nbsp;2<sup>[`MAX_EXP`]</sup>.
436    ///
437    /// [`MANTISSA_DIGITS`]: f64::MANTISSA_DIGITS
438    /// [`MAX_EXP`]: f64::MAX_EXP
439    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
440    pub const MAX: f64 = 1.7976931348623157e+308_f64;
441
442    /// One greater than the minimum possible normal power of 2 exponent.
443    ///
444    /// If <i>x</i>&nbsp;=&nbsp;`MIN_EXP`, then normal numbers
445    /// ≥&nbsp;0.5&nbsp;×&nbsp;2<sup><i>x</i></sup>.
446    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
447    pub const MIN_EXP: i32 = -1021;
448    /// Maximum possible power of 2 exponent.
449    ///
450    /// If <i>x</i>&nbsp;=&nbsp;`MAX_EXP`, then normal numbers
451    /// &lt;&nbsp;1&nbsp;×&nbsp;2<sup><i>x</i></sup>.
452    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
453    pub const MAX_EXP: i32 = 1024;
454
455    /// Minimum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
456    ///
457    /// Equal to ceil(log<sub>10</sub>&nbsp;[`MIN_POSITIVE`]).
458    ///
459    /// [`MIN_POSITIVE`]: f64::MIN_POSITIVE
460    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
461    pub const MIN_10_EXP: i32 = -307;
462    /// Maximum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
463    ///
464    /// Equal to floor(log<sub>10</sub>&nbsp;[`MAX`]).
465    ///
466    /// [`MAX`]: f64::MAX
467    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
468    pub const MAX_10_EXP: i32 = 308;
469
470    /// Not a Number (NaN).
471    ///
472    /// Note that IEEE 754 doesn't define just a single NaN value; a plethora of bit patterns are
473    /// considered to be NaN. Furthermore, the standard makes a difference between a "signaling" and
474    /// a "quiet" NaN, and allows inspecting its "payload" (the unspecified bits in the bit pattern)
475    /// and its sign. See the [specification of NaN bit patterns](f32#nan-bit-patterns) for more
476    /// info.
477    ///
478    /// This constant is guaranteed to be a quiet NaN (on targets that follow the Rust assumptions
479    /// that the quiet/signaling bit being set to 1 indicates a quiet NaN). Beyond that, nothing is
480    /// guaranteed about the specific bit pattern chosen here: both payload and sign are arbitrary.
481    /// The concrete bit pattern may change across Rust versions and target platforms.
482    #[rustc_diagnostic_item = "f64_nan"]
483    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
484    #[allow(clippy::eq_op)]
485    pub const NAN: f64 = 0.0_f64 / 0.0_f64;
486    /// Infinity (∞).
487    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
488    pub const INFINITY: f64 = 1.0_f64 / 0.0_f64;
489    /// Negative infinity (−∞).
490    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
491    pub const NEG_INFINITY: f64 = -1.0_f64 / 0.0_f64;
492
493    /// Sign bit
494    pub(crate) const SIGN_MASK: u64 = 0x8000_0000_0000_0000;
495
496    /// Exponent mask
497    pub(crate) const EXP_MASK: u64 = 0x7ff0_0000_0000_0000;
498
499    /// Mantissa mask
500    pub(crate) const MAN_MASK: u64 = 0x000f_ffff_ffff_ffff;
501
502    /// Minimum representable positive value (min subnormal)
503    const TINY_BITS: u64 = 0x1;
504
505    /// Minimum representable negative value (min negative subnormal)
506    const NEG_TINY_BITS: u64 = Self::TINY_BITS | Self::SIGN_MASK;
507
508    /// Returns `true` if this value is NaN.
509    ///
510    /// ```
511    /// let nan = f64::NAN;
512    /// let f = 7.0_f64;
513    ///
514    /// assert!(nan.is_nan());
515    /// assert!(!f.is_nan());
516    /// ```
517    #[must_use]
518    #[stable(feature = "rust1", since = "1.0.0")]
519    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
520    #[inline]
521    #[allow(clippy::eq_op)] // > if you intended to check if the operand is NaN, use `.is_nan()` instead :)
522    pub const fn is_nan(self) -> bool {
523        self != self
524    }
525
526    /// Returns `true` if this value is positive infinity or negative infinity, and
527    /// `false` otherwise.
528    ///
529    /// ```
530    /// let f = 7.0f64;
531    /// let inf = f64::INFINITY;
532    /// let neg_inf = f64::NEG_INFINITY;
533    /// let nan = f64::NAN;
534    ///
535    /// assert!(!f.is_infinite());
536    /// assert!(!nan.is_infinite());
537    ///
538    /// assert!(inf.is_infinite());
539    /// assert!(neg_inf.is_infinite());
540    /// ```
541    #[must_use]
542    #[stable(feature = "rust1", since = "1.0.0")]
543    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
544    #[inline]
545    pub const fn is_infinite(self) -> bool {
546        // Getting clever with transmutation can result in incorrect answers on some FPUs
547        // FIXME: alter the Rust <-> Rust calling convention to prevent this problem.
548        // See https://github.com/rust-lang/rust/issues/72327
549        (self == f64::INFINITY) | (self == f64::NEG_INFINITY)
550    }
551
552    /// Returns `true` if this number is neither infinite nor NaN.
553    ///
554    /// ```
555    /// let f = 7.0f64;
556    /// let inf: f64 = f64::INFINITY;
557    /// let neg_inf: f64 = f64::NEG_INFINITY;
558    /// let nan: f64 = f64::NAN;
559    ///
560    /// assert!(f.is_finite());
561    ///
562    /// assert!(!nan.is_finite());
563    /// assert!(!inf.is_finite());
564    /// assert!(!neg_inf.is_finite());
565    /// ```
566    #[must_use]
567    #[stable(feature = "rust1", since = "1.0.0")]
568    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
569    #[inline]
570    pub const fn is_finite(self) -> bool {
571        // There's no need to handle NaN separately: if self is NaN,
572        // the comparison is not true, exactly as desired.
573        self.abs() < Self::INFINITY
574    }
575
576    /// Returns `true` if the number is [subnormal].
577    ///
578    /// ```
579    /// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308_f64
580    /// let max = f64::MAX;
581    /// let lower_than_min = 1.0e-308_f64;
582    /// let zero = 0.0_f64;
583    ///
584    /// assert!(!min.is_subnormal());
585    /// assert!(!max.is_subnormal());
586    ///
587    /// assert!(!zero.is_subnormal());
588    /// assert!(!f64::NAN.is_subnormal());
589    /// assert!(!f64::INFINITY.is_subnormal());
590    /// // Values between `0` and `min` are Subnormal.
591    /// assert!(lower_than_min.is_subnormal());
592    /// ```
593    /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
594    #[must_use]
595    #[stable(feature = "is_subnormal", since = "1.53.0")]
596    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
597    #[inline]
598    pub const fn is_subnormal(self) -> bool {
599        matches!(self.classify(), FpCategory::Subnormal)
600    }
601
602    /// Returns `true` if the number is neither zero, infinite,
603    /// [subnormal], or NaN.
604    ///
605    /// ```
606    /// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308f64
607    /// let max = f64::MAX;
608    /// let lower_than_min = 1.0e-308_f64;
609    /// let zero = 0.0f64;
610    ///
611    /// assert!(min.is_normal());
612    /// assert!(max.is_normal());
613    ///
614    /// assert!(!zero.is_normal());
615    /// assert!(!f64::NAN.is_normal());
616    /// assert!(!f64::INFINITY.is_normal());
617    /// // Values between `0` and `min` are Subnormal.
618    /// assert!(!lower_than_min.is_normal());
619    /// ```
620    /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
621    #[must_use]
622    #[stable(feature = "rust1", since = "1.0.0")]
623    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
624    #[inline]
625    pub const fn is_normal(self) -> bool {
626        matches!(self.classify(), FpCategory::Normal)
627    }
628
629    /// Returns the floating point category of the number. If only one property
630    /// is going to be tested, it is generally faster to use the specific
631    /// predicate instead.
632    ///
633    /// ```
634    /// use std::num::FpCategory;
635    ///
636    /// let num = 12.4_f64;
637    /// let inf = f64::INFINITY;
638    ///
639    /// assert_eq!(num.classify(), FpCategory::Normal);
640    /// assert_eq!(inf.classify(), FpCategory::Infinite);
641    /// ```
642    #[stable(feature = "rust1", since = "1.0.0")]
643    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
644    pub const fn classify(self) -> FpCategory {
645        // We used to have complicated logic here that avoids the simple bit-based tests to work
646        // around buggy codegen for x87 targets (see
647        // https://github.com/rust-lang/rust/issues/114479). However, some LLVM versions later, none
648        // of our tests is able to find any difference between the complicated and the naive
649        // version, so now we are back to the naive version.
650        let b = self.to_bits();
651        match (b & Self::MAN_MASK, b & Self::EXP_MASK) {
652            (0, Self::EXP_MASK) => FpCategory::Infinite,
653            (_, Self::EXP_MASK) => FpCategory::Nan,
654            (0, 0) => FpCategory::Zero,
655            (_, 0) => FpCategory::Subnormal,
656            _ => FpCategory::Normal,
657        }
658    }
659
660    /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with
661    /// positive sign bit and positive infinity.
662    ///
663    /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
664    /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
665    /// conserved over arithmetic operations, the result of `is_sign_positive` on
666    /// a NaN might produce an unexpected or non-portable result. See the [specification
667    /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == 1.0`
668    /// if you need fully portable behavior (will return `false` for all NaNs).
669    ///
670    /// ```
671    /// let f = 7.0_f64;
672    /// let g = -7.0_f64;
673    ///
674    /// assert!(f.is_sign_positive());
675    /// assert!(!g.is_sign_positive());
676    /// ```
677    #[must_use]
678    #[stable(feature = "rust1", since = "1.0.0")]
679    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
680    #[inline]
681    pub const fn is_sign_positive(self) -> bool {
682        !self.is_sign_negative()
683    }
684
685    #[must_use]
686    #[stable(feature = "rust1", since = "1.0.0")]
687    #[deprecated(since = "1.0.0", note = "renamed to is_sign_positive")]
688    #[inline]
689    #[doc(hidden)]
690    pub fn is_positive(self) -> bool {
691        self.is_sign_positive()
692    }
693
694    /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with
695    /// negative sign bit and negative infinity.
696    ///
697    /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
698    /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
699    /// conserved over arithmetic operations, the result of `is_sign_negative` on
700    /// a NaN might produce an unexpected or non-portable result. See the [specification
701    /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == -1.0`
702    /// if you need fully portable behavior (will return `false` for all NaNs).
703    ///
704    /// ```
705    /// let f = 7.0_f64;
706    /// let g = -7.0_f64;
707    ///
708    /// assert!(!f.is_sign_negative());
709    /// assert!(g.is_sign_negative());
710    /// ```
711    #[must_use]
712    #[stable(feature = "rust1", since = "1.0.0")]
713    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
714    #[inline]
715    pub const fn is_sign_negative(self) -> bool {
716        // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
717        // applies to zeros and NaNs as well.
718        // SAFETY: This is just transmuting to get the sign bit, it's fine.
719        unsafe { mem::transmute::<f64, u64>(self) & Self::SIGN_MASK != 0 }
720    }
721
722    #[must_use]
723    #[stable(feature = "rust1", since = "1.0.0")]
724    #[deprecated(since = "1.0.0", note = "renamed to is_sign_negative")]
725    #[inline]
726    #[doc(hidden)]
727    pub fn is_negative(self) -> bool {
728        self.is_sign_negative()
729    }
730
731    /// Returns the least number greater than `self`.
732    ///
733    /// Let `TINY` be the smallest representable positive `f64`. Then,
734    ///  - if `self.is_nan()`, this returns `self`;
735    ///  - if `self` is [`NEG_INFINITY`], this returns [`MIN`];
736    ///  - if `self` is `-TINY`, this returns -0.0;
737    ///  - if `self` is -0.0 or +0.0, this returns `TINY`;
738    ///  - if `self` is [`MAX`] or [`INFINITY`], this returns [`INFINITY`];
739    ///  - otherwise the unique least value greater than `self` is returned.
740    ///
741    /// The identity `x.next_up() == -(-x).next_down()` holds for all non-NaN `x`. When `x`
742    /// is finite `x == x.next_up().next_down()` also holds.
743    ///
744    /// ```rust
745    /// // f64::EPSILON is the difference between 1.0 and the next number up.
746    /// assert_eq!(1.0f64.next_up(), 1.0 + f64::EPSILON);
747    /// // But not for most numbers.
748    /// assert!(0.1f64.next_up() < 0.1 + f64::EPSILON);
749    /// assert_eq!(9007199254740992f64.next_up(), 9007199254740994.0);
750    /// ```
751    ///
752    /// This operation corresponds to IEEE-754 `nextUp`.
753    ///
754    /// [`NEG_INFINITY`]: Self::NEG_INFINITY
755    /// [`INFINITY`]: Self::INFINITY
756    /// [`MIN`]: Self::MIN
757    /// [`MAX`]: Self::MAX
758    #[inline]
759    #[doc(alias = "nextUp")]
760    #[stable(feature = "float_next_up_down", since = "1.86.0")]
761    #[rustc_const_stable(feature = "float_next_up_down", since = "1.86.0")]
762    pub const fn next_up(self) -> Self {
763        // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
764        // denormals to zero. This is in general unsound and unsupported, but here
765        // we do our best to still produce the correct result on such targets.
766        let bits = self.to_bits();
767        if self.is_nan() || bits == Self::INFINITY.to_bits() {
768            return self;
769        }
770
771        let abs = bits & !Self::SIGN_MASK;
772        let next_bits = if abs == 0 {
773            Self::TINY_BITS
774        } else if bits == abs {
775            bits + 1
776        } else {
777            bits - 1
778        };
779        Self::from_bits(next_bits)
780    }
781
782    /// Returns the greatest number less than `self`.
783    ///
784    /// Let `TINY` be the smallest representable positive `f64`. Then,
785    ///  - if `self.is_nan()`, this returns `self`;
786    ///  - if `self` is [`INFINITY`], this returns [`MAX`];
787    ///  - if `self` is `TINY`, this returns 0.0;
788    ///  - if `self` is -0.0 or +0.0, this returns `-TINY`;
789    ///  - if `self` is [`MIN`] or [`NEG_INFINITY`], this returns [`NEG_INFINITY`];
790    ///  - otherwise the unique greatest value less than `self` is returned.
791    ///
792    /// The identity `x.next_down() == -(-x).next_up()` holds for all non-NaN `x`. When `x`
793    /// is finite `x == x.next_down().next_up()` also holds.
794    ///
795    /// ```rust
796    /// let x = 1.0f64;
797    /// // Clamp value into range [0, 1).
798    /// let clamped = x.clamp(0.0, 1.0f64.next_down());
799    /// assert!(clamped < 1.0);
800    /// assert_eq!(clamped.next_up(), 1.0);
801    /// ```
802    ///
803    /// This operation corresponds to IEEE-754 `nextDown`.
804    ///
805    /// [`NEG_INFINITY`]: Self::NEG_INFINITY
806    /// [`INFINITY`]: Self::INFINITY
807    /// [`MIN`]: Self::MIN
808    /// [`MAX`]: Self::MAX
809    #[inline]
810    #[doc(alias = "nextDown")]
811    #[stable(feature = "float_next_up_down", since = "1.86.0")]
812    #[rustc_const_stable(feature = "float_next_up_down", since = "1.86.0")]
813    pub const fn next_down(self) -> Self {
814        // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
815        // denormals to zero. This is in general unsound and unsupported, but here
816        // we do our best to still produce the correct result on such targets.
817        let bits = self.to_bits();
818        if self.is_nan() || bits == Self::NEG_INFINITY.to_bits() {
819            return self;
820        }
821
822        let abs = bits & !Self::SIGN_MASK;
823        let next_bits = if abs == 0 {
824            Self::NEG_TINY_BITS
825        } else if bits == abs {
826            bits - 1
827        } else {
828            bits + 1
829        };
830        Self::from_bits(next_bits)
831    }
832
833    /// Takes the reciprocal (inverse) of a number, `1/x`.
834    ///
835    /// ```
836    /// let x = 2.0_f64;
837    /// let abs_difference = (x.recip() - (1.0 / x)).abs();
838    ///
839    /// assert!(abs_difference < 1e-10);
840    /// ```
841    #[must_use = "this returns the result of the operation, without modifying the original"]
842    #[stable(feature = "rust1", since = "1.0.0")]
843    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
844    #[inline]
845    pub const fn recip(self) -> f64 {
846        1.0 / self
847    }
848
849    /// Converts radians to degrees.
850    ///
851    /// ```
852    /// let angle = std::f64::consts::PI;
853    ///
854    /// let abs_difference = (angle.to_degrees() - 180.0).abs();
855    ///
856    /// assert!(abs_difference < 1e-10);
857    /// ```
858    #[must_use = "this returns the result of the operation, \
859                  without modifying the original"]
860    #[stable(feature = "rust1", since = "1.0.0")]
861    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
862    #[inline]
863    pub const fn to_degrees(self) -> f64 {
864        // The division here is correctly rounded with respect to the true
865        // value of 180/π. (This differs from f32, where a constant must be
866        // used to ensure a correctly rounded result.)
867        self * (180.0f64 / consts::PI)
868    }
869
870    /// Converts degrees to radians.
871    ///
872    /// ```
873    /// let angle = 180.0_f64;
874    ///
875    /// let abs_difference = (angle.to_radians() - std::f64::consts::PI).abs();
876    ///
877    /// assert!(abs_difference < 1e-10);
878    /// ```
879    #[must_use = "this returns the result of the operation, \
880                  without modifying the original"]
881    #[stable(feature = "rust1", since = "1.0.0")]
882    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
883    #[inline]
884    pub const fn to_radians(self) -> f64 {
885        const RADS_PER_DEG: f64 = consts::PI / 180.0;
886        self * RADS_PER_DEG
887    }
888
889    /// Returns the maximum of the two numbers, ignoring NaN.
890    ///
891    /// If one of the arguments is NaN, then the other argument is returned.
892    /// This follows the IEEE 754-2008 semantics for maxNum, except for handling of signaling NaNs;
893    /// this function handles all NaNs the same way and avoids maxNum's problems with associativity.
894    /// This also matches the behavior of libm’s fmax. In particular, if the inputs compare equal
895    /// (such as for the case of `+0.0` and `-0.0`), either input may be returned non-deterministically.
896    ///
897    /// ```
898    /// let x = 1.0_f64;
899    /// let y = 2.0_f64;
900    ///
901    /// assert_eq!(x.max(y), y);
902    /// ```
903    #[must_use = "this returns the result of the comparison, without modifying either input"]
904    #[stable(feature = "rust1", since = "1.0.0")]
905    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
906    #[inline]
907    pub const fn max(self, other: f64) -> f64 {
908        intrinsics::maxnumf64(self, other)
909    }
910
911    /// Returns the minimum of the two numbers, ignoring NaN.
912    ///
913    /// If one of the arguments is NaN, then the other argument is returned.
914    /// This follows the IEEE 754-2008 semantics for minNum, except for handling of signaling NaNs;
915    /// this function handles all NaNs the same way and avoids minNum's problems with associativity.
916    /// This also matches the behavior of libm’s fmin. In particular, if the inputs compare equal
917    /// (such as for the case of `+0.0` and `-0.0`), either input may be returned non-deterministically.
918    ///
919    /// ```
920    /// let x = 1.0_f64;
921    /// let y = 2.0_f64;
922    ///
923    /// assert_eq!(x.min(y), x);
924    /// ```
925    #[must_use = "this returns the result of the comparison, without modifying either input"]
926    #[stable(feature = "rust1", since = "1.0.0")]
927    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
928    #[inline]
929    pub const fn min(self, other: f64) -> f64 {
930        intrinsics::minnumf64(self, other)
931    }
932
933    /// Returns the maximum of the two numbers, propagating NaN.
934    ///
935    /// This returns NaN when *either* argument is NaN, as opposed to
936    /// [`f64::max`] which only returns NaN when *both* arguments are NaN.
937    ///
938    /// ```
939    /// #![feature(float_minimum_maximum)]
940    /// let x = 1.0_f64;
941    /// let y = 2.0_f64;
942    ///
943    /// assert_eq!(x.maximum(y), y);
944    /// assert!(x.maximum(f64::NAN).is_nan());
945    /// ```
946    ///
947    /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the greater
948    /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
949    /// Note that this follows the semantics specified in IEEE 754-2019.
950    ///
951    /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
952    /// operand is conserved; see the [specification of NaN bit patterns](f32#nan-bit-patterns) for more info.
953    #[must_use = "this returns the result of the comparison, without modifying either input"]
954    #[unstable(feature = "float_minimum_maximum", issue = "91079")]
955    #[inline]
956    pub const fn maximum(self, other: f64) -> f64 {
957        if self > other {
958            self
959        } else if other > self {
960            other
961        } else if self == other {
962            if self.is_sign_positive() && other.is_sign_negative() { self } else { other }
963        } else {
964            self + other
965        }
966    }
967
968    /// Returns the minimum of the two numbers, propagating NaN.
969    ///
970    /// This returns NaN when *either* argument is NaN, as opposed to
971    /// [`f64::min`] which only returns NaN when *both* arguments are NaN.
972    ///
973    /// ```
974    /// #![feature(float_minimum_maximum)]
975    /// let x = 1.0_f64;
976    /// let y = 2.0_f64;
977    ///
978    /// assert_eq!(x.minimum(y), x);
979    /// assert!(x.minimum(f64::NAN).is_nan());
980    /// ```
981    ///
982    /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the lesser
983    /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
984    /// Note that this follows the semantics specified in IEEE 754-2019.
985    ///
986    /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
987    /// operand is conserved; see the [specification of NaN bit patterns](f32#nan-bit-patterns) for more info.
988    #[must_use = "this returns the result of the comparison, without modifying either input"]
989    #[unstable(feature = "float_minimum_maximum", issue = "91079")]
990    #[inline]
991    pub const fn minimum(self, other: f64) -> f64 {
992        if self < other {
993            self
994        } else if other < self {
995            other
996        } else if self == other {
997            if self.is_sign_negative() && other.is_sign_positive() { self } else { other }
998        } else {
999            // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
1000            self + other
1001        }
1002    }
1003
1004    /// Calculates the middle point of `self` and `rhs`.
1005    ///
1006    /// This returns NaN when *either* argument is NaN or if a combination of
1007    /// +inf and -inf is provided as arguments.
1008    ///
1009    /// # Examples
1010    ///
1011    /// ```
1012    /// assert_eq!(1f64.midpoint(4.0), 2.5);
1013    /// assert_eq!((-5.5f64).midpoint(8.0), 1.25);
1014    /// ```
1015    #[inline]
1016    #[stable(feature = "num_midpoint", since = "1.85.0")]
1017    #[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
1018    pub const fn midpoint(self, other: f64) -> f64 {
1019        const LO: f64 = f64::MIN_POSITIVE * 2.;
1020        const HI: f64 = f64::MAX / 2.;
1021
1022        let (a, b) = (self, other);
1023        let abs_a = a.abs();
1024        let abs_b = b.abs();
1025
1026        if abs_a <= HI && abs_b <= HI {
1027            // Overflow is impossible
1028            (a + b) / 2.
1029        } else if abs_a < LO {
1030            // Not safe to halve `a` (would underflow)
1031            a + (b / 2.)
1032        } else if abs_b < LO {
1033            // Not safe to halve `b` (would underflow)
1034            (a / 2.) + b
1035        } else {
1036            // Safe to halve `a` and `b`
1037            (a / 2.) + (b / 2.)
1038        }
1039    }
1040
1041    /// Rounds toward zero and converts to any primitive integer type,
1042    /// assuming that the value is finite and fits in that type.
1043    ///
1044    /// ```
1045    /// let value = 4.6_f64;
1046    /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
1047    /// assert_eq!(rounded, 4);
1048    ///
1049    /// let value = -128.9_f64;
1050    /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
1051    /// assert_eq!(rounded, i8::MIN);
1052    /// ```
1053    ///
1054    /// # Safety
1055    ///
1056    /// The value must:
1057    ///
1058    /// * Not be `NaN`
1059    /// * Not be infinite
1060    /// * Be representable in the return type `Int`, after truncating off its fractional part
1061    #[must_use = "this returns the result of the operation, \
1062                  without modifying the original"]
1063    #[stable(feature = "float_approx_unchecked_to", since = "1.44.0")]
1064    #[inline]
1065    pub unsafe fn to_int_unchecked<Int>(self) -> Int
1066    where
1067        Self: FloatToInt<Int>,
1068    {
1069        // SAFETY: the caller must uphold the safety contract for
1070        // `FloatToInt::to_int_unchecked`.
1071        unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
1072    }
1073
1074    /// Raw transmutation to `u64`.
1075    ///
1076    /// This is currently identical to `transmute::<f64, u64>(self)` on all platforms.
1077    ///
1078    /// See [`from_bits`](Self::from_bits) for some discussion of the
1079    /// portability of this operation (there are almost no issues).
1080    ///
1081    /// Note that this function is distinct from `as` casting, which attempts to
1082    /// preserve the *numeric* value, and not the bitwise value.
1083    ///
1084    /// # Examples
1085    ///
1086    /// ```
1087    /// assert!((1f64).to_bits() != 1f64 as u64); // to_bits() is not casting!
1088    /// assert_eq!((12.5f64).to_bits(), 0x4029000000000000);
1089    /// ```
1090    #[must_use = "this returns the result of the operation, \
1091                  without modifying the original"]
1092    #[stable(feature = "float_bits_conv", since = "1.20.0")]
1093    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1094    #[inline]
1095    pub const fn to_bits(self) -> u64 {
1096        // SAFETY: `u64` is a plain old datatype so we can always transmute to it.
1097        unsafe { mem::transmute(self) }
1098    }
1099
1100    /// Raw transmutation from `u64`.
1101    ///
1102    /// This is currently identical to `transmute::<u64, f64>(v)` on all platforms.
1103    /// It turns out this is incredibly portable, for two reasons:
1104    ///
1105    /// * Floats and Ints have the same endianness on all supported platforms.
1106    /// * IEEE 754 very precisely specifies the bit layout of floats.
1107    ///
1108    /// However there is one caveat: prior to the 2008 version of IEEE 754, how
1109    /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
1110    /// (notably x86 and ARM) picked the interpretation that was ultimately
1111    /// standardized in 2008, but some didn't (notably MIPS). As a result, all
1112    /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
1113    ///
1114    /// Rather than trying to preserve signaling-ness cross-platform, this
1115    /// implementation favors preserving the exact bits. This means that
1116    /// any payloads encoded in NaNs will be preserved even if the result of
1117    /// this method is sent over the network from an x86 machine to a MIPS one.
1118    ///
1119    /// If the results of this method are only manipulated by the same
1120    /// architecture that produced them, then there is no portability concern.
1121    ///
1122    /// If the input isn't NaN, then there is no portability concern.
1123    ///
1124    /// If you don't care about signaling-ness (very likely), then there is no
1125    /// portability concern.
1126    ///
1127    /// Note that this function is distinct from `as` casting, which attempts to
1128    /// preserve the *numeric* value, and not the bitwise value.
1129    ///
1130    /// # Examples
1131    ///
1132    /// ```
1133    /// let v = f64::from_bits(0x4029000000000000);
1134    /// assert_eq!(v, 12.5);
1135    /// ```
1136    #[stable(feature = "float_bits_conv", since = "1.20.0")]
1137    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1138    #[must_use]
1139    #[inline]
1140    pub const fn from_bits(v: u64) -> Self {
1141        // It turns out the safety issues with sNaN were overblown! Hooray!
1142        // SAFETY: `u64` is a plain old datatype so we can always transmute from it.
1143        unsafe { mem::transmute(v) }
1144    }
1145
1146    /// Returns the memory representation of this floating point number as a byte array in
1147    /// big-endian (network) byte order.
1148    ///
1149    /// See [`from_bits`](Self::from_bits) for some discussion of the
1150    /// portability of this operation (there are almost no issues).
1151    ///
1152    /// # Examples
1153    ///
1154    /// ```
1155    /// let bytes = 12.5f64.to_be_bytes();
1156    /// assert_eq!(bytes, [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1157    /// ```
1158    #[must_use = "this returns the result of the operation, \
1159                  without modifying the original"]
1160    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1161    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1162    #[inline]
1163    pub const fn to_be_bytes(self) -> [u8; 8] {
1164        self.to_bits().to_be_bytes()
1165    }
1166
1167    /// Returns the memory representation of this floating point number as a byte array in
1168    /// little-endian byte order.
1169    ///
1170    /// See [`from_bits`](Self::from_bits) for some discussion of the
1171    /// portability of this operation (there are almost no issues).
1172    ///
1173    /// # Examples
1174    ///
1175    /// ```
1176    /// let bytes = 12.5f64.to_le_bytes();
1177    /// assert_eq!(bytes, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]);
1178    /// ```
1179    #[must_use = "this returns the result of the operation, \
1180                  without modifying the original"]
1181    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1182    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1183    #[inline]
1184    pub const fn to_le_bytes(self) -> [u8; 8] {
1185        self.to_bits().to_le_bytes()
1186    }
1187
1188    /// Returns the memory representation of this floating point number as a byte array in
1189    /// native byte order.
1190    ///
1191    /// As the target platform's native endianness is used, portable code
1192    /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1193    ///
1194    /// [`to_be_bytes`]: f64::to_be_bytes
1195    /// [`to_le_bytes`]: f64::to_le_bytes
1196    ///
1197    /// See [`from_bits`](Self::from_bits) for some discussion of the
1198    /// portability of this operation (there are almost no issues).
1199    ///
1200    /// # Examples
1201    ///
1202    /// ```
1203    /// let bytes = 12.5f64.to_ne_bytes();
1204    /// assert_eq!(
1205    ///     bytes,
1206    ///     if cfg!(target_endian = "big") {
1207    ///         [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1208    ///     } else {
1209    ///         [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]
1210    ///     }
1211    /// );
1212    /// ```
1213    #[must_use = "this returns the result of the operation, \
1214                  without modifying the original"]
1215    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1216    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1217    #[inline]
1218    pub const fn to_ne_bytes(self) -> [u8; 8] {
1219        self.to_bits().to_ne_bytes()
1220    }
1221
1222    /// Creates a floating point value from its representation as a byte array in big endian.
1223    ///
1224    /// See [`from_bits`](Self::from_bits) for some discussion of the
1225    /// portability of this operation (there are almost no issues).
1226    ///
1227    /// # Examples
1228    ///
1229    /// ```
1230    /// let value = f64::from_be_bytes([0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1231    /// assert_eq!(value, 12.5);
1232    /// ```
1233    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1234    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1235    #[must_use]
1236    #[inline]
1237    pub const fn from_be_bytes(bytes: [u8; 8]) -> Self {
1238        Self::from_bits(u64::from_be_bytes(bytes))
1239    }
1240
1241    /// Creates a floating point value from its representation as a byte array in little endian.
1242    ///
1243    /// See [`from_bits`](Self::from_bits) for some discussion of the
1244    /// portability of this operation (there are almost no issues).
1245    ///
1246    /// # Examples
1247    ///
1248    /// ```
1249    /// let value = f64::from_le_bytes([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]);
1250    /// assert_eq!(value, 12.5);
1251    /// ```
1252    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1253    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1254    #[must_use]
1255    #[inline]
1256    pub const fn from_le_bytes(bytes: [u8; 8]) -> Self {
1257        Self::from_bits(u64::from_le_bytes(bytes))
1258    }
1259
1260    /// Creates a floating point value from its representation as a byte array in native endian.
1261    ///
1262    /// As the target platform's native endianness is used, portable code
1263    /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1264    /// appropriate instead.
1265    ///
1266    /// [`from_be_bytes`]: f64::from_be_bytes
1267    /// [`from_le_bytes`]: f64::from_le_bytes
1268    ///
1269    /// See [`from_bits`](Self::from_bits) for some discussion of the
1270    /// portability of this operation (there are almost no issues).
1271    ///
1272    /// # Examples
1273    ///
1274    /// ```
1275    /// let value = f64::from_ne_bytes(if cfg!(target_endian = "big") {
1276    ///     [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1277    /// } else {
1278    ///     [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]
1279    /// });
1280    /// assert_eq!(value, 12.5);
1281    /// ```
1282    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1283    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1284    #[must_use]
1285    #[inline]
1286    pub const fn from_ne_bytes(bytes: [u8; 8]) -> Self {
1287        Self::from_bits(u64::from_ne_bytes(bytes))
1288    }
1289
1290    /// Returns the ordering between `self` and `other`.
1291    ///
1292    /// Unlike the standard partial comparison between floating point numbers,
1293    /// this comparison always produces an ordering in accordance to
1294    /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1295    /// floating point standard. The values are ordered in the following sequence:
1296    ///
1297    /// - negative quiet NaN
1298    /// - negative signaling NaN
1299    /// - negative infinity
1300    /// - negative numbers
1301    /// - negative subnormal numbers
1302    /// - negative zero
1303    /// - positive zero
1304    /// - positive subnormal numbers
1305    /// - positive numbers
1306    /// - positive infinity
1307    /// - positive signaling NaN
1308    /// - positive quiet NaN.
1309    ///
1310    /// The ordering established by this function does not always agree with the
1311    /// [`PartialOrd`] and [`PartialEq`] implementations of `f64`. For example,
1312    /// they consider negative and positive zero equal, while `total_cmp`
1313    /// doesn't.
1314    ///
1315    /// The interpretation of the signaling NaN bit follows the definition in
1316    /// the IEEE 754 standard, which may not match the interpretation by some of
1317    /// the older, non-conformant (e.g. MIPS) hardware implementations.
1318    ///
1319    /// # Example
1320    ///
1321    /// ```
1322    /// struct GoodBoy {
1323    ///     name: String,
1324    ///     weight: f64,
1325    /// }
1326    ///
1327    /// let mut bois = vec![
1328    ///     GoodBoy { name: "Pucci".to_owned(), weight: 0.1 },
1329    ///     GoodBoy { name: "Woofer".to_owned(), weight: 99.0 },
1330    ///     GoodBoy { name: "Yapper".to_owned(), weight: 10.0 },
1331    ///     GoodBoy { name: "Chonk".to_owned(), weight: f64::INFINITY },
1332    ///     GoodBoy { name: "Abs. Unit".to_owned(), weight: f64::NAN },
1333    ///     GoodBoy { name: "Floaty".to_owned(), weight: -5.0 },
1334    /// ];
1335    ///
1336    /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1337    ///
1338    /// // `f64::NAN` could be positive or negative, which will affect the sort order.
1339    /// if f64::NAN.is_sign_negative() {
1340    ///     assert!(bois.into_iter().map(|b| b.weight)
1341    ///         .zip([f64::NAN, -5.0, 0.1, 10.0, 99.0, f64::INFINITY].iter())
1342    ///         .all(|(a, b)| a.to_bits() == b.to_bits()))
1343    /// } else {
1344    ///     assert!(bois.into_iter().map(|b| b.weight)
1345    ///         .zip([-5.0, 0.1, 10.0, 99.0, f64::INFINITY, f64::NAN].iter())
1346    ///         .all(|(a, b)| a.to_bits() == b.to_bits()))
1347    /// }
1348    /// ```
1349    #[stable(feature = "total_cmp", since = "1.62.0")]
1350    #[must_use]
1351    #[inline]
1352    pub fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1353        let mut left = self.to_bits() as i64;
1354        let mut right = other.to_bits() as i64;
1355
1356        // In case of negatives, flip all the bits except the sign
1357        // to achieve a similar layout as two's complement integers
1358        //
1359        // Why does this work? IEEE 754 floats consist of three fields:
1360        // Sign bit, exponent and mantissa. The set of exponent and mantissa
1361        // fields as a whole have the property that their bitwise order is
1362        // equal to the numeric magnitude where the magnitude is defined.
1363        // The magnitude is not normally defined on NaN values, but
1364        // IEEE 754 totalOrder defines the NaN values also to follow the
1365        // bitwise order. This leads to order explained in the doc comment.
1366        // However, the representation of magnitude is the same for negative
1367        // and positive numbers – only the sign bit is different.
1368        // To easily compare the floats as signed integers, we need to
1369        // flip the exponent and mantissa bits in case of negative numbers.
1370        // We effectively convert the numbers to "two's complement" form.
1371        //
1372        // To do the flipping, we construct a mask and XOR against it.
1373        // We branchlessly calculate an "all-ones except for the sign bit"
1374        // mask from negative-signed values: right shifting sign-extends
1375        // the integer, so we "fill" the mask with sign bits, and then
1376        // convert to unsigned to push one more zero bit.
1377        // On positive values, the mask is all zeros, so it's a no-op.
1378        left ^= (((left >> 63) as u64) >> 1) as i64;
1379        right ^= (((right >> 63) as u64) >> 1) as i64;
1380
1381        left.cmp(&right)
1382    }
1383
1384    /// Restrict a value to a certain interval unless it is NaN.
1385    ///
1386    /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1387    /// less than `min`. Otherwise this returns `self`.
1388    ///
1389    /// Note that this function returns NaN if the initial value was NaN as
1390    /// well.
1391    ///
1392    /// # Panics
1393    ///
1394    /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1395    ///
1396    /// # Examples
1397    ///
1398    /// ```
1399    /// assert!((-3.0f64).clamp(-2.0, 1.0) == -2.0);
1400    /// assert!((0.0f64).clamp(-2.0, 1.0) == 0.0);
1401    /// assert!((2.0f64).clamp(-2.0, 1.0) == 1.0);
1402    /// assert!((f64::NAN).clamp(-2.0, 1.0).is_nan());
1403    /// ```
1404    #[must_use = "method returns a new number and does not mutate the original value"]
1405    #[stable(feature = "clamp", since = "1.50.0")]
1406    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1407    #[inline]
1408    pub const fn clamp(mut self, min: f64, max: f64) -> f64 {
1409        const_assert!(
1410            min <= max,
1411            "min > max, or either was NaN",
1412            "min > max, or either was NaN. min = {min:?}, max = {max:?}",
1413            min: f64,
1414            max: f64,
1415        );
1416
1417        if self < min {
1418            self = min;
1419        }
1420        if self > max {
1421            self = max;
1422        }
1423        self
1424    }
1425
1426    /// Computes the absolute value of `self`.
1427    ///
1428    /// This function always returns the precise result.
1429    ///
1430    /// # Examples
1431    ///
1432    /// ```
1433    /// let x = 3.5_f64;
1434    /// let y = -3.5_f64;
1435    ///
1436    /// assert_eq!(x.abs(), x);
1437    /// assert_eq!(y.abs(), -y);
1438    ///
1439    /// assert!(f64::NAN.abs().is_nan());
1440    /// ```
1441    #[must_use = "method returns a new number and does not mutate the original value"]
1442    #[stable(feature = "rust1", since = "1.0.0")]
1443    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1444    #[inline]
1445    pub const fn abs(self) -> f64 {
1446        // SAFETY: this is actually a safe intrinsic
1447        unsafe { intrinsics::fabsf64(self) }
1448    }
1449
1450    /// Returns a number that represents the sign of `self`.
1451    ///
1452    /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
1453    /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
1454    /// - NaN if the number is NaN
1455    ///
1456    /// # Examples
1457    ///
1458    /// ```
1459    /// let f = 3.5_f64;
1460    ///
1461    /// assert_eq!(f.signum(), 1.0);
1462    /// assert_eq!(f64::NEG_INFINITY.signum(), -1.0);
1463    ///
1464    /// assert!(f64::NAN.signum().is_nan());
1465    /// ```
1466    #[must_use = "method returns a new number and does not mutate the original value"]
1467    #[stable(feature = "rust1", since = "1.0.0")]
1468    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1469    #[inline]
1470    pub const fn signum(self) -> f64 {
1471        if self.is_nan() { Self::NAN } else { 1.0_f64.copysign(self) }
1472    }
1473
1474    /// Returns a number composed of the magnitude of `self` and the sign of
1475    /// `sign`.
1476    ///
1477    /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`.
1478    /// If `self` is a NaN, then a NaN with the same payload as `self` and the sign bit of `sign` is
1479    /// returned.
1480    ///
1481    /// If `sign` is a NaN, then this operation will still carry over its sign into the result. Note
1482    /// that IEEE 754 doesn't assign any meaning to the sign bit in case of a NaN, and as Rust
1483    /// doesn't guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the
1484    /// result of `copysign` with `sign` being a NaN might produce an unexpected or non-portable
1485    /// result. See the [specification of NaN bit patterns](primitive@f32#nan-bit-patterns) for more
1486    /// info.
1487    ///
1488    /// # Examples
1489    ///
1490    /// ```
1491    /// let f = 3.5_f64;
1492    ///
1493    /// assert_eq!(f.copysign(0.42), 3.5_f64);
1494    /// assert_eq!(f.copysign(-0.42), -3.5_f64);
1495    /// assert_eq!((-f).copysign(0.42), 3.5_f64);
1496    /// assert_eq!((-f).copysign(-0.42), -3.5_f64);
1497    ///
1498    /// assert!(f64::NAN.copysign(1.0).is_nan());
1499    /// ```
1500    #[must_use = "method returns a new number and does not mutate the original value"]
1501    #[stable(feature = "copysign", since = "1.35.0")]
1502    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1503    #[inline]
1504    pub const fn copysign(self, sign: f64) -> f64 {
1505        // SAFETY: this is actually a safe intrinsic
1506        unsafe { intrinsics::copysignf64(self, sign) }
1507    }
1508
1509    /// Float addition that allows optimizations based on algebraic rules.
1510    ///
1511    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1512    #[must_use = "method returns a new number and does not mutate the original value"]
1513    #[unstable(feature = "float_algebraic", issue = "136469")]
1514    #[inline]
1515    pub fn algebraic_add(self, rhs: f64) -> f64 {
1516        intrinsics::fadd_algebraic(self, rhs)
1517    }
1518
1519    /// Float subtraction that allows optimizations based on algebraic rules.
1520    ///
1521    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1522    #[must_use = "method returns a new number and does not mutate the original value"]
1523    #[unstable(feature = "float_algebraic", issue = "136469")]
1524    #[inline]
1525    pub fn algebraic_sub(self, rhs: f64) -> f64 {
1526        intrinsics::fsub_algebraic(self, rhs)
1527    }
1528
1529    /// Float multiplication that allows optimizations based on algebraic rules.
1530    ///
1531    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1532    #[must_use = "method returns a new number and does not mutate the original value"]
1533    #[unstable(feature = "float_algebraic", issue = "136469")]
1534    #[inline]
1535    pub fn algebraic_mul(self, rhs: f64) -> f64 {
1536        intrinsics::fmul_algebraic(self, rhs)
1537    }
1538
1539    /// Float division that allows optimizations based on algebraic rules.
1540    ///
1541    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1542    #[must_use = "method returns a new number and does not mutate the original value"]
1543    #[unstable(feature = "float_algebraic", issue = "136469")]
1544    #[inline]
1545    pub fn algebraic_div(self, rhs: f64) -> f64 {
1546        intrinsics::fdiv_algebraic(self, rhs)
1547    }
1548
1549    /// Float remainder that allows optimizations based on algebraic rules.
1550    ///
1551    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1552    #[must_use = "method returns a new number and does not mutate the original value"]
1553    #[unstable(feature = "float_algebraic", issue = "136469")]
1554    #[inline]
1555    pub fn algebraic_rem(self, rhs: f64) -> f64 {
1556        intrinsics::frem_algebraic(self, rhs)
1557    }
1558}