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