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