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