Skip to main content

core/num/
f64.rs

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