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