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