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_f64(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_f64(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    #[inline]
894    pub const fn maximum(self, other: f64) -> f64 {
895        intrinsics::maximumf64(self, other)
896    }
897
898    /// Returns the minimum of the two numbers, propagating NaN.
899    ///
900    /// If at least one of the arguments is NaN, the return value is NaN, with the bit pattern
901    /// picked using the usual [rules for arithmetic operations](f32#nan-bit-patterns). Furthermore,
902    /// `-0.0` is considered to be less than `+0.0`, making this function fully deterministic for
903    /// non-NaN inputs.
904    ///
905    /// This is in contrast to [`f64::min`] which only returns NaN when *both* arguments are NaN,
906    /// and which does not reliably order `-0.0` and `+0.0`.
907    ///
908    /// This follows the IEEE 754-2019 semantics for `minimum`.
909    ///
910    /// ```
911    /// #![feature(float_minimum_maximum)]
912    /// let x = 1.0_f64;
913    /// let y = 2.0_f64;
914    ///
915    /// assert_eq!(x.minimum(y), x);
916    /// assert!(x.minimum(f64::NAN).is_nan());
917    /// ```
918    #[must_use = "this returns the result of the comparison, without modifying either input"]
919    #[unstable(feature = "float_minimum_maximum", issue = "91079")]
920    #[inline]
921    pub const fn minimum(self, other: f64) -> f64 {
922        intrinsics::minimumf64(self, other)
923    }
924
925    /// Calculates the midpoint (average) between `self` and `rhs`.
926    ///
927    /// This returns NaN when *either* argument is NaN or if a combination of
928    /// +inf and -inf is provided as arguments.
929    ///
930    /// # Examples
931    ///
932    /// ```
933    /// assert_eq!(1f64.midpoint(4.0), 2.5);
934    /// assert_eq!((-5.5f64).midpoint(8.0), 1.25);
935    /// ```
936    #[inline]
937    #[doc(alias = "average")]
938    #[stable(feature = "num_midpoint", since = "1.85.0")]
939    #[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
940    #[must_use = "this returns the result of the operation, \
941                  without modifying the original"]
942    pub const fn midpoint(self, other: f64) -> f64 {
943        const HI: f64 = f64::MAX * 0.5;
944
945        let (a, b) = (self, other);
946        let abs_a = a.abs();
947        let abs_b = b.abs();
948
949        if abs_a <= HI && abs_b <= HI {
950            // Overflow is impossible
951            (a + b) * 0.5
952        } else {
953            (a * 0.5) + (b * 0.5)
954        }
955    }
956
957    /// Rounds toward zero and converts to any primitive integer type,
958    /// assuming that the value is finite and fits in that type.
959    ///
960    /// ```
961    /// let value = 4.6_f64;
962    /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
963    /// assert_eq!(rounded, 4);
964    ///
965    /// let value = -128.9_f64;
966    /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
967    /// assert_eq!(rounded, i8::MIN);
968    /// ```
969    ///
970    /// # Safety
971    ///
972    /// The value must:
973    ///
974    /// * Not be `NaN`
975    /// * Not be infinite
976    /// * Be representable in the return type `Int`, after truncating off its fractional part
977    #[must_use = "this returns the result of the operation, \
978                  without modifying the original"]
979    #[stable(feature = "float_approx_unchecked_to", since = "1.44.0")]
980    #[inline]
981    pub unsafe fn to_int_unchecked<Int>(self) -> Int
982    where
983        Self: FloatToInt<Int>,
984    {
985        // SAFETY: the caller must uphold the safety contract for
986        // `FloatToInt::to_int_unchecked`.
987        unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
988    }
989
990    /// Converts to the target float type, rounding as defined in IEEE 754.
991    ///
992    /// This is equivalent to `self as Flt`. Narrowing to a smaller type can
993    /// produce an infinity.
994    ///
995    /// ```
996    /// #![feature(float_conversions)]
997    ///
998    /// let x = 1.5_f64;
999    /// assert_eq!(x.cast::<f32>(), 1.5_f32);
1000    /// ```
1001    #[unstable(feature = "float_conversions", issue = "159913")]
1002    #[must_use = "this returns the result of the operation, without modifying the original"]
1003    #[inline]
1004    pub fn cast<Flt>(self) -> Flt
1005    where
1006        Self: FloatToFloat<Flt>,
1007    {
1008        FloatToFloat::<Flt>::cast(self)
1009    }
1010
1011    /// Rounds toward zero and converts to any primitive integer type, saturating
1012    /// at the type's boundaries and mapping `NaN` to zero.
1013    ///
1014    /// This is equivalent to `self as Int`.
1015    ///
1016    /// ```
1017    /// #![feature(float_conversions)]
1018    ///
1019    /// assert_eq!(255.5_f64.to_int_saturating::<u8>(), 255);
1020    /// assert_eq!(300.0_f64.to_int_saturating::<u8>(), 255);
1021    /// assert_eq!((-1.0_f64).to_int_saturating::<u8>(), 0);
1022    /// assert_eq!(f64::NAN.to_int_saturating::<u8>(), 0);
1023    /// ```
1024    #[unstable(feature = "float_conversions", issue = "159913")]
1025    #[must_use = "this returns the result of the operation, without modifying the original"]
1026    #[inline]
1027    pub fn to_int_saturating<Int>(self) -> Int
1028    where
1029        Self: FloatToInt<Int>,
1030    {
1031        FloatToInt::<Int>::to_int_saturating(self)
1032    }
1033
1034    /// Rounds toward zero and converts to any primitive integer type, returning
1035    /// `None` if the value is `NaN`, infinite, or does not fit in the target type.
1036    ///
1037    /// ```
1038    /// #![feature(float_conversions)]
1039    ///
1040    /// assert_eq!(255.5_f64.to_int_checked::<u8>(), Some(255));
1041    /// assert_eq!(256.0_f64.to_int_checked::<u8>(), None);
1042    /// assert_eq!(f64::NAN.to_int_checked::<u8>(), None);
1043    /// ```
1044    #[unstable(feature = "float_conversions", issue = "159913")]
1045    #[must_use = "this returns the result of the operation, without modifying the original"]
1046    #[inline]
1047    pub fn to_int_checked<Int>(self) -> Option<Int>
1048    where
1049        Self: FloatToInt<Int>,
1050    {
1051        FloatToInt::<Int>::to_int_checked(self)
1052    }
1053
1054    /// Rounds toward zero and converts to any primitive integer type.
1055    ///
1056    /// This is equivalent to `self.to_int_checked().unwrap()`.
1057    ///
1058    /// # Panics
1059    ///
1060    /// Panics if the value is `NaN`, infinite, or does not fit in the target type.
1061    ///
1062    /// ```
1063    /// #![feature(float_conversions)]
1064    ///
1065    /// assert_eq!(255.5_f64.to_int_strict::<u8>(), 255);
1066    /// ```
1067    #[unstable(feature = "float_conversions", issue = "159913")]
1068    #[must_use = "this returns the result of the operation, without modifying the original"]
1069    #[inline]
1070    #[track_caller]
1071    pub fn to_int_strict<Int>(self) -> Int
1072    where
1073        Self: FloatToInt<Int>,
1074    {
1075        self.to_int_checked::<Int>()
1076            .expect("the value cannot be represented in the target integer type")
1077    }
1078
1079    /// Raw transmutation to `u64`.
1080    ///
1081    /// This is currently identical to `transmute::<f64, u64>(self)` on all platforms.
1082    ///
1083    /// See [`from_bits`](Self::from_bits) for some discussion of the
1084    /// portability of this operation (there are almost no issues).
1085    ///
1086    /// Note that this function is distinct from `as` casting, which attempts to
1087    /// preserve the *numeric* value, and not the bitwise value.
1088    ///
1089    /// # Examples
1090    ///
1091    /// ```
1092    /// assert!((1f64).to_bits() != 1f64 as u64); // to_bits() is not casting!
1093    /// assert_eq!((12.5f64).to_bits(), 0x4029000000000000);
1094    /// ```
1095    #[must_use = "this returns the result of the operation, \
1096                  without modifying the original"]
1097    #[stable(feature = "float_bits_conv", since = "1.20.0")]
1098    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1099    #[allow(unnecessary_transmutes)]
1100    #[inline]
1101    #[ferrocene::prevalidated]
1102    pub const fn to_bits(self) -> u64 {
1103        // SAFETY: `u64` is a plain old datatype so we can always transmute to it.
1104        unsafe { mem::transmute(self) }
1105    }
1106
1107    /// Raw transmutation from `u64`.
1108    ///
1109    /// This is currently identical to `transmute::<u64, f64>(v)` on all platforms.
1110    /// It turns out this is incredibly portable, for two reasons:
1111    ///
1112    /// * Floats and Ints have the same endianness on all supported platforms.
1113    /// * IEEE 754 very precisely specifies the bit layout of floats.
1114    ///
1115    /// However there is one caveat: prior to the 2008 version of IEEE 754, how
1116    /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
1117    /// (notably x86 and ARM) picked the interpretation that was ultimately
1118    /// standardized in 2008, but some didn't (notably MIPS). As a result, all
1119    /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
1120    ///
1121    /// Rather than trying to preserve signaling-ness cross-platform, this
1122    /// implementation favors preserving the exact bits. This means that
1123    /// any payloads encoded in NaNs will be preserved even if the result of
1124    /// this method is sent over the network from an x86 machine to a MIPS one.
1125    ///
1126    /// If the results of this method are only manipulated by the same
1127    /// architecture that produced them, then there is no portability concern.
1128    ///
1129    /// If the input isn't NaN, then there is no portability concern.
1130    ///
1131    /// If you don't care about signaling-ness (very likely), then there is no
1132    /// portability concern.
1133    ///
1134    /// Note that this function is distinct from `as` casting, which attempts to
1135    /// preserve the *numeric* value, and not the bitwise value.
1136    ///
1137    /// # Examples
1138    ///
1139    /// ```
1140    /// let v = f64::from_bits(0x4029000000000000);
1141    /// assert_eq!(v, 12.5);
1142    /// ```
1143    #[stable(feature = "float_bits_conv", since = "1.20.0")]
1144    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1145    #[must_use]
1146    #[inline]
1147    #[allow(unnecessary_transmutes)]
1148    #[ferrocene::prevalidated]
1149    pub const fn from_bits(v: u64) -> Self {
1150        // It turns out the safety issues with sNaN were overblown! Hooray!
1151        // SAFETY: `u64` is a plain old datatype so we can always transmute from it.
1152        unsafe { mem::transmute(v) }
1153    }
1154
1155    /// Returns the memory representation of this floating point number as a byte array in
1156    /// big-endian (network) byte order.
1157    ///
1158    /// See [`from_bits`](Self::from_bits) for some discussion of the
1159    /// portability of this operation (there are almost no issues).
1160    ///
1161    /// # Examples
1162    ///
1163    /// ```
1164    /// let bytes = 12.5f64.to_be_bytes();
1165    /// assert_eq!(bytes, [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1166    /// ```
1167    #[must_use = "this returns the result of the operation, \
1168                  without modifying the original"]
1169    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1170    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1171    #[inline]
1172    pub const fn to_be_bytes(self) -> [u8; 8] {
1173        self.to_bits().to_be_bytes()
1174    }
1175
1176    /// Returns the memory representation of this floating point number as a byte array in
1177    /// little-endian byte order.
1178    ///
1179    /// See [`from_bits`](Self::from_bits) for some discussion of the
1180    /// portability of this operation (there are almost no issues).
1181    ///
1182    /// # Examples
1183    ///
1184    /// ```
1185    /// let bytes = 12.5f64.to_le_bytes();
1186    /// assert_eq!(bytes, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]);
1187    /// ```
1188    #[must_use = "this returns the result of the operation, \
1189                  without modifying the original"]
1190    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1191    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1192    #[inline]
1193    #[ferrocene::prevalidated]
1194    pub const fn to_le_bytes(self) -> [u8; 8] {
1195        self.to_bits().to_le_bytes()
1196    }
1197
1198    /// Returns the memory representation of this floating point number as a byte array in
1199    /// native byte order.
1200    ///
1201    /// As the target platform's native endianness is used, portable code
1202    /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1203    ///
1204    /// [`to_be_bytes`]: f64::to_be_bytes
1205    /// [`to_le_bytes`]: f64::to_le_bytes
1206    ///
1207    /// See [`from_bits`](Self::from_bits) for some discussion of the
1208    /// portability of this operation (there are almost no issues).
1209    ///
1210    /// # Examples
1211    ///
1212    /// ```
1213    /// let bytes = 12.5f64.to_ne_bytes();
1214    /// assert_eq!(
1215    ///     bytes,
1216    ///     if cfg!(target_endian = "big") {
1217    ///         [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1218    ///     } else {
1219    ///         [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]
1220    ///     }
1221    /// );
1222    /// ```
1223    #[must_use = "this returns the result of the operation, \
1224                  without modifying the original"]
1225    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1226    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1227    #[inline]
1228    pub const fn to_ne_bytes(self) -> [u8; 8] {
1229        self.to_bits().to_ne_bytes()
1230    }
1231
1232    /// Creates a floating point value from its representation as a byte array in big endian.
1233    ///
1234    /// See [`from_bits`](Self::from_bits) for some discussion of the
1235    /// portability of this operation (there are almost no issues).
1236    ///
1237    /// # Examples
1238    ///
1239    /// ```
1240    /// let value = f64::from_be_bytes([0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1241    /// assert_eq!(value, 12.5);
1242    /// ```
1243    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1244    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1245    #[must_use]
1246    #[inline]
1247    pub const fn from_be_bytes(bytes: [u8; 8]) -> Self {
1248        Self::from_bits(u64::from_be_bytes(bytes))
1249    }
1250
1251    /// Creates a floating point value from its representation as a byte array in little endian.
1252    ///
1253    /// See [`from_bits`](Self::from_bits) for some discussion of the
1254    /// portability of this operation (there are almost no issues).
1255    ///
1256    /// # Examples
1257    ///
1258    /// ```
1259    /// let value = f64::from_le_bytes([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]);
1260    /// assert_eq!(value, 12.5);
1261    /// ```
1262    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1263    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1264    #[must_use]
1265    #[inline]
1266    #[ferrocene::prevalidated]
1267    pub const fn from_le_bytes(bytes: [u8; 8]) -> Self {
1268        Self::from_bits(u64::from_le_bytes(bytes))
1269    }
1270
1271    /// Creates a floating point value from its representation as a byte array in native endian.
1272    ///
1273    /// As the target platform's native endianness is used, portable code
1274    /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1275    /// appropriate instead.
1276    ///
1277    /// [`from_be_bytes`]: f64::from_be_bytes
1278    /// [`from_le_bytes`]: f64::from_le_bytes
1279    ///
1280    /// See [`from_bits`](Self::from_bits) for some discussion of the
1281    /// portability of this operation (there are almost no issues).
1282    ///
1283    /// # Examples
1284    ///
1285    /// ```
1286    /// let value = f64::from_ne_bytes(if cfg!(target_endian = "big") {
1287    ///     [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1288    /// } else {
1289    ///     [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]
1290    /// });
1291    /// assert_eq!(value, 12.5);
1292    /// ```
1293    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1294    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1295    #[must_use]
1296    #[inline]
1297    pub const fn from_ne_bytes(bytes: [u8; 8]) -> Self {
1298        Self::from_bits(u64::from_ne_bytes(bytes))
1299    }
1300
1301    /// Returns the ordering between `self` and `other`.
1302    ///
1303    /// Unlike the standard partial comparison between floating point numbers,
1304    /// this comparison always produces an ordering in accordance to
1305    /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1306    /// floating point standard. The values are ordered in the following sequence:
1307    ///
1308    /// - negative quiet NaN
1309    /// - negative signaling NaN
1310    /// - negative infinity
1311    /// - negative numbers
1312    /// - negative subnormal numbers
1313    /// - negative zero
1314    /// - positive zero
1315    /// - positive subnormal numbers
1316    /// - positive numbers
1317    /// - positive infinity
1318    /// - positive signaling NaN
1319    /// - positive quiet NaN.
1320    ///
1321    /// The ordering established by this function does not always agree with the
1322    /// [`PartialOrd`] and [`PartialEq`] implementations of `f64`. For example,
1323    /// they consider negative and positive zero equal, while `total_cmp`
1324    /// doesn't.
1325    ///
1326    /// The interpretation of the signaling NaN bit follows the definition in
1327    /// the IEEE 754 standard, which may not match the interpretation by some of
1328    /// the older, non-conformant (e.g. MIPS) hardware implementations.
1329    ///
1330    /// # Example
1331    ///
1332    /// ```
1333    /// struct GoodBoy {
1334    ///     name: String,
1335    ///     weight: f64,
1336    /// }
1337    ///
1338    /// let mut bois = vec![
1339    ///     GoodBoy { name: "Pucci".to_owned(), weight: 0.1 },
1340    ///     GoodBoy { name: "Woofer".to_owned(), weight: 99.0 },
1341    ///     GoodBoy { name: "Yapper".to_owned(), weight: 10.0 },
1342    ///     GoodBoy { name: "Chonk".to_owned(), weight: f64::INFINITY },
1343    ///     GoodBoy { name: "Abs. Unit".to_owned(), weight: f64::NAN },
1344    ///     GoodBoy { name: "Floaty".to_owned(), weight: -5.0 },
1345    /// ];
1346    ///
1347    /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1348    ///
1349    /// // `f64::NAN` could be positive or negative, which will affect the sort order.
1350    /// if f64::NAN.is_sign_negative() {
1351    ///     assert!(bois.into_iter().map(|b| b.weight)
1352    ///         .zip([f64::NAN, -5.0, 0.1, 10.0, 99.0, f64::INFINITY].iter())
1353    ///         .all(|(a, b)| a.to_bits() == b.to_bits()))
1354    /// } else {
1355    ///     assert!(bois.into_iter().map(|b| b.weight)
1356    ///         .zip([-5.0, 0.1, 10.0, 99.0, f64::INFINITY, f64::NAN].iter())
1357    ///         .all(|(a, b)| a.to_bits() == b.to_bits()))
1358    /// }
1359    /// ```
1360    #[stable(feature = "total_cmp", since = "1.62.0")]
1361    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1362    #[must_use]
1363    #[inline]
1364    pub const fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1365        let mut left = self.to_bits() as i64;
1366        let mut right = other.to_bits() as i64;
1367
1368        // In case of negatives, flip all the bits except the sign
1369        // to achieve a similar layout as two's complement integers
1370        //
1371        // Why does this work? IEEE 754 floats consist of three fields:
1372        // Sign bit, exponent and mantissa. The set of exponent and mantissa
1373        // fields as a whole have the property that their bitwise order is
1374        // equal to the numeric magnitude where the magnitude is defined.
1375        // The magnitude is not normally defined on NaN values, but
1376        // IEEE 754 totalOrder defines the NaN values also to follow the
1377        // bitwise order. This leads to order explained in the doc comment.
1378        // However, the representation of magnitude is the same for negative
1379        // and positive numbers – only the sign bit is different.
1380        // To easily compare the floats as signed integers, we need to
1381        // flip the exponent and mantissa bits in case of negative numbers.
1382        // We effectively convert the numbers to "two's complement" form.
1383        //
1384        // To do the flipping, we construct a mask and XOR against it.
1385        // We branchlessly calculate an "all-ones except for the sign bit"
1386        // mask from negative-signed values: right shifting sign-extends
1387        // the integer, so we "fill" the mask with sign bits, and then
1388        // convert to unsigned to push one more zero bit.
1389        // On positive values, the mask is all zeros, so it's a no-op.
1390        left ^= (((left >> 63) as u64) >> 1) as i64;
1391        right ^= (((right >> 63) as u64) >> 1) as i64;
1392
1393        left.cmp(&right)
1394    }
1395
1396    /// Restrict a value to a certain interval unless it is NaN.
1397    ///
1398    /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1399    /// less than `min`. Otherwise this returns `self`.
1400    ///
1401    /// Note that this function returns NaN if the initial value was NaN as
1402    /// well. If the result is zero and among the three inputs `self`, `min`, and `max` there are
1403    /// zeros with different sign, either `0.0` or `-0.0` is returned non-deterministically.
1404    ///
1405    /// # Panics
1406    ///
1407    /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1408    ///
1409    /// # Examples
1410    ///
1411    /// ```
1412    /// assert!((-3.0f64).clamp(-2.0, 1.0) == -2.0);
1413    /// assert!((0.0f64).clamp(-2.0, 1.0) == 0.0);
1414    /// assert!((2.0f64).clamp(-2.0, 1.0) == 1.0);
1415    /// assert!((f64::NAN).clamp(-2.0, 1.0).is_nan());
1416    ///
1417    /// // These always returns zero, but the sign (which is ignored by `==`) is non-deterministic.
1418    /// assert!((0.0f64).clamp(-0.0, -0.0) == 0.0);
1419    /// assert!((1.0f64).clamp(-0.0, 0.0) == 0.0);
1420    /// // This is definitely a negative zero.
1421    /// assert!((-1.0f64).clamp(-0.0, 1.0).is_sign_negative());
1422    /// ```
1423    #[must_use = "method returns a new number and does not mutate the original value"]
1424    #[stable(feature = "clamp", since = "1.50.0")]
1425    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1426    #[inline]
1427    #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "NaN is also invalid")]
1428    pub const fn clamp(mut self, min: f64, max: f64) -> f64 {
1429        const_assert!(
1430            min <= max,
1431            "min > max, or either was NaN",
1432            "min > max, or either was NaN. min = {min:?}, max = {max:?}",
1433            min: f64,
1434            max: f64,
1435        );
1436
1437        if self < min {
1438            self = min;
1439        }
1440        if self > max {
1441            self = max;
1442        }
1443        self
1444    }
1445
1446    /// Clamps this number to a symmetric range centered around zero.
1447    ///
1448    /// The method clamps the number's magnitude (absolute value) to be at most `limit`.
1449    ///
1450    /// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more
1451    /// explicit about the intent.
1452    ///
1453    /// # Panics
1454    ///
1455    /// Panics if `limit` is negative or NaN, as this indicates a logic error.
1456    ///
1457    /// # Examples
1458    ///
1459    /// ```
1460    /// #![feature(clamp_magnitude)]
1461    /// assert_eq!(5.0f64.clamp_magnitude(3.0), 3.0);
1462    /// assert_eq!((-5.0f64).clamp_magnitude(3.0), -3.0);
1463    /// assert_eq!(2.0f64.clamp_magnitude(3.0), 2.0);
1464    /// assert_eq!((-2.0f64).clamp_magnitude(3.0), -2.0);
1465    /// ```
1466    #[inline]
1467    #[unstable(feature = "clamp_magnitude", issue = "148519")]
1468    #[must_use = "method returns a new number and does not mutate the original value"]
1469    #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "NaN is also invalid")]
1470    pub const fn clamp_magnitude(self, limit: f64) -> f64 {
1471        assert!(limit >= 0.0, "limit must be non-negative and not NaN");
1472        let limit = limit.abs(); // Canonicalises -0.0 to 0.0
1473        self.clamp(-limit, limit)
1474    }
1475
1476    /// Restrict a value to a certain range, unless it is NaN.
1477    ///
1478    /// This is largely equal to `max`, `min`, or `clamp`, depending on whether the range is
1479    /// `min..`, `..=max`, or `min..=max`, respectively. However, unlike `max` and `min`, it will
1480    /// panic if any bound is NaN.
1481    ///
1482    /// Note that this function returns NaN if the initial value was NaN as
1483    /// well.
1484    ///
1485    /// Exclusive ranges are not permitted.
1486    ///
1487    /// # Panics
1488    ///
1489    /// Panics on `min..=max` if `min > max`, or if any bound is NaN.
1490    ///
1491    /// # Examples
1492    ///
1493    /// ```
1494    /// #![feature(clamp_to)]
1495    /// assert_eq!((-3.0f64).clamp_to(-2.0..=1.0), -2.0);
1496    /// assert_eq!(0.0f64.clamp_to(-2.0..=1.0), 0.0);
1497    /// assert_eq!(2.0f64.clamp_to(..=1.0), 1.0);
1498    /// assert_eq!(5.0f64.clamp_to(7.0..), 7.0);
1499    /// assert!(f64::NAN.clamp_to(1.0..=2.0).is_nan());
1500    /// ```
1501    #[must_use]
1502    #[inline]
1503    #[unstable(feature = "clamp_to", issue = "147781")]
1504    pub fn clamp_to<R>(self, range: R) -> Self
1505    where
1506        R: crate::cmp::ClampBounds<Self>,
1507    {
1508        range.clamp(self)
1509    }
1510
1511    /// Computes the absolute value of `self`.
1512    ///
1513    /// This function always returns the precise result.
1514    ///
1515    /// # Examples
1516    ///
1517    /// ```
1518    /// let x = 3.5_f64;
1519    /// let y = -3.5_f64;
1520    ///
1521    /// assert_eq!(x.abs(), x);
1522    /// assert_eq!(y.abs(), -y);
1523    ///
1524    /// assert!(f64::NAN.abs().is_nan());
1525    /// ```
1526    #[must_use = "method returns a new number and does not mutate the original value"]
1527    #[stable(feature = "rust1", since = "1.0.0")]
1528    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1529    #[inline]
1530    #[ferrocene::prevalidated]
1531    pub const fn abs(self) -> f64 {
1532        intrinsics::fabs(self)
1533    }
1534
1535    /// Returns a number that represents the sign of `self`.
1536    ///
1537    /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
1538    /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
1539    /// - NaN if the number is NaN
1540    ///
1541    /// # Examples
1542    ///
1543    /// ```
1544    /// let f = 3.5_f64;
1545    ///
1546    /// assert_eq!(f.signum(), 1.0);
1547    /// assert_eq!(f64::NEG_INFINITY.signum(), -1.0);
1548    ///
1549    /// assert!(f64::NAN.signum().is_nan());
1550    /// ```
1551    #[must_use = "method returns a new number and does not mutate the original value"]
1552    #[stable(feature = "rust1", since = "1.0.0")]
1553    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1554    #[inline]
1555    pub const fn signum(self) -> f64 {
1556        if self.is_nan() { Self::NAN } else { 1.0_f64.copysign(self) }
1557    }
1558
1559    /// Returns a number composed of the magnitude of `self` and the sign of
1560    /// `sign`.
1561    ///
1562    /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`.
1563    /// If `self` is a NaN, then a NaN with the same payload as `self` and the sign bit of `sign` is
1564    /// returned.
1565    ///
1566    /// If `sign` is a NaN, then this operation will still carry over its sign into the result. Note
1567    /// that IEEE 754 doesn't assign any meaning to the sign bit in case of a NaN, and as Rust
1568    /// doesn't guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the
1569    /// result of `copysign` with `sign` being a NaN might produce an unexpected or non-portable
1570    /// result. See the [specification of NaN bit patterns](primitive@f32#nan-bit-patterns) for more
1571    /// info.
1572    ///
1573    /// # Examples
1574    ///
1575    /// ```
1576    /// let f = 3.5_f64;
1577    ///
1578    /// assert_eq!(f.copysign(0.42), 3.5_f64);
1579    /// assert_eq!(f.copysign(-0.42), -3.5_f64);
1580    /// assert_eq!((-f).copysign(0.42), 3.5_f64);
1581    /// assert_eq!((-f).copysign(-0.42), -3.5_f64);
1582    ///
1583    /// assert!(f64::NAN.copysign(1.0).is_nan());
1584    /// ```
1585    #[must_use = "method returns a new number and does not mutate the original value"]
1586    #[stable(feature = "copysign", since = "1.35.0")]
1587    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1588    #[inline]
1589    #[ferrocene::prevalidated]
1590    pub const fn copysign(self, sign: f64) -> f64 {
1591        intrinsics::copysignf64(self, sign)
1592    }
1593
1594    /// Float addition that allows optimizations based on algebraic rules.
1595    ///
1596    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1597    #[must_use = "method returns a new number and does not mutate the original value"]
1598    #[stable(feature = "float_algebraic", since = "1.98.0")]
1599    #[rustc_const_stable(feature = "float_algebraic", since = "1.98.0")]
1600    #[inline]
1601    pub const fn algebraic_add(self, rhs: f64) -> f64 {
1602        intrinsics::fadd_algebraic(self, rhs)
1603    }
1604
1605    /// Float subtraction that allows optimizations based on algebraic rules.
1606    ///
1607    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1608    #[must_use = "method returns a new number and does not mutate the original value"]
1609    #[stable(feature = "float_algebraic", since = "1.98.0")]
1610    #[rustc_const_stable(feature = "float_algebraic", since = "1.98.0")]
1611    #[inline]
1612    pub const fn algebraic_sub(self, rhs: f64) -> f64 {
1613        intrinsics::fsub_algebraic(self, rhs)
1614    }
1615
1616    /// Float multiplication that allows optimizations based on algebraic rules.
1617    ///
1618    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1619    #[must_use = "method returns a new number and does not mutate the original value"]
1620    #[stable(feature = "float_algebraic", since = "1.98.0")]
1621    #[rustc_const_stable(feature = "float_algebraic", since = "1.98.0")]
1622    #[inline]
1623    pub const fn algebraic_mul(self, rhs: f64) -> f64 {
1624        intrinsics::fmul_algebraic(self, rhs)
1625    }
1626
1627    /// Float division that allows optimizations based on algebraic rules.
1628    ///
1629    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1630    #[must_use = "method returns a new number and does not mutate the original value"]
1631    #[stable(feature = "float_algebraic", since = "1.98.0")]
1632    #[rustc_const_stable(feature = "float_algebraic", since = "1.98.0")]
1633    #[inline]
1634    pub const fn algebraic_div(self, rhs: f64) -> f64 {
1635        intrinsics::fdiv_algebraic(self, rhs)
1636    }
1637
1638    /// Float remainder that allows optimizations based on algebraic rules.
1639    ///
1640    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1641    #[must_use = "method returns a new number and does not mutate the original value"]
1642    #[stable(feature = "float_algebraic", since = "1.98.0")]
1643    #[rustc_const_stable(feature = "float_algebraic", since = "1.98.0")]
1644    #[inline]
1645    pub const fn algebraic_rem(self, rhs: f64) -> f64 {
1646        intrinsics::frem_algebraic(self, rhs)
1647    }
1648
1649    /// Computes `(self * a) + b` with nondeterministic rounding.
1650    ///
1651    /// This is similar to [`mul_add`], but the intermediate result may be
1652    /// rounded differently depending on the implementation. The operation is
1653    /// either executed as a single fused multiply-add instruction, or as
1654    /// separate multiply and add instructions.
1655    ///
1656    /// The choice of which one is used is unspecified and non-deterministic:
1657    /// it may vary by target, optimization level, and surrounding code, and
1658    /// even two invocations of this operation with the same inputs may
1659    /// produce different results.
1660    ///
1661    /// # Precision
1662    ///
1663    /// The result of this operation is not guaranteed: it is either the result
1664    /// of [`mul_add`] (one rounding of the infinite-precision result) or of
1665    /// `self * a + b` (two roundings, with an intermediate rounding of the
1666    /// product).
1667    ///
1668    /// # Examples
1669    ///
1670    /// ```
1671    /// #![feature(float_mul_add_relaxed)]
1672    ///
1673    /// // When the fused and unfused operations round differently, either
1674    /// // result may be returned:
1675    /// // - 9.020562075079397e-19 is the fused result (one rounding)
1676    /// // - 1.734723475976807e-18 is the unfused result (two roundings)
1677    /// # // FIXME(#114479): on `i586`, x87 excess precision gives neither allowed result
1678    /// # #[cfg(not(all(target_arch = "x86", not(target_feature = "sse2"))))] {
1679    /// let r = 0.1_f64.mul_add_relaxed(0.1_f64, -0.01_f64);
1680    /// assert!(r == 9.020562075079397e-19 || r == 1.734723475976807e-18);
1681    /// # }
1682    /// ```
1683    ///
1684    /// [`mul_add`]: ../std/primitive.f64.html#method.mul_add
1685    #[must_use = "method returns a new number and does not mutate the original value"]
1686    #[doc(alias = "fmuladd")]
1687    #[unstable(feature = "float_mul_add_relaxed", issue = "151770")]
1688    #[inline]
1689    pub const fn mul_add_relaxed(self, a: f64, b: f64) -> f64 {
1690        intrinsics::fmuladd(self, a, b)
1691    }
1692
1693    /// Returns `self` if the value is not NaN, otherwise returns `replacement`
1694    /// if `self` is NaN.
1695    ///
1696    /// # Examples
1697    ///
1698    /// ```
1699    /// #![feature(float_nan_to)]
1700    ///
1701    /// let n = f64::NAN;
1702    /// let x = 2.0f64;
1703    /// let y = f64::INFINITY;
1704    ///
1705    /// assert_eq!(n.nan_to(0.0f64), 0.0f64);
1706    /// assert_eq!(x.nan_to(0.0f64), 2.0f64);
1707    /// assert_eq!(y.nan_to(0.0f64), f64::INFINITY);
1708    /// ```
1709    #[must_use = "method returns a new float and does not mutate the original value"]
1710    #[unstable(feature = "float_nan_to", issue = "161248")]
1711    #[rustc_const_unstable(feature = "float_nan_to", issue = "161248")]
1712    #[inline]
1713    pub const fn nan_to(self, replacement: f64) -> f64 {
1714        if self.is_nan() { replacement } else { self }
1715    }
1716}
1717
1718#[unstable(feature = "core_float_math", issue = "137578")]
1719/// Experimental implementations of floating point functions in `core`.
1720///
1721/// _The standalone functions in this module are for testing only.
1722/// They will be stabilized as inherent methods._
1723pub mod math {
1724    use crate::intrinsics;
1725    use crate::num::imp::libm;
1726
1727    /// Experimental version of `floor` in `core`. See [`f64::floor`] for details.
1728    ///
1729    /// # Examples
1730    ///
1731    /// ```
1732    /// #![feature(core_float_math)]
1733    ///
1734    /// use core::f64;
1735    ///
1736    /// let f = 3.7_f64;
1737    /// let g = 3.0_f64;
1738    /// let h = -3.7_f64;
1739    ///
1740    /// assert_eq!(f64::math::floor(f), 3.0);
1741    /// assert_eq!(f64::math::floor(g), 3.0);
1742    /// assert_eq!(f64::math::floor(h), -4.0);
1743    /// ```
1744    ///
1745    /// _This standalone function is for testing only.
1746    /// It will be stabilized as an inherent method._
1747    ///
1748    /// [`f64::floor`]: ../../../std/primitive.f64.html#method.floor
1749    #[inline]
1750    #[unstable(feature = "core_float_math", issue = "137578")]
1751    #[must_use = "method returns a new number and does not mutate the original value"]
1752    pub const fn floor(x: f64) -> f64 {
1753        intrinsics::floor(x)
1754    }
1755
1756    /// Experimental version of `ceil` in `core`. See [`f64::ceil`] for details.
1757    ///
1758    /// # Examples
1759    ///
1760    /// ```
1761    /// #![feature(core_float_math)]
1762    ///
1763    /// use core::f64;
1764    ///
1765    /// let f = 3.01_f64;
1766    /// let g = 4.0_f64;
1767    ///
1768    /// assert_eq!(f64::math::ceil(f), 4.0);
1769    /// assert_eq!(f64::math::ceil(g), 4.0);
1770    /// ```
1771    ///
1772    /// _This standalone function is for testing only.
1773    /// It will be stabilized as an inherent method._
1774    ///
1775    /// [`f64::ceil`]: ../../../std/primitive.f64.html#method.ceil
1776    #[inline]
1777    #[doc(alias = "ceiling")]
1778    #[unstable(feature = "core_float_math", issue = "137578")]
1779    #[must_use = "method returns a new number and does not mutate the original value"]
1780    pub const fn ceil(x: f64) -> f64 {
1781        intrinsics::ceil(x)
1782    }
1783
1784    /// Experimental version of `round` in `core`. See [`f64::round`] for details.
1785    ///
1786    /// # Examples
1787    ///
1788    /// ```
1789    /// #![feature(core_float_math)]
1790    ///
1791    /// use core::f64;
1792    ///
1793    /// let f = 3.3_f64;
1794    /// let g = -3.3_f64;
1795    /// let h = -3.7_f64;
1796    /// let i = 3.5_f64;
1797    /// let j = 4.5_f64;
1798    ///
1799    /// assert_eq!(f64::math::round(f), 3.0);
1800    /// assert_eq!(f64::math::round(g), -3.0);
1801    /// assert_eq!(f64::math::round(h), -4.0);
1802    /// assert_eq!(f64::math::round(i), 4.0);
1803    /// assert_eq!(f64::math::round(j), 5.0);
1804    /// ```
1805    ///
1806    /// _This standalone function is for testing only.
1807    /// It will be stabilized as an inherent method._
1808    ///
1809    /// [`f64::round`]: ../../../std/primitive.f64.html#method.round
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 round(x: f64) -> f64 {
1814        intrinsics::round(x)
1815    }
1816
1817    /// Experimental version of `round_ties_even` in `core`. See [`f64::round_ties_even`] for
1818    /// details.
1819    ///
1820    /// # Examples
1821    ///
1822    /// ```
1823    /// #![feature(core_float_math)]
1824    ///
1825    /// use core::f64;
1826    ///
1827    /// let f = 3.3_f64;
1828    /// let g = -3.3_f64;
1829    /// let h = 3.5_f64;
1830    /// let i = 4.5_f64;
1831    ///
1832    /// assert_eq!(f64::math::round_ties_even(f), 3.0);
1833    /// assert_eq!(f64::math::round_ties_even(g), -3.0);
1834    /// assert_eq!(f64::math::round_ties_even(h), 4.0);
1835    /// assert_eq!(f64::math::round_ties_even(i), 4.0);
1836    /// ```
1837    ///
1838    /// _This standalone function is for testing only.
1839    /// It will be stabilized as an inherent method._
1840    ///
1841    /// [`f64::round_ties_even`]: ../../../std/primitive.f64.html#method.round_ties_even
1842    #[inline]
1843    #[unstable(feature = "core_float_math", issue = "137578")]
1844    #[must_use = "method returns a new number and does not mutate the original value"]
1845    pub const fn round_ties_even(x: f64) -> f64 {
1846        intrinsics::round_ties_even(x)
1847    }
1848
1849    /// Experimental version of `trunc` in `core`. See [`f64::trunc`] for details.
1850    ///
1851    /// # Examples
1852    ///
1853    /// ```
1854    /// #![feature(core_float_math)]
1855    ///
1856    /// use core::f64;
1857    ///
1858    /// let f = 3.7_f64;
1859    /// let g = 3.0_f64;
1860    /// let h = -3.7_f64;
1861    ///
1862    /// assert_eq!(f64::math::trunc(f), 3.0);
1863    /// assert_eq!(f64::math::trunc(g), 3.0);
1864    /// assert_eq!(f64::math::trunc(h), -3.0);
1865    /// ```
1866    ///
1867    /// _This standalone function is for testing only.
1868    /// It will be stabilized as an inherent method._
1869    ///
1870    /// [`f64::trunc`]: ../../../std/primitive.f64.html#method.trunc
1871    #[inline]
1872    #[doc(alias = "truncate")]
1873    #[unstable(feature = "core_float_math", issue = "137578")]
1874    #[must_use = "method returns a new number and does not mutate the original value"]
1875    pub const fn trunc(x: f64) -> f64 {
1876        intrinsics::trunc(x)
1877    }
1878
1879    /// Experimental version of `fract` in `core`. See [`f64::fract`] for details.
1880    ///
1881    /// # Examples
1882    ///
1883    /// ```
1884    /// #![feature(core_float_math)]
1885    ///
1886    /// use core::f64;
1887    ///
1888    /// let x = 3.6_f64;
1889    /// let y = -3.6_f64;
1890    /// let abs_difference_x = (f64::math::fract(x) - 0.6).abs();
1891    /// let abs_difference_y = (f64::math::fract(y) - (-0.6)).abs();
1892    ///
1893    /// assert!(abs_difference_x < 1e-10);
1894    /// assert!(abs_difference_y < 1e-10);
1895    /// ```
1896    ///
1897    /// _This standalone function is for testing only.
1898    /// It will be stabilized as an inherent method._
1899    ///
1900    /// [`f64::fract`]: ../../../std/primitive.f64.html#method.fract
1901    #[inline]
1902    #[unstable(feature = "core_float_math", issue = "137578")]
1903    #[must_use = "method returns a new number and does not mutate the original value"]
1904    pub const fn fract(x: f64) -> f64 {
1905        x - trunc(x)
1906    }
1907
1908    /// Experimental version of `mul_add` in `core`. See [`f64::mul_add`] for details.
1909    ///
1910    /// # Examples
1911    ///
1912    /// ```
1913    /// # #![allow(unused_features)]
1914    /// #![feature(core_float_math)]
1915    ///
1916    /// # // FIXME(#140515): mingw has an incorrect fma
1917    /// # // https://sourceforge.net/p/mingw-w64/bugs/848/
1918    /// # #[cfg(all(target_os = "windows", target_env = "gnu", not(target_abi = "llvm")))] {
1919    /// use core::f64;
1920    ///
1921    /// let m = 10.0_f64;
1922    /// let x = 4.0_f64;
1923    /// let b = 60.0_f64;
1924    ///
1925    /// assert_eq!(f64::math::mul_add(m, x, b), 100.0);
1926    /// assert_eq!(m * x + b, 100.0);
1927    ///
1928    /// let one_plus_eps = 1.0_f64 + f64::EPSILON;
1929    /// let one_minus_eps = 1.0_f64 - f64::EPSILON;
1930    /// let minus_one = -1.0_f64;
1931    ///
1932    /// // The exact result (1 + eps) * (1 - eps) = 1 - eps * eps.
1933    /// assert_eq!(
1934    ///     f64::math::mul_add(one_plus_eps, one_minus_eps, minus_one),
1935    ///     -f64::EPSILON * f64::EPSILON
1936    /// );
1937    /// // Different rounding with the non-fused multiply and add.
1938    /// assert_eq!(one_plus_eps * one_minus_eps + minus_one, 0.0);
1939    /// # }
1940    /// ```
1941    ///
1942    /// _This standalone function is for testing only.
1943    /// It will be stabilized as an inherent method._
1944    ///
1945    /// [`f64::mul_add`]: ../../../std/primitive.f64.html#method.mul_add
1946    #[inline]
1947    #[doc(alias = "fma", alias = "fusedMultiplyAdd")]
1948    #[unstable(feature = "core_float_math", issue = "137578")]
1949    #[must_use = "method returns a new number and does not mutate the original value"]
1950    pub const fn mul_add(x: f64, a: f64, b: f64) -> f64 {
1951        intrinsics::fma(x, a, b)
1952    }
1953
1954    /// Experimental version of `div_euclid` in `core`. See [`f64::div_euclid`] for details.
1955    ///
1956    /// # Examples
1957    ///
1958    /// ```
1959    /// #![feature(core_float_math)]
1960    ///
1961    /// use core::f64;
1962    ///
1963    /// let a: f64 = 7.0;
1964    /// let b = 4.0;
1965    /// assert_eq!(f64::math::div_euclid(a, b), 1.0); // 7.0 > 4.0 * 1.0
1966    /// assert_eq!(f64::math::div_euclid(-a, b), -2.0); // -7.0 >= 4.0 * -2.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    /// ```
1970    ///
1971    /// _This standalone function is for testing only.
1972    /// It will be stabilized as an inherent method._
1973    ///
1974    /// [`f64::div_euclid`]: ../../../std/primitive.f64.html#method.div_euclid
1975    #[inline]
1976    #[unstable(feature = "core_float_math", issue = "137578")]
1977    #[must_use = "method returns a new number and does not mutate the original value"]
1978    pub fn div_euclid(x: f64, rhs: f64) -> f64 {
1979        let q = trunc(x / rhs);
1980        if x % rhs < 0.0 {
1981            return if rhs > 0.0 { q - 1.0 } else { q + 1.0 };
1982        }
1983        q
1984    }
1985
1986    /// Experimental version of `rem_euclid` in `core`. See [`f64::rem_euclid`] for details.
1987    ///
1988    /// # Examples
1989    ///
1990    /// ```
1991    /// #![feature(core_float_math)]
1992    ///
1993    /// use core::f64;
1994    ///
1995    /// let a: f64 = 7.0;
1996    /// let b = 4.0;
1997    /// assert_eq!(f64::math::rem_euclid(a, b), 3.0);
1998    /// assert_eq!(f64::math::rem_euclid(-a, b), 1.0);
1999    /// assert_eq!(f64::math::rem_euclid(a, -b), 3.0);
2000    /// assert_eq!(f64::math::rem_euclid(-a, -b), 1.0);
2001    /// // limitation due to round-off error
2002    /// assert!(f64::math::rem_euclid(-f64::EPSILON, 3.0) != 0.0);
2003    /// ```
2004    ///
2005    /// _This standalone function is for testing only.
2006    /// It will be stabilized as an inherent method._
2007    ///
2008    /// [`f64::rem_euclid`]: ../../../std/primitive.f64.html#method.rem_euclid
2009    #[inline]
2010    #[doc(alias = "modulo", alias = "mod")]
2011    #[unstable(feature = "core_float_math", issue = "137578")]
2012    #[must_use = "method returns a new number and does not mutate the original value"]
2013    pub fn rem_euclid(x: f64, rhs: f64) -> f64 {
2014        let r = x % rhs;
2015        if r < 0.0 { r + rhs.abs() } else { r }
2016    }
2017
2018    /// Experimental version of `powi` in `core`. See [`f64::powi`] for details.
2019    ///
2020    /// # Examples
2021    ///
2022    /// ```
2023    /// #![feature(core_float_math)]
2024    ///
2025    /// use core::f64;
2026    ///
2027    /// let x = 2.0_f64;
2028    /// let abs_difference = (f64::math::powi(x, 2) - (x * x)).abs();
2029    /// assert!(abs_difference <= 1e-6);
2030    ///
2031    /// assert_eq!(f64::math::powi(f64::NAN, 0), 1.0);
2032    /// ```
2033    ///
2034    /// _This standalone function is for testing only.
2035    /// It will be stabilized as an inherent method._
2036    ///
2037    /// [`f64::powi`]: ../../../std/primitive.f64.html#method.powi
2038    #[inline]
2039    #[unstable(feature = "core_float_math", issue = "137578")]
2040    #[must_use = "method returns a new number and does not mutate the original value"]
2041    pub fn powi(x: f64, n: i32) -> f64 {
2042        intrinsics::powi(x, n)
2043    }
2044
2045    /// Experimental version of `sqrt` in `core`. See [`f64::sqrt`] for details.
2046    ///
2047    /// # Examples
2048    ///
2049    /// ```
2050    /// #![feature(core_float_math)]
2051    ///
2052    /// use core::f64;
2053    ///
2054    /// let positive = 4.0_f64;
2055    /// let negative = -4.0_f64;
2056    /// let negative_zero = -0.0_f64;
2057    ///
2058    /// assert_eq!(f64::math::sqrt(positive), 2.0);
2059    /// assert!(f64::math::sqrt(negative).is_nan());
2060    /// assert_eq!(f64::math::sqrt(negative_zero), negative_zero);
2061    /// ```
2062    ///
2063    /// _This standalone function is for testing only.
2064    /// It will be stabilized as an inherent method._
2065    ///
2066    /// [`f64::sqrt`]: ../../../std/primitive.f64.html#method.sqrt
2067    #[inline]
2068    #[doc(alias = "squareRoot")]
2069    #[unstable(feature = "core_float_math", issue = "137578")]
2070    #[must_use = "method returns a new number and does not mutate the original value"]
2071    pub fn sqrt(x: f64) -> f64 {
2072        intrinsics::sqrt(x)
2073    }
2074
2075    /// Experimental version of `abs_sub` in `core`. See [`f64::abs_sub`] for details.
2076    ///
2077    /// # Examples
2078    ///
2079    /// ```
2080    /// #![feature(core_float_math)]
2081    ///
2082    /// use core::f64;
2083    ///
2084    /// let x = 3.0_f64;
2085    /// let y = -3.0_f64;
2086    ///
2087    /// let abs_difference_x = (f64::math::abs_sub(x, 1.0) - 2.0).abs();
2088    /// let abs_difference_y = (f64::math::abs_sub(y, 1.0) - 0.0).abs();
2089    ///
2090    /// assert!(abs_difference_x < 1e-10);
2091    /// assert!(abs_difference_y < 1e-10);
2092    /// ```
2093    ///
2094    /// _This standalone function is for testing only.
2095    /// It will be stabilized as an inherent method._
2096    ///
2097    /// [`f64::abs_sub`]: ../../../std/primitive.f64.html#method.abs_sub
2098    #[inline]
2099    #[unstable(feature = "core_float_math", issue = "137578")]
2100    #[deprecated(
2101        since = "1.10.0",
2102        note = "you probably meant `(self - other).abs()`: \
2103                this operation is `(self - other).max(0.0)` \
2104                except that `abs_sub` also propagates NaNs (also \
2105                known as `fdim` in C). If you truly need the positive \
2106                difference, consider using that expression or the C function \
2107                `fdim`, depending on how you wish to handle NaN (please consider \
2108                filing an issue describing your use-case too)."
2109    )]
2110    #[must_use = "method returns a new number and does not mutate the original value"]
2111    pub fn abs_sub(x: f64, other: f64) -> f64 {
2112        libm::fdim(x, other)
2113    }
2114
2115    /// Experimental version of `cbrt` in `core`. See [`f64::cbrt`] for details.
2116    ///
2117    /// # Examples
2118    ///
2119    /// ```
2120    /// #![feature(core_float_math)]
2121    ///
2122    /// use core::f64;
2123    ///
2124    /// let x = 8.0_f64;
2125    ///
2126    /// // x^(1/3) - 2 == 0
2127    /// let abs_difference = (f64::math::cbrt(x) - 2.0).abs();
2128    ///
2129    /// assert!(abs_difference < 1e-10);
2130    /// ```
2131    ///
2132    /// _This standalone function is for testing only.
2133    /// It will be stabilized as an inherent method._
2134    ///
2135    /// [`f64::cbrt`]: ../../../std/primitive.f64.html#method.cbrt
2136    #[inline]
2137    #[unstable(feature = "core_float_math", issue = "137578")]
2138    #[must_use = "method returns a new number and does not mutate the original value"]
2139    pub fn cbrt(x: f64) -> f64 {
2140        libm::cbrt(x)
2141    }
2142}