Skip to main content

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")]
280#[rustc_diagnostic_item = "f64_consts_mod"]
281pub mod consts {
282    // FIXME: replace with mathematical constants from cmath.
283
284    /// Archimedes' constant (π)
285    #[stable(feature = "rust1", since = "1.0.0")]
286    pub const PI: f64 = 3.14159265358979323846264338327950288_f64;
287
288    /// The full circle constant (τ)
289    ///
290    /// Equal to 2π.
291    #[stable(feature = "tau_constant", since = "1.47.0")]
292    pub const TAU: f64 = 6.28318530717958647692528676655900577_f64;
293
294    /// The golden ratio (φ)
295    #[stable(feature = "euler_gamma_golden_ratio", since = "1.94.0")]
296    pub const GOLDEN_RATIO: f64 = 1.618033988749894848204586834365638118_f64;
297
298    /// The Euler-Mascheroni constant (γ)
299    #[stable(feature = "euler_gamma_golden_ratio", since = "1.94.0")]
300    pub const EULER_GAMMA: f64 = 0.577215664901532860606512090082402431_f64;
301
302    /// π/2
303    #[stable(feature = "rust1", since = "1.0.0")]
304    pub const FRAC_PI_2: f64 = 1.57079632679489661923132169163975144_f64;
305
306    /// π/3
307    #[stable(feature = "rust1", since = "1.0.0")]
308    pub const FRAC_PI_3: f64 = 1.04719755119659774615421446109316763_f64;
309
310    /// π/4
311    #[stable(feature = "rust1", since = "1.0.0")]
312    pub const FRAC_PI_4: f64 = 0.785398163397448309615660845819875721_f64;
313
314    /// π/6
315    #[stable(feature = "rust1", since = "1.0.0")]
316    pub const FRAC_PI_6: f64 = 0.52359877559829887307710723054658381_f64;
317
318    /// π/8
319    #[stable(feature = "rust1", since = "1.0.0")]
320    pub const FRAC_PI_8: f64 = 0.39269908169872415480783042290993786_f64;
321
322    /// 1/π
323    #[stable(feature = "rust1", since = "1.0.0")]
324    pub const FRAC_1_PI: f64 = 0.318309886183790671537767526745028724_f64;
325
326    /// 1/sqrt(π)
327    #[unstable(feature = "more_float_constants", issue = "146939")]
328    pub const FRAC_1_SQRT_PI: f64 = 0.564189583547756286948079451560772586_f64;
329
330    /// 1/sqrt(2π)
331    #[doc(alias = "FRAC_1_SQRT_TAU")]
332    #[unstable(feature = "more_float_constants", issue = "146939")]
333    pub const FRAC_1_SQRT_2PI: f64 = 0.398942280401432677939946059934381868_f64;
334
335    /// 2/π
336    #[stable(feature = "rust1", since = "1.0.0")]
337    pub const FRAC_2_PI: f64 = 0.636619772367581343075535053490057448_f64;
338
339    /// 2/sqrt(π)
340    #[stable(feature = "rust1", since = "1.0.0")]
341    pub const FRAC_2_SQRT_PI: f64 = 1.12837916709551257389615890312154517_f64;
342
343    /// sqrt(2)
344    #[stable(feature = "rust1", since = "1.0.0")]
345    pub const SQRT_2: f64 = 1.41421356237309504880168872420969808_f64;
346
347    /// 1/sqrt(2)
348    #[stable(feature = "rust1", since = "1.0.0")]
349    pub const FRAC_1_SQRT_2: f64 = 0.707106781186547524400844362104849039_f64;
350
351    /// sqrt(3)
352    #[unstable(feature = "more_float_constants", issue = "146939")]
353    pub const SQRT_3: f64 = 1.732050807568877293527446341505872367_f64;
354
355    /// 1/sqrt(3)
356    #[unstable(feature = "more_float_constants", issue = "146939")]
357    pub const FRAC_1_SQRT_3: f64 = 0.577350269189625764509148780501957456_f64;
358
359    /// sqrt(5)
360    #[unstable(feature = "more_float_constants", issue = "146939")]
361    pub const SQRT_5: f64 = 2.23606797749978969640917366873127623_f64;
362
363    /// 1/sqrt(5)
364    #[unstable(feature = "more_float_constants", issue = "146939")]
365    pub const FRAC_1_SQRT_5: f64 = 0.44721359549995793928183473374625524_f64;
366
367    /// Euler's number (e)
368    #[stable(feature = "rust1", since = "1.0.0")]
369    pub const E: f64 = 2.71828182845904523536028747135266250_f64;
370
371    /// log<sub>2</sub>(10)
372    #[stable(feature = "extra_log_consts", since = "1.43.0")]
373    pub const LOG2_10: f64 = 3.32192809488736234787031942948939018_f64;
374
375    /// log<sub>2</sub>(e)
376    #[stable(feature = "rust1", since = "1.0.0")]
377    pub const LOG2_E: f64 = 1.44269504088896340735992468100189214_f64;
378
379    /// log<sub>10</sub>(2)
380    #[stable(feature = "extra_log_consts", since = "1.43.0")]
381    pub const LOG10_2: f64 = 0.301029995663981195213738894724493027_f64;
382
383    /// log<sub>10</sub>(e)
384    #[stable(feature = "rust1", since = "1.0.0")]
385    pub const LOG10_E: f64 = 0.434294481903251827651128918916605082_f64;
386
387    /// ln(2)
388    #[stable(feature = "rust1", since = "1.0.0")]
389    pub const LN_2: f64 = 0.693147180559945309417232121458176568_f64;
390
391    /// ln(10)
392    #[stable(feature = "rust1", since = "1.0.0")]
393    pub const LN_10: f64 = 2.30258509299404568401799145468436421_f64;
394}
395
396#[doc(test(attr(allow(unused_features))))]
397impl f64 {
398    /// The radix or base of the internal representation of `f64`.
399    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
400    pub const RADIX: u32 = 2;
401
402    /// The size of this float type in bits.
403    #[unstable(feature = "float_bits_const", issue = "151073")]
404    pub const BITS: u32 = 64;
405
406    /// Number of significant digits in base 2.
407    ///
408    /// Note that the size of the mantissa in the bitwise representation is one
409    /// smaller than this since the leading 1 is not stored explicitly.
410    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
411    pub const MANTISSA_DIGITS: u32 = 53;
412    /// Approximate number of significant digits in base 10.
413    ///
414    /// This is the maximum <i>x</i> such that any decimal number with <i>x</i>
415    /// significant digits can be converted to `f64` and back without loss.
416    ///
417    /// Equal to floor(log<sub>10</sub>&nbsp;2<sup>[`MANTISSA_DIGITS`]&nbsp;&minus;&nbsp;1</sup>).
418    ///
419    /// [`MANTISSA_DIGITS`]: f64::MANTISSA_DIGITS
420    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
421    pub const DIGITS: u32 = 15;
422
423    /// [Machine epsilon] value for `f64`.
424    ///
425    /// This is the difference between `1.0` and the next larger representable number.
426    ///
427    /// Equal to 2<sup>1&nbsp;&minus;&nbsp;[`MANTISSA_DIGITS`]</sup>.
428    ///
429    /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
430    /// [`MANTISSA_DIGITS`]: f64::MANTISSA_DIGITS
431    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
432    #[rustc_diagnostic_item = "f64_epsilon"]
433    pub const EPSILON: f64 = 2.2204460492503131e-16_f64;
434
435    /// Smallest finite `f64` value.
436    ///
437    /// Equal to &minus;[`MAX`].
438    ///
439    /// [`MAX`]: f64::MAX
440    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
441    pub const MIN: f64 = -1.7976931348623157e+308_f64;
442    /// Smallest positive normal `f64` value.
443    ///
444    /// Equal to 2<sup>[`MIN_EXP`]&nbsp;&minus;&nbsp;1</sup>.
445    ///
446    /// [`MIN_EXP`]: f64::MIN_EXP
447    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
448    pub const MIN_POSITIVE: f64 = 2.2250738585072014e-308_f64;
449    /// Largest finite `f64` value.
450    ///
451    /// Equal to
452    /// (1&nbsp;&minus;&nbsp;2<sup>&minus;[`MANTISSA_DIGITS`]</sup>)&nbsp;2<sup>[`MAX_EXP`]</sup>.
453    ///
454    /// [`MANTISSA_DIGITS`]: f64::MANTISSA_DIGITS
455    /// [`MAX_EXP`]: f64::MAX_EXP
456    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
457    pub const MAX: f64 = 1.7976931348623157e+308_f64;
458
459    /// One greater than the minimum possible *normal* power of 2 exponent
460    /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).
461    ///
462    /// This corresponds to the exact minimum possible *normal* power of 2 exponent
463    /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).
464    /// In other words, all normal numbers representable by this type are
465    /// greater than or equal to 0.5&nbsp;×&nbsp;2<sup><i>MIN_EXP</i></sup>.
466    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
467    pub const MIN_EXP: i32 = -1021;
468    /// One greater than the maximum possible power of 2 exponent
469    /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).
470    ///
471    /// This corresponds to the exact maximum possible power of 2 exponent
472    /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).
473    /// In other words, all numbers representable by this type are
474    /// strictly less than 2<sup><i>MAX_EXP</i></sup>.
475    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
476    pub const MAX_EXP: i32 = 1024;
477
478    /// Minimum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
479    ///
480    /// Equal to ceil(log<sub>10</sub>&nbsp;[`MIN_POSITIVE`]).
481    ///
482    /// [`MIN_POSITIVE`]: f64::MIN_POSITIVE
483    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
484    pub const MIN_10_EXP: i32 = -307;
485    /// Maximum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
486    ///
487    /// Equal to floor(log<sub>10</sub>&nbsp;[`MAX`]).
488    ///
489    /// [`MAX`]: f64::MAX
490    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
491    pub const MAX_10_EXP: i32 = 308;
492
493    /// Not a Number (NaN).
494    ///
495    /// Note that IEEE 754 doesn't define just a single NaN value; a plethora of bit patterns are
496    /// considered to be NaN. Furthermore, the standard makes a difference between a "signaling" and
497    /// a "quiet" NaN, and allows inspecting its "payload" (the unspecified bits in the bit pattern)
498    /// and its sign. See the [specification of NaN bit patterns](f32#nan-bit-patterns) for more
499    /// info.
500    ///
501    /// This constant is guaranteed to be a quiet NaN (on targets that follow the Rust assumptions
502    /// that the quiet/signaling bit being set to 1 indicates a quiet NaN). Beyond that, nothing is
503    /// guaranteed about the specific bit pattern chosen here: both payload and sign are arbitrary.
504    /// The concrete bit pattern may change across Rust versions and target platforms.
505    #[rustc_diagnostic_item = "f64_nan"]
506    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
507    #[allow(clippy::eq_op)]
508    pub const NAN: f64 = 0.0_f64 / 0.0_f64;
509    /// Infinity (∞).
510    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
511    pub const INFINITY: f64 = 1.0_f64 / 0.0_f64;
512    /// Negative infinity (−∞).
513    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
514    pub const NEG_INFINITY: f64 = -1.0_f64 / 0.0_f64;
515
516    /// Maximum integer that can be represented exactly in an [`f64`] value,
517    /// with no other integer converting to the same floating point value.
518    ///
519    /// For an integer `x` which satisfies `MIN_EXACT_INTEGER <= x <= MAX_EXACT_INTEGER`,
520    /// there is a "one-to-one" mapping between [`i64`] and [`f64`] values.
521    /// `MAX_EXACT_INTEGER + 1` also converts losslessly to [`f64`] and back to
522    /// [`i64`], but `MAX_EXACT_INTEGER + 2` converts to the same [`f64`] value
523    /// (and back to `MAX_EXACT_INTEGER + 1` as an integer) so there is not a
524    /// "one-to-one" mapping.
525    ///
526    /// [`MAX_EXACT_INTEGER`]: f64::MAX_EXACT_INTEGER
527    /// [`MIN_EXACT_INTEGER`]: f64::MIN_EXACT_INTEGER
528    /// ```
529    /// #![feature(float_exact_integer_constants)]
530    /// # // FIXME(#152635): Float rounding on `i586` does not adhere to IEEE 754
531    /// # #[cfg(not(all(target_arch = "x86", not(target_feature = "sse"))))] {
532    /// let max_exact_int = f64::MAX_EXACT_INTEGER;
533    /// assert_eq!(max_exact_int, max_exact_int as f64 as i64);
534    /// assert_eq!(max_exact_int + 1, (max_exact_int + 1) as f64 as i64);
535    /// assert_ne!(max_exact_int + 2, (max_exact_int + 2) as f64 as i64);
536    ///
537    /// // Beyond `f64::MAX_EXACT_INTEGER`, multiple integers can map to one float value
538    /// assert_eq!((max_exact_int + 1) as f64, (max_exact_int + 2) as f64);
539    /// # }
540    /// ```
541    #[unstable(feature = "float_exact_integer_constants", issue = "152466")]
542    pub const MAX_EXACT_INTEGER: i64 = (1 << Self::MANTISSA_DIGITS) - 1;
543
544    /// Minimum integer that can be represented exactly in an [`f64`] value,
545    /// with no other integer converting to the same floating point value.
546    ///
547    /// For an integer `x` which satisfies `MIN_EXACT_INTEGER <= x <= MAX_EXACT_INTEGER`,
548    /// there is a "one-to-one" mapping between [`i64`] and [`f64`] values.
549    /// `MAX_EXACT_INTEGER + 1` also converts losslessly to [`f64`] and back to
550    /// [`i64`], but `MAX_EXACT_INTEGER + 2` converts to the same [`f64`] value
551    /// (and back to `MAX_EXACT_INTEGER + 1` as an integer) so there is not a
552    /// "one-to-one" mapping.
553    ///
554    /// This constant is equivalent to `-MAX_EXACT_INTEGER`.
555    ///
556    /// [`MAX_EXACT_INTEGER`]: f64::MAX_EXACT_INTEGER
557    /// [`MIN_EXACT_INTEGER`]: f64::MIN_EXACT_INTEGER
558    /// ```
559    /// #![feature(float_exact_integer_constants)]
560    /// # // FIXME(#152635): Float rounding on `i586` does not adhere to IEEE 754
561    /// # #[cfg(not(all(target_arch = "x86", not(target_feature = "sse"))))] {
562    /// let min_exact_int = f64::MIN_EXACT_INTEGER;
563    /// assert_eq!(min_exact_int, min_exact_int as f64 as i64);
564    /// assert_eq!(min_exact_int - 1, (min_exact_int - 1) as f64 as i64);
565    /// assert_ne!(min_exact_int - 2, (min_exact_int - 2) as f64 as i64);
566    ///
567    /// // Below `f64::MIN_EXACT_INTEGER`, multiple integers can map to one float value
568    /// assert_eq!((min_exact_int - 1) as f64, (min_exact_int - 2) as f64);
569    /// # }
570    /// ```
571    #[unstable(feature = "float_exact_integer_constants", issue = "152466")]
572    pub const MIN_EXACT_INTEGER: i64 = -Self::MAX_EXACT_INTEGER;
573
574    /// The mask of the bit used to encode the sign of an [`f64`].
575    ///
576    /// This bit is set when the sign is negative and unset when the sign is
577    /// positive.
578    /// If you only need to check whether a value is positive or negative,
579    /// [`is_sign_positive`] or [`is_sign_negative`] can be used.
580    ///
581    /// [`is_sign_positive`]: f64::is_sign_positive
582    /// [`is_sign_negative`]: f64::is_sign_negative
583    /// ```rust
584    /// #![feature(float_masks)]
585    /// let sign_mask = f64::SIGN_MASK;
586    /// let a = 1.6552f64;
587    /// let a_bits = a.to_bits();
588    ///
589    /// assert_eq!(a_bits & sign_mask, 0x0);
590    /// assert_eq!(f64::from_bits(a_bits ^ sign_mask), -a);
591    /// assert_eq!(sign_mask, (-0.0f64).to_bits());
592    /// ```
593    #[unstable(feature = "float_masks", issue = "154064")]
594    pub const SIGN_MASK: u64 = 0x8000_0000_0000_0000;
595
596    /// The mask of the bits used to encode the exponent of an [`f64`].
597    ///
598    /// Note that the exponent is stored as a biased value, with a bias of 1024 for `f64`.
599    ///
600    /// ```rust
601    /// #![feature(float_masks)]
602    /// fn get_exp(a: f64) -> i64 {
603    ///     let bias = 1023;
604    ///     let biased = a.to_bits() & f64::EXPONENT_MASK;
605    ///     (biased >> (f64::MANTISSA_DIGITS - 1)).cast_signed() - bias
606    /// }
607    ///
608    /// assert_eq!(get_exp(0.5), -1);
609    /// assert_eq!(get_exp(1.0), 0);
610    /// assert_eq!(get_exp(2.0), 1);
611    /// assert_eq!(get_exp(4.0), 2);
612    /// ```
613    #[unstable(feature = "float_masks", issue = "154064")]
614    pub const EXPONENT_MASK: u64 = 0x7ff0_0000_0000_0000;
615
616    /// The mask of the bits used to encode the mantissa of an [`f64`].
617    ///
618    /// ```rust
619    /// #![feature(float_masks)]
620    /// let mantissa_mask = f64::MANTISSA_MASK;
621    ///
622    /// assert_eq!(0f64.to_bits() & mantissa_mask, 0x0);
623    /// assert_eq!(1f64.to_bits() & mantissa_mask, 0x0);
624    ///
625    /// // multiplying a finite value by a power of 2 doesn't change its mantissa
626    /// // unless the result or initial value is not normal.
627    /// let a = 1.6552f64;
628    /// let b = 4.0 * a;
629    /// assert_eq!(a.to_bits() & mantissa_mask, b.to_bits() & mantissa_mask);
630    ///
631    /// // The maximum and minimum values have a saturated significand
632    /// assert_eq!(f64::MAX.to_bits() & f64::MANTISSA_MASK, f64::MANTISSA_MASK);
633    /// assert_eq!(f64::MIN.to_bits() & f64::MANTISSA_MASK, f64::MANTISSA_MASK);
634    /// ```
635    #[unstable(feature = "float_masks", issue = "154064")]
636    pub const MANTISSA_MASK: u64 = 0x000f_ffff_ffff_ffff;
637
638    /// Minimum representable positive value (min subnormal)
639    const TINY_BITS: u64 = 0x1;
640
641    /// Minimum representable negative value (min negative subnormal)
642    const NEG_TINY_BITS: u64 = Self::TINY_BITS | Self::SIGN_MASK;
643
644    /// Returns `true` if this value is NaN.
645    ///
646    /// ```
647    /// let nan = f64::NAN;
648    /// let f = 7.0_f64;
649    ///
650    /// assert!(nan.is_nan());
651    /// assert!(!f.is_nan());
652    /// ```
653    #[must_use]
654    #[stable(feature = "rust1", since = "1.0.0")]
655    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
656    #[inline]
657    #[allow(clippy::eq_op)] // > if you intended to check if the operand is NaN, use `.is_nan()` instead :)
658    pub const fn is_nan(self) -> bool {
659        self != self
660    }
661
662    /// Returns `true` if this value is positive infinity or negative infinity, and
663    /// `false` otherwise.
664    ///
665    /// ```
666    /// let f = 7.0f64;
667    /// let inf = f64::INFINITY;
668    /// let neg_inf = f64::NEG_INFINITY;
669    /// let nan = f64::NAN;
670    ///
671    /// assert!(!f.is_infinite());
672    /// assert!(!nan.is_infinite());
673    ///
674    /// assert!(inf.is_infinite());
675    /// assert!(neg_inf.is_infinite());
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_infinite(self) -> bool {
682        // Getting clever with transmutation can result in incorrect answers on some FPUs
683        // FIXME: alter the Rust <-> Rust calling convention to prevent this problem.
684        // See https://github.com/rust-lang/rust/issues/72327
685        (self == f64::INFINITY) | (self == f64::NEG_INFINITY)
686    }
687
688    /// Returns `true` if this number is neither infinite nor NaN.
689    ///
690    /// ```
691    /// let f = 7.0f64;
692    /// let inf: f64 = f64::INFINITY;
693    /// let neg_inf: f64 = f64::NEG_INFINITY;
694    /// let nan: f64 = f64::NAN;
695    ///
696    /// assert!(f.is_finite());
697    ///
698    /// assert!(!nan.is_finite());
699    /// assert!(!inf.is_finite());
700    /// assert!(!neg_inf.is_finite());
701    /// ```
702    #[must_use]
703    #[stable(feature = "rust1", since = "1.0.0")]
704    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
705    #[inline]
706    pub const fn is_finite(self) -> bool {
707        // There's no need to handle NaN separately: if self is NaN,
708        // the comparison is not true, exactly as desired.
709        self.abs() < Self::INFINITY
710    }
711
712    /// Returns `true` if the number is [subnormal].
713    ///
714    /// ```
715    /// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308_f64
716    /// let max = f64::MAX;
717    /// let lower_than_min = 1.0e-308_f64;
718    /// let zero = 0.0_f64;
719    ///
720    /// assert!(!min.is_subnormal());
721    /// assert!(!max.is_subnormal());
722    ///
723    /// assert!(!zero.is_subnormal());
724    /// assert!(!f64::NAN.is_subnormal());
725    /// assert!(!f64::INFINITY.is_subnormal());
726    /// // Values between `0` and `min` are Subnormal.
727    /// assert!(lower_than_min.is_subnormal());
728    /// ```
729    /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
730    #[must_use]
731    #[stable(feature = "is_subnormal", since = "1.53.0")]
732    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
733    #[inline]
734    pub const fn is_subnormal(self) -> bool {
735        matches!(self.classify(), FpCategory::Subnormal)
736    }
737
738    /// Returns `true` if the number is neither zero, infinite,
739    /// [subnormal], or NaN.
740    ///
741    /// ```
742    /// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308f64
743    /// let max = f64::MAX;
744    /// let lower_than_min = 1.0e-308_f64;
745    /// let zero = 0.0f64;
746    ///
747    /// assert!(min.is_normal());
748    /// assert!(max.is_normal());
749    ///
750    /// assert!(!zero.is_normal());
751    /// assert!(!f64::NAN.is_normal());
752    /// assert!(!f64::INFINITY.is_normal());
753    /// // Values between `0` and `min` are Subnormal.
754    /// assert!(!lower_than_min.is_normal());
755    /// ```
756    /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
757    #[must_use]
758    #[stable(feature = "rust1", since = "1.0.0")]
759    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
760    #[inline]
761    pub const fn is_normal(self) -> bool {
762        matches!(self.classify(), FpCategory::Normal)
763    }
764
765    /// Returns the floating point category of the number. If only one property
766    /// is going to be tested, it is generally faster to use the specific
767    /// predicate instead.
768    ///
769    /// ```
770    /// use std::num::FpCategory;
771    ///
772    /// let num = 12.4_f64;
773    /// let inf = f64::INFINITY;
774    ///
775    /// assert_eq!(num.classify(), FpCategory::Normal);
776    /// assert_eq!(inf.classify(), FpCategory::Infinite);
777    /// ```
778    #[stable(feature = "rust1", since = "1.0.0")]
779    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
780    #[must_use]
781    pub const fn classify(self) -> FpCategory {
782        // We used to have complicated logic here that avoids the simple bit-based tests to work
783        // around buggy codegen for x87 targets (see
784        // https://github.com/rust-lang/rust/issues/114479). However, some LLVM versions later, none
785        // of our tests is able to find any difference between the complicated and the naive
786        // version, so now we are back to the naive version.
787        let b = self.to_bits();
788        match (b & Self::MANTISSA_MASK, b & Self::EXPONENT_MASK) {
789            (0, Self::EXPONENT_MASK) => FpCategory::Infinite,
790            (_, Self::EXPONENT_MASK) => FpCategory::Nan,
791            (0, 0) => FpCategory::Zero,
792            (_, 0) => FpCategory::Subnormal,
793            _ => FpCategory::Normal,
794        }
795    }
796
797    /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with
798    /// positive sign bit and positive infinity.
799    ///
800    /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
801    /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
802    /// conserved over arithmetic operations, the result of `is_sign_positive` on
803    /// a NaN might produce an unexpected or non-portable result. See the [specification
804    /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == 1.0`
805    /// if you need fully portable behavior (will return `false` for all NaNs).
806    ///
807    /// ```
808    /// let f = 7.0_f64;
809    /// let g = -7.0_f64;
810    ///
811    /// assert!(f.is_sign_positive());
812    /// assert!(!g.is_sign_positive());
813    /// ```
814    #[must_use]
815    #[stable(feature = "rust1", since = "1.0.0")]
816    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
817    #[inline]
818    pub const fn is_sign_positive(self) -> bool {
819        !self.is_sign_negative()
820    }
821
822    #[must_use]
823    #[stable(feature = "rust1", since = "1.0.0")]
824    #[deprecated(since = "1.0.0", note = "renamed to is_sign_positive")]
825    #[inline]
826    #[doc(hidden)]
827    pub fn is_positive(self) -> bool {
828        self.is_sign_positive()
829    }
830
831    /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with
832    /// negative sign bit and negative infinity.
833    ///
834    /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
835    /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
836    /// conserved over arithmetic operations, the result of `is_sign_negative` on
837    /// a NaN might produce an unexpected or non-portable result. See the [specification
838    /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == -1.0`
839    /// if you need fully portable behavior (will return `false` for all NaNs).
840    ///
841    /// ```
842    /// let f = 7.0_f64;
843    /// let g = -7.0_f64;
844    ///
845    /// assert!(!f.is_sign_negative());
846    /// assert!(g.is_sign_negative());
847    /// ```
848    #[must_use]
849    #[stable(feature = "rust1", since = "1.0.0")]
850    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
851    #[inline]
852    pub const fn is_sign_negative(self) -> bool {
853        // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
854        // applies to zeros and NaNs as well.
855        self.to_bits() & Self::SIGN_MASK != 0
856    }
857
858    #[must_use]
859    #[stable(feature = "rust1", since = "1.0.0")]
860    #[deprecated(since = "1.0.0", note = "renamed to is_sign_negative")]
861    #[inline]
862    #[doc(hidden)]
863    pub fn is_negative(self) -> bool {
864        self.is_sign_negative()
865    }
866
867    /// Returns the least number greater than `self`.
868    ///
869    /// Let `TINY` be the smallest representable positive `f64`. Then,
870    ///  - if `self.is_nan()`, this returns `self`;
871    ///  - if `self` is [`NEG_INFINITY`], this returns [`MIN`];
872    ///  - if `self` is `-TINY`, this returns -0.0;
873    ///  - if `self` is -0.0 or +0.0, this returns `TINY`;
874    ///  - if `self` is [`MAX`] or [`INFINITY`], this returns [`INFINITY`];
875    ///  - otherwise the unique least value greater than `self` is returned.
876    ///
877    /// The identity `x.next_up() == -(-x).next_down()` holds for all non-NaN `x`. When `x`
878    /// is finite `x == x.next_up().next_down()` also holds.
879    ///
880    /// ```rust
881    /// // f64::EPSILON is the difference between 1.0 and the next number up.
882    /// assert_eq!(1.0f64.next_up(), 1.0 + f64::EPSILON);
883    /// // But not for most numbers.
884    /// assert!(0.1f64.next_up() < 0.1 + f64::EPSILON);
885    /// assert_eq!(9007199254740992f64.next_up(), 9007199254740994.0);
886    /// ```
887    ///
888    /// This operation corresponds to IEEE-754 `nextUp`.
889    ///
890    /// [`NEG_INFINITY`]: Self::NEG_INFINITY
891    /// [`INFINITY`]: Self::INFINITY
892    /// [`MIN`]: Self::MIN
893    /// [`MAX`]: Self::MAX
894    #[inline]
895    #[doc(alias = "nextUp")]
896    #[stable(feature = "float_next_up_down", since = "1.86.0")]
897    #[rustc_const_stable(feature = "float_next_up_down", since = "1.86.0")]
898    #[must_use = "method returns a new number and does not mutate the original value"]
899    pub const fn next_up(self) -> Self {
900        // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
901        // denormals to zero. This is in general unsound and unsupported, but here
902        // we do our best to still produce the correct result on such targets.
903        let bits = self.to_bits();
904        if self.is_nan() || bits == Self::INFINITY.to_bits() {
905            return self;
906        }
907
908        let abs = bits & !Self::SIGN_MASK;
909        let next_bits = if abs == 0 {
910            Self::TINY_BITS
911        } else if bits == abs {
912            bits + 1
913        } else {
914            bits - 1
915        };
916        Self::from_bits(next_bits)
917    }
918
919    /// Returns the greatest number less than `self`.
920    ///
921    /// Let `TINY` be the smallest representable positive `f64`. Then,
922    ///  - if `self.is_nan()`, this returns `self`;
923    ///  - if `self` is [`INFINITY`], this returns [`MAX`];
924    ///  - if `self` is `TINY`, this returns 0.0;
925    ///  - if `self` is -0.0 or +0.0, this returns `-TINY`;
926    ///  - if `self` is [`MIN`] or [`NEG_INFINITY`], this returns [`NEG_INFINITY`];
927    ///  - otherwise the unique greatest value less than `self` is returned.
928    ///
929    /// The identity `x.next_down() == -(-x).next_up()` holds for all non-NaN `x`. When `x`
930    /// is finite `x == x.next_down().next_up()` also holds.
931    ///
932    /// ```rust
933    /// let x = 1.0f64;
934    /// // Clamp value into range [0, 1).
935    /// let clamped = x.clamp(0.0, 1.0f64.next_down());
936    /// assert!(clamped < 1.0);
937    /// assert_eq!(clamped.next_up(), 1.0);
938    /// ```
939    ///
940    /// This operation corresponds to IEEE-754 `nextDown`.
941    ///
942    /// [`NEG_INFINITY`]: Self::NEG_INFINITY
943    /// [`INFINITY`]: Self::INFINITY
944    /// [`MIN`]: Self::MIN
945    /// [`MAX`]: Self::MAX
946    #[inline]
947    #[doc(alias = "nextDown")]
948    #[stable(feature = "float_next_up_down", since = "1.86.0")]
949    #[rustc_const_stable(feature = "float_next_up_down", since = "1.86.0")]
950    #[must_use = "method returns a new number and does not mutate the original value"]
951    pub const fn next_down(self) -> Self {
952        // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
953        // denormals to zero. This is in general unsound and unsupported, but here
954        // we do our best to still produce the correct result on such targets.
955        let bits = self.to_bits();
956        if self.is_nan() || bits == Self::NEG_INFINITY.to_bits() {
957            return self;
958        }
959
960        let abs = bits & !Self::SIGN_MASK;
961        let next_bits = if abs == 0 {
962            Self::NEG_TINY_BITS
963        } else if bits == abs {
964            bits - 1
965        } else {
966            bits + 1
967        };
968        Self::from_bits(next_bits)
969    }
970
971    /// Takes the reciprocal (inverse) of a number, `1/x`.
972    ///
973    /// ```
974    /// let x = 2.0_f64;
975    /// let abs_difference = (x.recip() - (1.0 / x)).abs();
976    ///
977    /// assert!(abs_difference < 1e-10);
978    /// ```
979    #[must_use = "this returns the result of the operation, without modifying the original"]
980    #[stable(feature = "rust1", since = "1.0.0")]
981    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
982    #[inline]
983    pub const fn recip(self) -> f64 {
984        1.0 / self
985    }
986
987    /// Converts radians to degrees.
988    ///
989    /// # Unspecified precision
990    ///
991    /// The precision of this function is non-deterministic. This means it varies by platform,
992    /// Rust version, and can even differ within the same execution from one invocation to the next.
993    ///
994    /// # Examples
995    ///
996    /// ```
997    /// let angle = std::f64::consts::PI;
998    ///
999    /// let abs_difference = (angle.to_degrees() - 180.0).abs();
1000    ///
1001    /// assert!(abs_difference < 1e-10);
1002    /// ```
1003    #[must_use = "this returns the result of the operation, \
1004                  without modifying the original"]
1005    #[stable(feature = "rust1", since = "1.0.0")]
1006    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1007    #[inline]
1008    pub const fn to_degrees(self) -> f64 {
1009        // The division here is correctly rounded with respect to the true value of 180/π.
1010        // Although π is irrational and already rounded, the double rounding happens
1011        // to produce correct result for f64.
1012        const PIS_IN_180: f64 = 180.0 / consts::PI;
1013        self * PIS_IN_180
1014    }
1015
1016    /// Converts degrees to radians.
1017    ///
1018    /// # Unspecified precision
1019    ///
1020    /// The precision of this function is non-deterministic. This means it varies by platform,
1021    /// Rust version, and can even differ within the same execution from one invocation to the next.
1022    ///
1023    /// # Examples
1024    ///
1025    /// ```
1026    /// let angle = 180.0_f64;
1027    ///
1028    /// let abs_difference = (angle.to_radians() - std::f64::consts::PI).abs();
1029    ///
1030    /// assert!(abs_difference < 1e-10);
1031    /// ```
1032    #[must_use = "this returns the result of the operation, \
1033                  without modifying the original"]
1034    #[stable(feature = "rust1", since = "1.0.0")]
1035    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1036    #[inline]
1037    pub const fn to_radians(self) -> f64 {
1038        // The division here is correctly rounded with respect to the true value of π/180.
1039        // Although π is irrational and already rounded, the double rounding happens
1040        // to produce correct result for f64.
1041        const RADS_PER_DEG: f64 = consts::PI / 180.0;
1042        self * RADS_PER_DEG
1043    }
1044
1045    /// Returns the maximum of the two numbers, ignoring NaN.
1046    ///
1047    /// If exactly one of the arguments is NaN (quiet or signaling), then the other argument is
1048    /// returned. If both arguments are NaN, the return value is NaN, with the bit pattern picked
1049    /// using the usual [rules for arithmetic operations](f32#nan-bit-patterns). If the inputs
1050    /// compare equal (such as for the case of `+0.0` and `-0.0`), either input may be returned
1051    /// non-deterministically.
1052    ///
1053    /// The handling of NaNs follows the IEEE 754-2019 semantics for `maximumNumber`, treating all
1054    /// NaNs the same way to ensure the operation is associative. The handling of signed zeros
1055    /// follows the IEEE 754-2008 semantics for `maxNum`.
1056    ///
1057    /// ```
1058    /// let x = 1.0_f64;
1059    /// let y = 2.0_f64;
1060    ///
1061    /// assert_eq!(x.max(y), y);
1062    /// assert_eq!(x.max(f64::NAN), x);
1063    /// ```
1064    #[must_use = "this returns the result of the comparison, without modifying either input"]
1065    #[stable(feature = "rust1", since = "1.0.0")]
1066    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1067    #[inline]
1068    pub const fn max(self, other: f64) -> f64 {
1069        intrinsics::maximum_number_nsz_f64(self, other)
1070    }
1071
1072    /// Returns the minimum of the two numbers, ignoring NaN.
1073    ///
1074    /// If exactly one of the arguments is NaN (quiet or signaling), then the other argument is
1075    /// returned. If both arguments are NaN, the return value is NaN, with the bit pattern picked
1076    /// using the usual [rules for arithmetic operations](f32#nan-bit-patterns). If the inputs
1077    /// compare equal (such as for the case of `+0.0` and `-0.0`), either input may be returned
1078    /// non-deterministically.
1079    ///
1080    /// The handling of NaNs follows the IEEE 754-2019 semantics for `minimumNumber`, treating all
1081    /// NaNs the same way to ensure the operation is associative. The handling of signed zeros
1082    /// follows the IEEE 754-2008 semantics for `minNum`.
1083    ///
1084    /// ```
1085    /// let x = 1.0_f64;
1086    /// let y = 2.0_f64;
1087    ///
1088    /// assert_eq!(x.min(y), x);
1089    /// assert_eq!(x.min(f64::NAN), x);
1090    /// ```
1091    #[must_use = "this returns the result of the comparison, without modifying either input"]
1092    #[stable(feature = "rust1", since = "1.0.0")]
1093    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1094    #[inline]
1095    pub const fn min(self, other: f64) -> f64 {
1096        intrinsics::minimum_number_nsz_f64(self, other)
1097    }
1098
1099    /// Returns the maximum of the two numbers, propagating NaN.
1100    ///
1101    /// If at least one of the arguments is NaN, the return value is NaN, with the bit pattern
1102    /// picked using the usual [rules for arithmetic operations](f32#nan-bit-patterns). Furthermore,
1103    /// `-0.0` is considered to be less than `+0.0`, making this function fully deterministic for
1104    /// non-NaN inputs.
1105    ///
1106    /// This is in contrast to [`f64::max`] which only returns NaN when *both* arguments are NaN,
1107    /// and which does not reliably order `-0.0` and `+0.0`.
1108    ///
1109    /// This follows the IEEE 754-2019 semantics for `maximum`.
1110    ///
1111    /// ```
1112    /// #![feature(float_minimum_maximum)]
1113    /// let x = 1.0_f64;
1114    /// let y = 2.0_f64;
1115    ///
1116    /// assert_eq!(x.maximum(y), y);
1117    /// assert!(x.maximum(f64::NAN).is_nan());
1118    /// ```
1119    #[must_use = "this returns the result of the comparison, without modifying either input"]
1120    #[unstable(feature = "float_minimum_maximum", issue = "91079")]
1121    #[inline]
1122    pub const fn maximum(self, other: f64) -> f64 {
1123        intrinsics::maximumf64(self, other)
1124    }
1125
1126    /// Returns the minimum of the two numbers, propagating NaN.
1127    ///
1128    /// If at least one of the arguments is NaN, the return value is NaN, with the bit pattern
1129    /// picked using the usual [rules for arithmetic operations](f32#nan-bit-patterns). Furthermore,
1130    /// `-0.0` is considered to be less than `+0.0`, making this function fully deterministic for
1131    /// non-NaN inputs.
1132    ///
1133    /// This is in contrast to [`f64::min`] which only returns NaN when *both* arguments are NaN,
1134    /// and which does not reliably order `-0.0` and `+0.0`.
1135    ///
1136    /// This follows the IEEE 754-2019 semantics for `minimum`.
1137    ///
1138    /// ```
1139    /// #![feature(float_minimum_maximum)]
1140    /// let x = 1.0_f64;
1141    /// let y = 2.0_f64;
1142    ///
1143    /// assert_eq!(x.minimum(y), x);
1144    /// assert!(x.minimum(f64::NAN).is_nan());
1145    /// ```
1146    #[must_use = "this returns the result of the comparison, without modifying either input"]
1147    #[unstable(feature = "float_minimum_maximum", issue = "91079")]
1148    #[inline]
1149    pub const fn minimum(self, other: f64) -> f64 {
1150        intrinsics::minimumf64(self, other)
1151    }
1152
1153    /// Calculates the midpoint (average) between `self` and `rhs`.
1154    ///
1155    /// This returns NaN when *either* argument is NaN or if a combination of
1156    /// +inf and -inf is provided as arguments.
1157    ///
1158    /// # Examples
1159    ///
1160    /// ```
1161    /// assert_eq!(1f64.midpoint(4.0), 2.5);
1162    /// assert_eq!((-5.5f64).midpoint(8.0), 1.25);
1163    /// ```
1164    #[inline]
1165    #[doc(alias = "average")]
1166    #[stable(feature = "num_midpoint", since = "1.85.0")]
1167    #[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
1168    #[must_use = "this returns the result of the operation, \
1169                  without modifying the original"]
1170    pub const fn midpoint(self, other: f64) -> f64 {
1171        const HI: f64 = f64::MAX / 2.;
1172
1173        let (a, b) = (self, other);
1174        let abs_a = a.abs();
1175        let abs_b = b.abs();
1176
1177        if abs_a <= HI && abs_b <= HI {
1178            // Overflow is impossible
1179            (a + b) / 2.
1180        } else {
1181            (a / 2.) + (b / 2.)
1182        }
1183    }
1184
1185    /// Rounds toward zero and converts to any primitive integer type,
1186    /// assuming that the value is finite and fits in that type.
1187    ///
1188    /// ```
1189    /// let value = 4.6_f64;
1190    /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
1191    /// assert_eq!(rounded, 4);
1192    ///
1193    /// let value = -128.9_f64;
1194    /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
1195    /// assert_eq!(rounded, i8::MIN);
1196    /// ```
1197    ///
1198    /// # Safety
1199    ///
1200    /// The value must:
1201    ///
1202    /// * Not be `NaN`
1203    /// * Not be infinite
1204    /// * Be representable in the return type `Int`, after truncating off its fractional part
1205    #[must_use = "this returns the result of the operation, \
1206                  without modifying the original"]
1207    #[stable(feature = "float_approx_unchecked_to", since = "1.44.0")]
1208    #[inline]
1209    pub unsafe fn to_int_unchecked<Int>(self) -> Int
1210    where
1211        Self: FloatToInt<Int>,
1212    {
1213        // SAFETY: the caller must uphold the safety contract for
1214        // `FloatToInt::to_int_unchecked`.
1215        unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
1216    }
1217
1218    /// Raw transmutation to `u64`.
1219    ///
1220    /// This is currently identical to `transmute::<f64, u64>(self)` on all platforms.
1221    ///
1222    /// See [`from_bits`](Self::from_bits) for some discussion of the
1223    /// portability of this operation (there are almost no issues).
1224    ///
1225    /// Note that this function is distinct from `as` casting, which attempts to
1226    /// preserve the *numeric* value, and not the bitwise value.
1227    ///
1228    /// # Examples
1229    ///
1230    /// ```
1231    /// assert!((1f64).to_bits() != 1f64 as u64); // to_bits() is not casting!
1232    /// assert_eq!((12.5f64).to_bits(), 0x4029000000000000);
1233    /// ```
1234    #[must_use = "this returns the result of the operation, \
1235                  without modifying the original"]
1236    #[stable(feature = "float_bits_conv", since = "1.20.0")]
1237    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1238    #[allow(unnecessary_transmutes)]
1239    #[inline]
1240    pub const fn to_bits(self) -> u64 {
1241        // SAFETY: `u64` is a plain old datatype so we can always transmute to it.
1242        unsafe { mem::transmute(self) }
1243    }
1244
1245    /// Raw transmutation from `u64`.
1246    ///
1247    /// This is currently identical to `transmute::<u64, f64>(v)` on all platforms.
1248    /// It turns out this is incredibly portable, for two reasons:
1249    ///
1250    /// * Floats and Ints have the same endianness on all supported platforms.
1251    /// * IEEE 754 very precisely specifies the bit layout of floats.
1252    ///
1253    /// However there is one caveat: prior to the 2008 version of IEEE 754, how
1254    /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
1255    /// (notably x86 and ARM) picked the interpretation that was ultimately
1256    /// standardized in 2008, but some didn't (notably MIPS). As a result, all
1257    /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
1258    ///
1259    /// Rather than trying to preserve signaling-ness cross-platform, this
1260    /// implementation favors preserving the exact bits. This means that
1261    /// any payloads encoded in NaNs will be preserved even if the result of
1262    /// this method is sent over the network from an x86 machine to a MIPS one.
1263    ///
1264    /// If the results of this method are only manipulated by the same
1265    /// architecture that produced them, then there is no portability concern.
1266    ///
1267    /// If the input isn't NaN, then there is no portability concern.
1268    ///
1269    /// If you don't care about signaling-ness (very likely), then there is no
1270    /// portability concern.
1271    ///
1272    /// Note that this function is distinct from `as` casting, which attempts to
1273    /// preserve the *numeric* value, and not the bitwise value.
1274    ///
1275    /// # Examples
1276    ///
1277    /// ```
1278    /// let v = f64::from_bits(0x4029000000000000);
1279    /// assert_eq!(v, 12.5);
1280    /// ```
1281    #[stable(feature = "float_bits_conv", since = "1.20.0")]
1282    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1283    #[must_use]
1284    #[inline]
1285    #[allow(unnecessary_transmutes)]
1286    pub const fn from_bits(v: u64) -> Self {
1287        // It turns out the safety issues with sNaN were overblown! Hooray!
1288        // SAFETY: `u64` is a plain old datatype so we can always transmute from it.
1289        unsafe { mem::transmute(v) }
1290    }
1291
1292    /// Returns the memory representation of this floating point number as a byte array in
1293    /// big-endian (network) byte order.
1294    ///
1295    /// See [`from_bits`](Self::from_bits) for some discussion of the
1296    /// portability of this operation (there are almost no issues).
1297    ///
1298    /// # Examples
1299    ///
1300    /// ```
1301    /// let bytes = 12.5f64.to_be_bytes();
1302    /// assert_eq!(bytes, [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1303    /// ```
1304    #[must_use = "this returns the result of the operation, \
1305                  without modifying the original"]
1306    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1307    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1308    #[inline]
1309    pub const fn to_be_bytes(self) -> [u8; 8] {
1310        self.to_bits().to_be_bytes()
1311    }
1312
1313    /// Returns the memory representation of this floating point number as a byte array in
1314    /// little-endian byte order.
1315    ///
1316    /// See [`from_bits`](Self::from_bits) for some discussion of the
1317    /// portability of this operation (there are almost no issues).
1318    ///
1319    /// # Examples
1320    ///
1321    /// ```
1322    /// let bytes = 12.5f64.to_le_bytes();
1323    /// assert_eq!(bytes, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]);
1324    /// ```
1325    #[must_use = "this returns the result of the operation, \
1326                  without modifying the original"]
1327    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1328    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1329    #[inline]
1330    pub const fn to_le_bytes(self) -> [u8; 8] {
1331        self.to_bits().to_le_bytes()
1332    }
1333
1334    /// Returns the memory representation of this floating point number as a byte array in
1335    /// native byte order.
1336    ///
1337    /// As the target platform's native endianness is used, portable code
1338    /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1339    ///
1340    /// [`to_be_bytes`]: f64::to_be_bytes
1341    /// [`to_le_bytes`]: f64::to_le_bytes
1342    ///
1343    /// See [`from_bits`](Self::from_bits) for some discussion of the
1344    /// portability of this operation (there are almost no issues).
1345    ///
1346    /// # Examples
1347    ///
1348    /// ```
1349    /// let bytes = 12.5f64.to_ne_bytes();
1350    /// assert_eq!(
1351    ///     bytes,
1352    ///     if cfg!(target_endian = "big") {
1353    ///         [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1354    ///     } else {
1355    ///         [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]
1356    ///     }
1357    /// );
1358    /// ```
1359    #[must_use = "this returns the result of the operation, \
1360                  without modifying the original"]
1361    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1362    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1363    #[inline]
1364    pub const fn to_ne_bytes(self) -> [u8; 8] {
1365        self.to_bits().to_ne_bytes()
1366    }
1367
1368    /// Creates a floating point value from its representation as a byte array in big endian.
1369    ///
1370    /// See [`from_bits`](Self::from_bits) for some discussion of the
1371    /// portability of this operation (there are almost no issues).
1372    ///
1373    /// # Examples
1374    ///
1375    /// ```
1376    /// let value = f64::from_be_bytes([0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1377    /// assert_eq!(value, 12.5);
1378    /// ```
1379    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1380    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1381    #[must_use]
1382    #[inline]
1383    pub const fn from_be_bytes(bytes: [u8; 8]) -> Self {
1384        Self::from_bits(u64::from_be_bytes(bytes))
1385    }
1386
1387    /// Creates a floating point value from its representation as a byte array in little endian.
1388    ///
1389    /// See [`from_bits`](Self::from_bits) for some discussion of the
1390    /// portability of this operation (there are almost no issues).
1391    ///
1392    /// # Examples
1393    ///
1394    /// ```
1395    /// let value = f64::from_le_bytes([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]);
1396    /// assert_eq!(value, 12.5);
1397    /// ```
1398    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1399    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1400    #[must_use]
1401    #[inline]
1402    pub const fn from_le_bytes(bytes: [u8; 8]) -> Self {
1403        Self::from_bits(u64::from_le_bytes(bytes))
1404    }
1405
1406    /// Creates a floating point value from its representation as a byte array in native endian.
1407    ///
1408    /// As the target platform's native endianness is used, portable code
1409    /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1410    /// appropriate instead.
1411    ///
1412    /// [`from_be_bytes`]: f64::from_be_bytes
1413    /// [`from_le_bytes`]: f64::from_le_bytes
1414    ///
1415    /// See [`from_bits`](Self::from_bits) for some discussion of the
1416    /// portability of this operation (there are almost no issues).
1417    ///
1418    /// # Examples
1419    ///
1420    /// ```
1421    /// let value = f64::from_ne_bytes(if cfg!(target_endian = "big") {
1422    ///     [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1423    /// } else {
1424    ///     [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]
1425    /// });
1426    /// assert_eq!(value, 12.5);
1427    /// ```
1428    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1429    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1430    #[must_use]
1431    #[inline]
1432    pub const fn from_ne_bytes(bytes: [u8; 8]) -> Self {
1433        Self::from_bits(u64::from_ne_bytes(bytes))
1434    }
1435
1436    /// Returns the ordering between `self` and `other`.
1437    ///
1438    /// Unlike the standard partial comparison between floating point numbers,
1439    /// this comparison always produces an ordering in accordance to
1440    /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1441    /// floating point standard. The values are ordered in the following sequence:
1442    ///
1443    /// - negative quiet NaN
1444    /// - negative signaling NaN
1445    /// - negative infinity
1446    /// - negative numbers
1447    /// - negative subnormal numbers
1448    /// - negative zero
1449    /// - positive zero
1450    /// - positive subnormal numbers
1451    /// - positive numbers
1452    /// - positive infinity
1453    /// - positive signaling NaN
1454    /// - positive quiet NaN.
1455    ///
1456    /// The ordering established by this function does not always agree with the
1457    /// [`PartialOrd`] and [`PartialEq`] implementations of `f64`. For example,
1458    /// they consider negative and positive zero equal, while `total_cmp`
1459    /// doesn't.
1460    ///
1461    /// The interpretation of the signaling NaN bit follows the definition in
1462    /// the IEEE 754 standard, which may not match the interpretation by some of
1463    /// the older, non-conformant (e.g. MIPS) hardware implementations.
1464    ///
1465    /// # Example
1466    ///
1467    /// ```
1468    /// struct GoodBoy {
1469    ///     name: String,
1470    ///     weight: f64,
1471    /// }
1472    ///
1473    /// let mut bois = vec![
1474    ///     GoodBoy { name: "Pucci".to_owned(), weight: 0.1 },
1475    ///     GoodBoy { name: "Woofer".to_owned(), weight: 99.0 },
1476    ///     GoodBoy { name: "Yapper".to_owned(), weight: 10.0 },
1477    ///     GoodBoy { name: "Chonk".to_owned(), weight: f64::INFINITY },
1478    ///     GoodBoy { name: "Abs. Unit".to_owned(), weight: f64::NAN },
1479    ///     GoodBoy { name: "Floaty".to_owned(), weight: -5.0 },
1480    /// ];
1481    ///
1482    /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1483    ///
1484    /// // `f64::NAN` could be positive or negative, which will affect the sort order.
1485    /// if f64::NAN.is_sign_negative() {
1486    ///     assert!(bois.into_iter().map(|b| b.weight)
1487    ///         .zip([f64::NAN, -5.0, 0.1, 10.0, 99.0, f64::INFINITY].iter())
1488    ///         .all(|(a, b)| a.to_bits() == b.to_bits()))
1489    /// } else {
1490    ///     assert!(bois.into_iter().map(|b| b.weight)
1491    ///         .zip([-5.0, 0.1, 10.0, 99.0, f64::INFINITY, f64::NAN].iter())
1492    ///         .all(|(a, b)| a.to_bits() == b.to_bits()))
1493    /// }
1494    /// ```
1495    #[stable(feature = "total_cmp", since = "1.62.0")]
1496    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1497    #[must_use]
1498    #[inline]
1499    pub const fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1500        let mut left = self.to_bits() as i64;
1501        let mut right = other.to_bits() as i64;
1502
1503        // In case of negatives, flip all the bits except the sign
1504        // to achieve a similar layout as two's complement integers
1505        //
1506        // Why does this work? IEEE 754 floats consist of three fields:
1507        // Sign bit, exponent and mantissa. The set of exponent and mantissa
1508        // fields as a whole have the property that their bitwise order is
1509        // equal to the numeric magnitude where the magnitude is defined.
1510        // The magnitude is not normally defined on NaN values, but
1511        // IEEE 754 totalOrder defines the NaN values also to follow the
1512        // bitwise order. This leads to order explained in the doc comment.
1513        // However, the representation of magnitude is the same for negative
1514        // and positive numbers – only the sign bit is different.
1515        // To easily compare the floats as signed integers, we need to
1516        // flip the exponent and mantissa bits in case of negative numbers.
1517        // We effectively convert the numbers to "two's complement" form.
1518        //
1519        // To do the flipping, we construct a mask and XOR against it.
1520        // We branchlessly calculate an "all-ones except for the sign bit"
1521        // mask from negative-signed values: right shifting sign-extends
1522        // the integer, so we "fill" the mask with sign bits, and then
1523        // convert to unsigned to push one more zero bit.
1524        // On positive values, the mask is all zeros, so it's a no-op.
1525        left ^= (((left >> 63) as u64) >> 1) as i64;
1526        right ^= (((right >> 63) as u64) >> 1) as i64;
1527
1528        left.cmp(&right)
1529    }
1530
1531    /// Restrict a value to a certain interval unless it is NaN.
1532    ///
1533    /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1534    /// less than `min`. Otherwise this returns `self`.
1535    ///
1536    /// Note that this function returns NaN if the initial value was NaN as
1537    /// well. If the result is zero and among the three inputs `self`, `min`, and `max` there are
1538    /// zeros with different sign, either `0.0` or `-0.0` is returned non-deterministically.
1539    ///
1540    /// # Panics
1541    ///
1542    /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1543    ///
1544    /// # Examples
1545    ///
1546    /// ```
1547    /// assert!((-3.0f64).clamp(-2.0, 1.0) == -2.0);
1548    /// assert!((0.0f64).clamp(-2.0, 1.0) == 0.0);
1549    /// assert!((2.0f64).clamp(-2.0, 1.0) == 1.0);
1550    /// assert!((f64::NAN).clamp(-2.0, 1.0).is_nan());
1551    ///
1552    /// // These always returns zero, but the sign (which is ignored by `==`) is non-deterministic.
1553    /// assert!((0.0f64).clamp(-0.0, -0.0) == 0.0);
1554    /// assert!((1.0f64).clamp(-0.0, 0.0) == 0.0);
1555    /// // This is definitely a negative zero.
1556    /// assert!((-1.0f64).clamp(-0.0, 1.0).is_sign_negative());
1557    /// ```
1558    #[must_use = "method returns a new number and does not mutate the original value"]
1559    #[stable(feature = "clamp", since = "1.50.0")]
1560    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1561    #[inline]
1562    pub const fn clamp(mut self, min: f64, max: f64) -> f64 {
1563        const_assert!(
1564            min <= max,
1565            "min > max, or either was NaN",
1566            "min > max, or either was NaN. min = {min:?}, max = {max:?}",
1567            min: f64,
1568            max: f64,
1569        );
1570
1571        if self < min {
1572            self = min;
1573        }
1574        if self > max {
1575            self = max;
1576        }
1577        self
1578    }
1579
1580    /// Clamps this number to a symmetric range centered around zero.
1581    ///
1582    /// The method clamps the number's magnitude (absolute value) to be at most `limit`.
1583    ///
1584    /// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more
1585    /// explicit about the intent.
1586    ///
1587    /// # Panics
1588    ///
1589    /// Panics if `limit` is negative or NaN, as this indicates a logic error.
1590    ///
1591    /// # Examples
1592    ///
1593    /// ```
1594    /// #![feature(clamp_magnitude)]
1595    /// assert_eq!(5.0f64.clamp_magnitude(3.0), 3.0);
1596    /// assert_eq!((-5.0f64).clamp_magnitude(3.0), -3.0);
1597    /// assert_eq!(2.0f64.clamp_magnitude(3.0), 2.0);
1598    /// assert_eq!((-2.0f64).clamp_magnitude(3.0), -2.0);
1599    /// ```
1600    #[must_use = "this returns the clamped value and does not modify the original"]
1601    #[unstable(feature = "clamp_magnitude", issue = "148519")]
1602    #[inline]
1603    pub fn clamp_magnitude(self, limit: f64) -> f64 {
1604        assert!(limit >= 0.0, "limit must be non-negative");
1605        let limit = limit.abs(); // Canonicalises -0.0 to 0.0
1606        self.clamp(-limit, limit)
1607    }
1608
1609    /// Computes the absolute value of `self`.
1610    ///
1611    /// This function always returns the precise result.
1612    ///
1613    /// # Examples
1614    ///
1615    /// ```
1616    /// let x = 3.5_f64;
1617    /// let y = -3.5_f64;
1618    ///
1619    /// assert_eq!(x.abs(), x);
1620    /// assert_eq!(y.abs(), -y);
1621    ///
1622    /// assert!(f64::NAN.abs().is_nan());
1623    /// ```
1624    #[must_use = "method returns a new number and does not mutate the original value"]
1625    #[stable(feature = "rust1", since = "1.0.0")]
1626    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1627    #[inline]
1628    pub const fn abs(self) -> f64 {
1629        intrinsics::fabs(self)
1630    }
1631
1632    /// Returns a number that represents the sign of `self`.
1633    ///
1634    /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
1635    /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
1636    /// - NaN if the number is NaN
1637    ///
1638    /// # Examples
1639    ///
1640    /// ```
1641    /// let f = 3.5_f64;
1642    ///
1643    /// assert_eq!(f.signum(), 1.0);
1644    /// assert_eq!(f64::NEG_INFINITY.signum(), -1.0);
1645    ///
1646    /// assert!(f64::NAN.signum().is_nan());
1647    /// ```
1648    #[must_use = "method returns a new number and does not mutate the original value"]
1649    #[stable(feature = "rust1", since = "1.0.0")]
1650    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1651    #[inline]
1652    pub const fn signum(self) -> f64 {
1653        if self.is_nan() { Self::NAN } else { 1.0_f64.copysign(self) }
1654    }
1655
1656    /// Returns a number composed of the magnitude of `self` and the sign of
1657    /// `sign`.
1658    ///
1659    /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`.
1660    /// If `self` is a NaN, then a NaN with the same payload as `self` and the sign bit of `sign` is
1661    /// returned.
1662    ///
1663    /// If `sign` is a NaN, then this operation will still carry over its sign into the result. Note
1664    /// that IEEE 754 doesn't assign any meaning to the sign bit in case of a NaN, and as Rust
1665    /// doesn't guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the
1666    /// result of `copysign` with `sign` being a NaN might produce an unexpected or non-portable
1667    /// result. See the [specification of NaN bit patterns](primitive@f32#nan-bit-patterns) for more
1668    /// info.
1669    ///
1670    /// # Examples
1671    ///
1672    /// ```
1673    /// let f = 3.5_f64;
1674    ///
1675    /// assert_eq!(f.copysign(0.42), 3.5_f64);
1676    /// assert_eq!(f.copysign(-0.42), -3.5_f64);
1677    /// assert_eq!((-f).copysign(0.42), 3.5_f64);
1678    /// assert_eq!((-f).copysign(-0.42), -3.5_f64);
1679    ///
1680    /// assert!(f64::NAN.copysign(1.0).is_nan());
1681    /// ```
1682    #[must_use = "method returns a new number and does not mutate the original value"]
1683    #[stable(feature = "copysign", since = "1.35.0")]
1684    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1685    #[inline]
1686    pub const fn copysign(self, sign: f64) -> f64 {
1687        intrinsics::copysignf64(self, sign)
1688    }
1689
1690    /// Float addition that allows optimizations based on algebraic rules.
1691    ///
1692    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1693    #[must_use = "method returns a new number and does not mutate the original value"]
1694    #[unstable(feature = "float_algebraic", issue = "136469")]
1695    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1696    #[inline]
1697    pub const fn algebraic_add(self, rhs: f64) -> f64 {
1698        intrinsics::fadd_algebraic(self, rhs)
1699    }
1700
1701    /// Float subtraction that allows optimizations based on algebraic rules.
1702    ///
1703    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1704    #[must_use = "method returns a new number and does not mutate the original value"]
1705    #[unstable(feature = "float_algebraic", issue = "136469")]
1706    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1707    #[inline]
1708    pub const fn algebraic_sub(self, rhs: f64) -> f64 {
1709        intrinsics::fsub_algebraic(self, rhs)
1710    }
1711
1712    /// Float multiplication that allows optimizations based on algebraic rules.
1713    ///
1714    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1715    #[must_use = "method returns a new number and does not mutate the original value"]
1716    #[unstable(feature = "float_algebraic", issue = "136469")]
1717    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1718    #[inline]
1719    pub const fn algebraic_mul(self, rhs: f64) -> f64 {
1720        intrinsics::fmul_algebraic(self, rhs)
1721    }
1722
1723    /// Float division that allows optimizations based on algebraic rules.
1724    ///
1725    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1726    #[must_use = "method returns a new number and does not mutate the original value"]
1727    #[unstable(feature = "float_algebraic", issue = "136469")]
1728    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1729    #[inline]
1730    pub const fn algebraic_div(self, rhs: f64) -> f64 {
1731        intrinsics::fdiv_algebraic(self, rhs)
1732    }
1733
1734    /// Float remainder that allows optimizations based on algebraic rules.
1735    ///
1736    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1737    #[must_use = "method returns a new number and does not mutate the original value"]
1738    #[unstable(feature = "float_algebraic", issue = "136469")]
1739    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1740    #[inline]
1741    pub const fn algebraic_rem(self, rhs: f64) -> f64 {
1742        intrinsics::frem_algebraic(self, rhs)
1743    }
1744}
1745
1746#[unstable(feature = "core_float_math", issue = "137578")]
1747/// Experimental implementations of floating point functions in `core`.
1748///
1749/// _The standalone functions in this module are for testing only.
1750/// They will be stabilized as inherent methods._
1751pub mod math {
1752    use crate::intrinsics;
1753    use crate::num::imp::libm;
1754
1755    /// Experimental version of `floor` in `core`. See [`f64::floor`] for details.
1756    ///
1757    /// # Examples
1758    ///
1759    /// ```
1760    /// #![feature(core_float_math)]
1761    ///
1762    /// use core::f64;
1763    ///
1764    /// let f = 3.7_f64;
1765    /// let g = 3.0_f64;
1766    /// let h = -3.7_f64;
1767    ///
1768    /// assert_eq!(f64::math::floor(f), 3.0);
1769    /// assert_eq!(f64::math::floor(g), 3.0);
1770    /// assert_eq!(f64::math::floor(h), -4.0);
1771    /// ```
1772    ///
1773    /// _This standalone function is for testing only.
1774    /// It will be stabilized as an inherent method._
1775    ///
1776    /// [`f64::floor`]: ../../../std/primitive.f64.html#method.floor
1777    #[inline]
1778    #[unstable(feature = "core_float_math", issue = "137578")]
1779    #[must_use = "method returns a new number and does not mutate the original value"]
1780    pub const fn floor(x: f64) -> f64 {
1781        intrinsics::floorf64(x)
1782    }
1783
1784    /// Experimental version of `ceil` in `core`. See [`f64::ceil`] for details.
1785    ///
1786    /// # Examples
1787    ///
1788    /// ```
1789    /// #![feature(core_float_math)]
1790    ///
1791    /// use core::f64;
1792    ///
1793    /// let f = 3.01_f64;
1794    /// let g = 4.0_f64;
1795    ///
1796    /// assert_eq!(f64::math::ceil(f), 4.0);
1797    /// assert_eq!(f64::math::ceil(g), 4.0);
1798    /// ```
1799    ///
1800    /// _This standalone function is for testing only.
1801    /// It will be stabilized as an inherent method._
1802    ///
1803    /// [`f64::ceil`]: ../../../std/primitive.f64.html#method.ceil
1804    #[inline]
1805    #[doc(alias = "ceiling")]
1806    #[unstable(feature = "core_float_math", issue = "137578")]
1807    #[must_use = "method returns a new number and does not mutate the original value"]
1808    pub const fn ceil(x: f64) -> f64 {
1809        intrinsics::ceilf64(x)
1810    }
1811
1812    /// Experimental version of `round` in `core`. See [`f64::round`] for details.
1813    ///
1814    /// # Examples
1815    ///
1816    /// ```
1817    /// #![feature(core_float_math)]
1818    ///
1819    /// use core::f64;
1820    ///
1821    /// let f = 3.3_f64;
1822    /// let g = -3.3_f64;
1823    /// let h = -3.7_f64;
1824    /// let i = 3.5_f64;
1825    /// let j = 4.5_f64;
1826    ///
1827    /// assert_eq!(f64::math::round(f), 3.0);
1828    /// assert_eq!(f64::math::round(g), -3.0);
1829    /// assert_eq!(f64::math::round(h), -4.0);
1830    /// assert_eq!(f64::math::round(i), 4.0);
1831    /// assert_eq!(f64::math::round(j), 5.0);
1832    /// ```
1833    ///
1834    /// _This standalone function is for testing only.
1835    /// It will be stabilized as an inherent method._
1836    ///
1837    /// [`f64::round`]: ../../../std/primitive.f64.html#method.round
1838    #[inline]
1839    #[unstable(feature = "core_float_math", issue = "137578")]
1840    #[must_use = "method returns a new number and does not mutate the original value"]
1841    pub const fn round(x: f64) -> f64 {
1842        intrinsics::roundf64(x)
1843    }
1844
1845    /// Experimental version of `round_ties_even` in `core`. See [`f64::round_ties_even`] for
1846    /// details.
1847    ///
1848    /// # Examples
1849    ///
1850    /// ```
1851    /// #![feature(core_float_math)]
1852    ///
1853    /// use core::f64;
1854    ///
1855    /// let f = 3.3_f64;
1856    /// let g = -3.3_f64;
1857    /// let h = 3.5_f64;
1858    /// let i = 4.5_f64;
1859    ///
1860    /// assert_eq!(f64::math::round_ties_even(f), 3.0);
1861    /// assert_eq!(f64::math::round_ties_even(g), -3.0);
1862    /// assert_eq!(f64::math::round_ties_even(h), 4.0);
1863    /// assert_eq!(f64::math::round_ties_even(i), 4.0);
1864    /// ```
1865    ///
1866    /// _This standalone function is for testing only.
1867    /// It will be stabilized as an inherent method._
1868    ///
1869    /// [`f64::round_ties_even`]: ../../../std/primitive.f64.html#method.round_ties_even
1870    #[inline]
1871    #[unstable(feature = "core_float_math", issue = "137578")]
1872    #[must_use = "method returns a new number and does not mutate the original value"]
1873    pub const fn round_ties_even(x: f64) -> f64 {
1874        intrinsics::round_ties_even_f64(x)
1875    }
1876
1877    /// Experimental version of `trunc` in `core`. See [`f64::trunc`] for details.
1878    ///
1879    /// # Examples
1880    ///
1881    /// ```
1882    /// #![feature(core_float_math)]
1883    ///
1884    /// use core::f64;
1885    ///
1886    /// let f = 3.7_f64;
1887    /// let g = 3.0_f64;
1888    /// let h = -3.7_f64;
1889    ///
1890    /// assert_eq!(f64::math::trunc(f), 3.0);
1891    /// assert_eq!(f64::math::trunc(g), 3.0);
1892    /// assert_eq!(f64::math::trunc(h), -3.0);
1893    /// ```
1894    ///
1895    /// _This standalone function is for testing only.
1896    /// It will be stabilized as an inherent method._
1897    ///
1898    /// [`f64::trunc`]: ../../../std/primitive.f64.html#method.trunc
1899    #[inline]
1900    #[doc(alias = "truncate")]
1901    #[unstable(feature = "core_float_math", issue = "137578")]
1902    #[must_use = "method returns a new number and does not mutate the original value"]
1903    pub const fn trunc(x: f64) -> f64 {
1904        intrinsics::truncf64(x)
1905    }
1906
1907    /// Experimental version of `fract` in `core`. See [`f64::fract`] for details.
1908    ///
1909    /// # Examples
1910    ///
1911    /// ```
1912    /// #![feature(core_float_math)]
1913    ///
1914    /// use core::f64;
1915    ///
1916    /// let x = 3.6_f64;
1917    /// let y = -3.6_f64;
1918    /// let abs_difference_x = (f64::math::fract(x) - 0.6).abs();
1919    /// let abs_difference_y = (f64::math::fract(y) - (-0.6)).abs();
1920    ///
1921    /// assert!(abs_difference_x < 1e-10);
1922    /// assert!(abs_difference_y < 1e-10);
1923    /// ```
1924    ///
1925    /// _This standalone function is for testing only.
1926    /// It will be stabilized as an inherent method._
1927    ///
1928    /// [`f64::fract`]: ../../../std/primitive.f64.html#method.fract
1929    #[inline]
1930    #[unstable(feature = "core_float_math", issue = "137578")]
1931    #[must_use = "method returns a new number and does not mutate the original value"]
1932    pub const fn fract(x: f64) -> f64 {
1933        x - trunc(x)
1934    }
1935
1936    /// Experimental version of `mul_add` in `core`. See [`f64::mul_add`] for details.
1937    ///
1938    /// # Examples
1939    ///
1940    /// ```
1941    /// # #![allow(unused_features)]
1942    /// #![feature(core_float_math)]
1943    ///
1944    /// # // FIXME(#140515): mingw has an incorrect fma
1945    /// # // https://sourceforge.net/p/mingw-w64/bugs/848/
1946    /// # #[cfg(all(target_os = "windows", target_env = "gnu", not(target_abi = "llvm")))] {
1947    /// use core::f64;
1948    ///
1949    /// let m = 10.0_f64;
1950    /// let x = 4.0_f64;
1951    /// let b = 60.0_f64;
1952    ///
1953    /// assert_eq!(f64::math::mul_add(m, x, b), 100.0);
1954    /// assert_eq!(m * x + b, 100.0);
1955    ///
1956    /// let one_plus_eps = 1.0_f64 + f64::EPSILON;
1957    /// let one_minus_eps = 1.0_f64 - f64::EPSILON;
1958    /// let minus_one = -1.0_f64;
1959    ///
1960    /// // The exact result (1 + eps) * (1 - eps) = 1 - eps * eps.
1961    /// assert_eq!(
1962    ///     f64::math::mul_add(one_plus_eps, one_minus_eps, minus_one),
1963    ///     -f64::EPSILON * f64::EPSILON
1964    /// );
1965    /// // Different rounding with the non-fused multiply and add.
1966    /// assert_eq!(one_plus_eps * one_minus_eps + minus_one, 0.0);
1967    /// # }
1968    /// ```
1969    ///
1970    /// _This standalone function is for testing only.
1971    /// It will be stabilized as an inherent method._
1972    ///
1973    /// [`f64::mul_add`]: ../../../std/primitive.f64.html#method.mul_add
1974    #[inline]
1975    #[doc(alias = "fma", alias = "fusedMultiplyAdd")]
1976    #[unstable(feature = "core_float_math", issue = "137578")]
1977    #[must_use = "method returns a new number and does not mutate the original value"]
1978    pub const fn mul_add(x: f64, a: f64, b: f64) -> f64 {
1979        intrinsics::fmaf64(x, a, b)
1980    }
1981
1982    /// Experimental version of `div_euclid` in `core`. See [`f64::div_euclid`] for details.
1983    ///
1984    /// # Examples
1985    ///
1986    /// ```
1987    /// #![feature(core_float_math)]
1988    ///
1989    /// use core::f64;
1990    ///
1991    /// let a: f64 = 7.0;
1992    /// let b = 4.0;
1993    /// assert_eq!(f64::math::div_euclid(a, b), 1.0); // 7.0 > 4.0 * 1.0
1994    /// assert_eq!(f64::math::div_euclid(-a, b), -2.0); // -7.0 >= 4.0 * -2.0
1995    /// assert_eq!(f64::math::div_euclid(a, -b), -1.0); // 7.0 >= -4.0 * -1.0
1996    /// assert_eq!(f64::math::div_euclid(-a, -b), 2.0); // -7.0 >= -4.0 * 2.0
1997    /// ```
1998    ///
1999    /// _This standalone function is for testing only.
2000    /// It will be stabilized as an inherent method._
2001    ///
2002    /// [`f64::div_euclid`]: ../../../std/primitive.f64.html#method.div_euclid
2003    #[inline]
2004    #[unstable(feature = "core_float_math", issue = "137578")]
2005    #[must_use = "method returns a new number and does not mutate the original value"]
2006    pub fn div_euclid(x: f64, rhs: f64) -> f64 {
2007        let q = trunc(x / rhs);
2008        if x % rhs < 0.0 {
2009            return if rhs > 0.0 { q - 1.0 } else { q + 1.0 };
2010        }
2011        q
2012    }
2013
2014    /// Experimental version of `rem_euclid` in `core`. See [`f64::rem_euclid`] for details.
2015    ///
2016    /// # Examples
2017    ///
2018    /// ```
2019    /// #![feature(core_float_math)]
2020    ///
2021    /// use core::f64;
2022    ///
2023    /// let a: f64 = 7.0;
2024    /// let b = 4.0;
2025    /// assert_eq!(f64::math::rem_euclid(a, b), 3.0);
2026    /// assert_eq!(f64::math::rem_euclid(-a, b), 1.0);
2027    /// assert_eq!(f64::math::rem_euclid(a, -b), 3.0);
2028    /// assert_eq!(f64::math::rem_euclid(-a, -b), 1.0);
2029    /// // limitation due to round-off error
2030    /// assert!(f64::math::rem_euclid(-f64::EPSILON, 3.0) != 0.0);
2031    /// ```
2032    ///
2033    /// _This standalone function is for testing only.
2034    /// It will be stabilized as an inherent method._
2035    ///
2036    /// [`f64::rem_euclid`]: ../../../std/primitive.f64.html#method.rem_euclid
2037    #[inline]
2038    #[doc(alias = "modulo", alias = "mod")]
2039    #[unstable(feature = "core_float_math", issue = "137578")]
2040    #[must_use = "method returns a new number and does not mutate the original value"]
2041    pub fn rem_euclid(x: f64, rhs: f64) -> f64 {
2042        let r = x % rhs;
2043        if r < 0.0 { r + rhs.abs() } else { r }
2044    }
2045
2046    /// Experimental version of `powi` in `core`. See [`f64::powi`] for details.
2047    ///
2048    /// # Examples
2049    ///
2050    /// ```
2051    /// #![feature(core_float_math)]
2052    ///
2053    /// use core::f64;
2054    ///
2055    /// let x = 2.0_f64;
2056    /// let abs_difference = (f64::math::powi(x, 2) - (x * x)).abs();
2057    /// assert!(abs_difference <= 1e-6);
2058    ///
2059    /// assert_eq!(f64::math::powi(f64::NAN, 0), 1.0);
2060    /// ```
2061    ///
2062    /// _This standalone function is for testing only.
2063    /// It will be stabilized as an inherent method._
2064    ///
2065    /// [`f64::powi`]: ../../../std/primitive.f64.html#method.powi
2066    #[inline]
2067    #[unstable(feature = "core_float_math", issue = "137578")]
2068    #[must_use = "method returns a new number and does not mutate the original value"]
2069    pub fn powi(x: f64, n: i32) -> f64 {
2070        intrinsics::powif64(x, n)
2071    }
2072
2073    /// Experimental version of `sqrt` in `core`. See [`f64::sqrt`] for details.
2074    ///
2075    /// # Examples
2076    ///
2077    /// ```
2078    /// #![feature(core_float_math)]
2079    ///
2080    /// use core::f64;
2081    ///
2082    /// let positive = 4.0_f64;
2083    /// let negative = -4.0_f64;
2084    /// let negative_zero = -0.0_f64;
2085    ///
2086    /// assert_eq!(f64::math::sqrt(positive), 2.0);
2087    /// assert!(f64::math::sqrt(negative).is_nan());
2088    /// assert_eq!(f64::math::sqrt(negative_zero), negative_zero);
2089    /// ```
2090    ///
2091    /// _This standalone function is for testing only.
2092    /// It will be stabilized as an inherent method._
2093    ///
2094    /// [`f64::sqrt`]: ../../../std/primitive.f64.html#method.sqrt
2095    #[inline]
2096    #[doc(alias = "squareRoot")]
2097    #[unstable(feature = "core_float_math", issue = "137578")]
2098    #[must_use = "method returns a new number and does not mutate the original value"]
2099    pub fn sqrt(x: f64) -> f64 {
2100        intrinsics::sqrtf64(x)
2101    }
2102
2103    /// Experimental version of `abs_sub` in `core`. See [`f64::abs_sub`] for details.
2104    ///
2105    /// # Examples
2106    ///
2107    /// ```
2108    /// #![feature(core_float_math)]
2109    ///
2110    /// use core::f64;
2111    ///
2112    /// let x = 3.0_f64;
2113    /// let y = -3.0_f64;
2114    ///
2115    /// let abs_difference_x = (f64::math::abs_sub(x, 1.0) - 2.0).abs();
2116    /// let abs_difference_y = (f64::math::abs_sub(y, 1.0) - 0.0).abs();
2117    ///
2118    /// assert!(abs_difference_x < 1e-10);
2119    /// assert!(abs_difference_y < 1e-10);
2120    /// ```
2121    ///
2122    /// _This standalone function is for testing only.
2123    /// It will be stabilized as an inherent method._
2124    ///
2125    /// [`f64::abs_sub`]: ../../../std/primitive.f64.html#method.abs_sub
2126    #[inline]
2127    #[unstable(feature = "core_float_math", issue = "137578")]
2128    #[deprecated(
2129        since = "1.10.0",
2130        note = "you probably meant `(self - other).abs()`: \
2131                this operation is `(self - other).max(0.0)` \
2132                except that `abs_sub` also propagates NaNs (also \
2133                known as `fdim` in C). If you truly need the positive \
2134                difference, consider using that expression or the C function \
2135                `fdim`, depending on how you wish to handle NaN (please consider \
2136                filing an issue describing your use-case too)."
2137    )]
2138    #[must_use = "method returns a new number and does not mutate the original value"]
2139    pub fn abs_sub(x: f64, other: f64) -> f64 {
2140        libm::fdim(x, other)
2141    }
2142
2143    /// Experimental version of `cbrt` in `core`. See [`f64::cbrt`] for details.
2144    ///
2145    /// # Examples
2146    ///
2147    /// ```
2148    /// #![feature(core_float_math)]
2149    ///
2150    /// use core::f64;
2151    ///
2152    /// let x = 8.0_f64;
2153    ///
2154    /// // x^(1/3) - 2 == 0
2155    /// let abs_difference = (f64::math::cbrt(x) - 2.0).abs();
2156    ///
2157    /// assert!(abs_difference < 1e-10);
2158    /// ```
2159    ///
2160    /// _This standalone function is for testing only.
2161    /// It will be stabilized as an inherent method._
2162    ///
2163    /// [`f64::cbrt`]: ../../../std/primitive.f64.html#method.cbrt
2164    #[inline]
2165    #[unstable(feature = "core_float_math", issue = "137578")]
2166    #[must_use = "method returns a new number and does not mutate the original value"]
2167    pub fn cbrt(x: f64) -> f64 {
2168        libm::cbrt(x)
2169    }
2170}