]> git.lizzy.rs Git - rust.git/blob - library/core/src/num/f64.rs
Rollup merge of #102706 - ferrocene:pa-ignore-doc-index, r=jyn514
[rust.git] / library / core / src / 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
14 use crate::convert::FloatToInt;
15 #[cfg(not(test))]
16 use crate::intrinsics;
17 use crate::mem;
18 use crate::num::FpCategory;
19
20 /// The radix or base of the internal representation of `f64`.
21 /// Use [`f64::RADIX`] instead.
22 ///
23 /// # Examples
24 ///
25 /// ```rust
26 /// // deprecated way
27 /// # #[allow(deprecated, deprecated_in_future)]
28 /// let r = std::f64::RADIX;
29 ///
30 /// // intended way
31 /// let r = f64::RADIX;
32 /// ```
33 #[stable(feature = "rust1", since = "1.0.0")]
34 #[deprecated(since = "TBD", note = "replaced by the `RADIX` associated constant on `f64`")]
35 pub 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 pub const MANTISSA_DIGITS: u32 = f64::MANTISSA_DIGITS;
56
57 /// Approximate number of significant digits in base 10.
58 /// Use [`f64::DIGITS`] instead.
59 ///
60 /// # Examples
61 ///
62 /// ```rust
63 /// // deprecated way
64 /// # #[allow(deprecated, deprecated_in_future)]
65 /// let d = std::f64::DIGITS;
66 ///
67 /// // intended way
68 /// let d = f64::DIGITS;
69 /// ```
70 #[stable(feature = "rust1", since = "1.0.0")]
71 #[deprecated(since = "TBD", note = "replaced by the `DIGITS` associated constant on `f64`")]
72 pub const DIGITS: u32 = f64::DIGITS;
73
74 /// [Machine epsilon] value for `f64`.
75 /// Use [`f64::EPSILON`] instead.
76 ///
77 /// This is the difference between `1.0` and the next larger representable number.
78 ///
79 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
80 ///
81 /// # Examples
82 ///
83 /// ```rust
84 /// // deprecated way
85 /// # #[allow(deprecated, deprecated_in_future)]
86 /// let e = std::f64::EPSILON;
87 ///
88 /// // intended way
89 /// let e = f64::EPSILON;
90 /// ```
91 #[stable(feature = "rust1", since = "1.0.0")]
92 #[deprecated(since = "TBD", note = "replaced by the `EPSILON` associated constant on `f64`")]
93 pub const EPSILON: f64 = f64::EPSILON;
94
95 /// Smallest finite `f64` value.
96 /// Use [`f64::MIN`] instead.
97 ///
98 /// # Examples
99 ///
100 /// ```rust
101 /// // deprecated way
102 /// # #[allow(deprecated, deprecated_in_future)]
103 /// let min = std::f64::MIN;
104 ///
105 /// // intended way
106 /// let min = f64::MIN;
107 /// ```
108 #[stable(feature = "rust1", since = "1.0.0")]
109 #[deprecated(since = "TBD", note = "replaced by the `MIN` associated constant on `f64`")]
110 pub const MIN: f64 = f64::MIN;
111
112 /// Smallest positive normal `f64` value.
113 /// Use [`f64::MIN_POSITIVE`] instead.
114 ///
115 /// # Examples
116 ///
117 /// ```rust
118 /// // deprecated way
119 /// # #[allow(deprecated, deprecated_in_future)]
120 /// let min = std::f64::MIN_POSITIVE;
121 ///
122 /// // intended way
123 /// let min = f64::MIN_POSITIVE;
124 /// ```
125 #[stable(feature = "rust1", since = "1.0.0")]
126 #[deprecated(since = "TBD", note = "replaced by the `MIN_POSITIVE` associated constant on `f64`")]
127 pub const MIN_POSITIVE: f64 = f64::MIN_POSITIVE;
128
129 /// Largest finite `f64` value.
130 /// Use [`f64::MAX`] instead.
131 ///
132 /// # Examples
133 ///
134 /// ```rust
135 /// // deprecated way
136 /// # #[allow(deprecated, deprecated_in_future)]
137 /// let max = std::f64::MAX;
138 ///
139 /// // intended way
140 /// let max = f64::MAX;
141 /// ```
142 #[stable(feature = "rust1", since = "1.0.0")]
143 #[deprecated(since = "TBD", note = "replaced by the `MAX` associated constant on `f64`")]
144 pub const MAX: f64 = f64::MAX;
145
146 /// One greater than the minimum possible normal power of 2 exponent.
147 /// Use [`f64::MIN_EXP`] instead.
148 ///
149 /// # Examples
150 ///
151 /// ```rust
152 /// // deprecated way
153 /// # #[allow(deprecated, deprecated_in_future)]
154 /// let min = std::f64::MIN_EXP;
155 ///
156 /// // intended way
157 /// let min = f64::MIN_EXP;
158 /// ```
159 #[stable(feature = "rust1", since = "1.0.0")]
160 #[deprecated(since = "TBD", note = "replaced by the `MIN_EXP` associated constant on `f64`")]
161 pub const MIN_EXP: i32 = f64::MIN_EXP;
162
163 /// Maximum possible power of 2 exponent.
164 /// Use [`f64::MAX_EXP`] instead.
165 ///
166 /// # Examples
167 ///
168 /// ```rust
169 /// // deprecated way
170 /// # #[allow(deprecated, deprecated_in_future)]
171 /// let max = std::f64::MAX_EXP;
172 ///
173 /// // intended way
174 /// let max = f64::MAX_EXP;
175 /// ```
176 #[stable(feature = "rust1", since = "1.0.0")]
177 #[deprecated(since = "TBD", note = "replaced by the `MAX_EXP` associated constant on `f64`")]
178 pub const MAX_EXP: i32 = f64::MAX_EXP;
179
180 /// Minimum possible normal power of 10 exponent.
181 /// Use [`f64::MIN_10_EXP`] instead.
182 ///
183 /// # Examples
184 ///
185 /// ```rust
186 /// // deprecated way
187 /// # #[allow(deprecated, deprecated_in_future)]
188 /// let min = std::f64::MIN_10_EXP;
189 ///
190 /// // intended way
191 /// let min = f64::MIN_10_EXP;
192 /// ```
193 #[stable(feature = "rust1", since = "1.0.0")]
194 #[deprecated(since = "TBD", note = "replaced by the `MIN_10_EXP` associated constant on `f64`")]
195 pub const MIN_10_EXP: i32 = f64::MIN_10_EXP;
196
197 /// Maximum possible power of 10 exponent.
198 /// Use [`f64::MAX_10_EXP`] instead.
199 ///
200 /// # Examples
201 ///
202 /// ```rust
203 /// // deprecated way
204 /// # #[allow(deprecated, deprecated_in_future)]
205 /// let max = std::f64::MAX_10_EXP;
206 ///
207 /// // intended way
208 /// let max = f64::MAX_10_EXP;
209 /// ```
210 #[stable(feature = "rust1", since = "1.0.0")]
211 #[deprecated(since = "TBD", note = "replaced by the `MAX_10_EXP` associated constant on `f64`")]
212 pub const MAX_10_EXP: i32 = f64::MAX_10_EXP;
213
214 /// Not a Number (NaN).
215 /// Use [`f64::NAN`] instead.
216 ///
217 /// # Examples
218 ///
219 /// ```rust
220 /// // deprecated way
221 /// # #[allow(deprecated, deprecated_in_future)]
222 /// let nan = std::f64::NAN;
223 ///
224 /// // intended way
225 /// let nan = f64::NAN;
226 /// ```
227 #[stable(feature = "rust1", since = "1.0.0")]
228 #[deprecated(since = "TBD", note = "replaced by the `NAN` associated constant on `f64`")]
229 pub const NAN: f64 = f64::NAN;
230
231 /// Infinity (∞).
232 /// Use [`f64::INFINITY`] instead.
233 ///
234 /// # Examples
235 ///
236 /// ```rust
237 /// // deprecated way
238 /// # #[allow(deprecated, deprecated_in_future)]
239 /// let inf = std::f64::INFINITY;
240 ///
241 /// // intended way
242 /// let inf = f64::INFINITY;
243 /// ```
244 #[stable(feature = "rust1", since = "1.0.0")]
245 #[deprecated(since = "TBD", note = "replaced by the `INFINITY` associated constant on `f64`")]
246 pub const INFINITY: f64 = f64::INFINITY;
247
248 /// Negative infinity (−∞).
249 /// Use [`f64::NEG_INFINITY`] instead.
250 ///
251 /// # Examples
252 ///
253 /// ```rust
254 /// // deprecated way
255 /// # #[allow(deprecated, deprecated_in_future)]
256 /// let ninf = std::f64::NEG_INFINITY;
257 ///
258 /// // intended way
259 /// let ninf = f64::NEG_INFINITY;
260 /// ```
261 #[stable(feature = "rust1", since = "1.0.0")]
262 #[deprecated(since = "TBD", note = "replaced by the `NEG_INFINITY` associated constant on `f64`")]
263 pub const NEG_INFINITY: f64 = f64::NEG_INFINITY;
264
265 /// Basic mathematical constants.
266 #[stable(feature = "rust1", since = "1.0.0")]
267 pub mod consts {
268     // FIXME: replace with mathematical constants from cmath.
269
270     /// Archimedes' constant (π)
271     #[stable(feature = "rust1", since = "1.0.0")]
272     pub const PI: f64 = 3.14159265358979323846264338327950288_f64;
273
274     /// The full circle constant (τ)
275     ///
276     /// Equal to 2π.
277     #[stable(feature = "tau_constant", since = "1.47.0")]
278     pub const TAU: f64 = 6.28318530717958647692528676655900577_f64;
279
280     /// π/2
281     #[stable(feature = "rust1", since = "1.0.0")]
282     pub const FRAC_PI_2: f64 = 1.57079632679489661923132169163975144_f64;
283
284     /// π/3
285     #[stable(feature = "rust1", since = "1.0.0")]
286     pub const FRAC_PI_3: f64 = 1.04719755119659774615421446109316763_f64;
287
288     /// π/4
289     #[stable(feature = "rust1", since = "1.0.0")]
290     pub const FRAC_PI_4: f64 = 0.785398163397448309615660845819875721_f64;
291
292     /// π/6
293     #[stable(feature = "rust1", since = "1.0.0")]
294     pub const FRAC_PI_6: f64 = 0.52359877559829887307710723054658381_f64;
295
296     /// π/8
297     #[stable(feature = "rust1", since = "1.0.0")]
298     pub const FRAC_PI_8: f64 = 0.39269908169872415480783042290993786_f64;
299
300     /// 1/π
301     #[stable(feature = "rust1", since = "1.0.0")]
302     pub const FRAC_1_PI: f64 = 0.318309886183790671537767526745028724_f64;
303
304     /// 2/π
305     #[stable(feature = "rust1", since = "1.0.0")]
306     pub const FRAC_2_PI: f64 = 0.636619772367581343075535053490057448_f64;
307
308     /// 2/sqrt(π)
309     #[stable(feature = "rust1", since = "1.0.0")]
310     pub const FRAC_2_SQRT_PI: f64 = 1.12837916709551257389615890312154517_f64;
311
312     /// sqrt(2)
313     #[stable(feature = "rust1", since = "1.0.0")]
314     pub const SQRT_2: f64 = 1.41421356237309504880168872420969808_f64;
315
316     /// 1/sqrt(2)
317     #[stable(feature = "rust1", since = "1.0.0")]
318     pub const FRAC_1_SQRT_2: f64 = 0.707106781186547524400844362104849039_f64;
319
320     /// Euler's number (e)
321     #[stable(feature = "rust1", since = "1.0.0")]
322     pub const E: f64 = 2.71828182845904523536028747135266250_f64;
323
324     /// log<sub>2</sub>(10)
325     #[stable(feature = "extra_log_consts", since = "1.43.0")]
326     pub const LOG2_10: f64 = 3.32192809488736234787031942948939018_f64;
327
328     /// log<sub>2</sub>(e)
329     #[stable(feature = "rust1", since = "1.0.0")]
330     pub const LOG2_E: f64 = 1.44269504088896340735992468100189214_f64;
331
332     /// log<sub>10</sub>(2)
333     #[stable(feature = "extra_log_consts", since = "1.43.0")]
334     pub const LOG10_2: f64 = 0.301029995663981195213738894724493027_f64;
335
336     /// log<sub>10</sub>(e)
337     #[stable(feature = "rust1", since = "1.0.0")]
338     pub const LOG10_E: f64 = 0.434294481903251827651128918916605082_f64;
339
340     /// ln(2)
341     #[stable(feature = "rust1", since = "1.0.0")]
342     pub const LN_2: f64 = 0.693147180559945309417232121458176568_f64;
343
344     /// ln(10)
345     #[stable(feature = "rust1", since = "1.0.0")]
346     pub const LN_10: f64 = 2.30258509299404568401799145468436421_f64;
347 }
348
349 #[cfg(not(test))]
350 impl f64 {
351     /// The radix or base of the internal representation of `f64`.
352     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
353     pub const RADIX: u32 = 2;
354
355     /// Number of significant digits in base 2.
356     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
357     pub const MANTISSA_DIGITS: u32 = 53;
358     /// Approximate number of significant digits in base 10.
359     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
360     pub const DIGITS: u32 = 15;
361
362     /// [Machine epsilon] value for `f64`.
363     ///
364     /// This is the difference between `1.0` and the next larger representable number.
365     ///
366     /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
367     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
368     pub const EPSILON: f64 = 2.2204460492503131e-16_f64;
369
370     /// Smallest finite `f64` value.
371     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
372     pub const MIN: f64 = -1.7976931348623157e+308_f64;
373     /// Smallest positive normal `f64` value.
374     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
375     pub const MIN_POSITIVE: f64 = 2.2250738585072014e-308_f64;
376     /// Largest finite `f64` value.
377     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
378     pub const MAX: f64 = 1.7976931348623157e+308_f64;
379
380     /// One greater than the minimum possible normal power of 2 exponent.
381     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
382     pub const MIN_EXP: i32 = -1021;
383     /// Maximum possible power of 2 exponent.
384     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
385     pub const MAX_EXP: i32 = 1024;
386
387     /// Minimum possible normal power of 10 exponent.
388     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
389     pub const MIN_10_EXP: i32 = -307;
390     /// Maximum possible power of 10 exponent.
391     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
392     pub const MAX_10_EXP: i32 = 308;
393
394     /// Not a Number (NaN).
395     ///
396     /// Note that IEEE 754 doesn't define just a single NaN value;
397     /// a plethora of bit patterns are considered to be NaN.
398     /// Furthermore, the standard makes a difference
399     /// between a "signaling" and a "quiet" NaN,
400     /// and allows inspecting its "payload" (the unspecified bits in the bit pattern).
401     /// This constant isn't guaranteed to equal to any specific NaN bitpattern,
402     /// and the stability of its representation over Rust versions
403     /// and target platforms isn't guaranteed.
404     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
405     pub const NAN: f64 = 0.0_f64 / 0.0_f64;
406     /// Infinity (∞).
407     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
408     pub const INFINITY: f64 = 1.0_f64 / 0.0_f64;
409     /// Negative infinity (−∞).
410     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
411     pub const NEG_INFINITY: f64 = -1.0_f64 / 0.0_f64;
412
413     /// Returns `true` if this value is NaN.
414     ///
415     /// ```
416     /// let nan = f64::NAN;
417     /// let f = 7.0_f64;
418     ///
419     /// assert!(nan.is_nan());
420     /// assert!(!f.is_nan());
421     /// ```
422     #[must_use]
423     #[stable(feature = "rust1", since = "1.0.0")]
424     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
425     #[inline]
426     pub const fn is_nan(self) -> bool {
427         self != self
428     }
429
430     // FIXME(#50145): `abs` is publicly unavailable in libcore due to
431     // concerns about portability, so this implementation is for
432     // private use internally.
433     #[inline]
434     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
435     pub(crate) const fn abs_private(self) -> f64 {
436         // SAFETY: This transmutation is fine. Probably. For the reasons std is using it.
437         unsafe {
438             mem::transmute::<u64, f64>(mem::transmute::<f64, u64>(self) & 0x7fff_ffff_ffff_ffff)
439         }
440     }
441
442     /// Returns `true` if this value is positive infinity or negative infinity, and
443     /// `false` otherwise.
444     ///
445     /// ```
446     /// let f = 7.0f64;
447     /// let inf = f64::INFINITY;
448     /// let neg_inf = f64::NEG_INFINITY;
449     /// let nan = f64::NAN;
450     ///
451     /// assert!(!f.is_infinite());
452     /// assert!(!nan.is_infinite());
453     ///
454     /// assert!(inf.is_infinite());
455     /// assert!(neg_inf.is_infinite());
456     /// ```
457     #[must_use]
458     #[stable(feature = "rust1", since = "1.0.0")]
459     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
460     #[inline]
461     pub const fn is_infinite(self) -> bool {
462         // Getting clever with transmutation can result in incorrect answers on some FPUs
463         // FIXME: alter the Rust <-> Rust calling convention to prevent this problem.
464         // See https://github.com/rust-lang/rust/issues/72327
465         (self == f64::INFINITY) | (self == f64::NEG_INFINITY)
466     }
467
468     /// Returns `true` if this number is neither infinite nor NaN.
469     ///
470     /// ```
471     /// let f = 7.0f64;
472     /// let inf: f64 = f64::INFINITY;
473     /// let neg_inf: f64 = f64::NEG_INFINITY;
474     /// let nan: f64 = f64::NAN;
475     ///
476     /// assert!(f.is_finite());
477     ///
478     /// assert!(!nan.is_finite());
479     /// assert!(!inf.is_finite());
480     /// assert!(!neg_inf.is_finite());
481     /// ```
482     #[must_use]
483     #[stable(feature = "rust1", since = "1.0.0")]
484     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
485     #[inline]
486     pub const fn is_finite(self) -> bool {
487         // There's no need to handle NaN separately: if self is NaN,
488         // the comparison is not true, exactly as desired.
489         self.abs_private() < Self::INFINITY
490     }
491
492     /// Returns `true` if the number is [subnormal].
493     ///
494     /// ```
495     /// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308_f64
496     /// let max = f64::MAX;
497     /// let lower_than_min = 1.0e-308_f64;
498     /// let zero = 0.0_f64;
499     ///
500     /// assert!(!min.is_subnormal());
501     /// assert!(!max.is_subnormal());
502     ///
503     /// assert!(!zero.is_subnormal());
504     /// assert!(!f64::NAN.is_subnormal());
505     /// assert!(!f64::INFINITY.is_subnormal());
506     /// // Values between `0` and `min` are Subnormal.
507     /// assert!(lower_than_min.is_subnormal());
508     /// ```
509     /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
510     #[must_use]
511     #[stable(feature = "is_subnormal", since = "1.53.0")]
512     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
513     #[inline]
514     pub const fn is_subnormal(self) -> bool {
515         matches!(self.classify(), FpCategory::Subnormal)
516     }
517
518     /// Returns `true` if the number is neither zero, infinite,
519     /// [subnormal], or NaN.
520     ///
521     /// ```
522     /// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308f64
523     /// let max = f64::MAX;
524     /// let lower_than_min = 1.0e-308_f64;
525     /// let zero = 0.0f64;
526     ///
527     /// assert!(min.is_normal());
528     /// assert!(max.is_normal());
529     ///
530     /// assert!(!zero.is_normal());
531     /// assert!(!f64::NAN.is_normal());
532     /// assert!(!f64::INFINITY.is_normal());
533     /// // Values between `0` and `min` are Subnormal.
534     /// assert!(!lower_than_min.is_normal());
535     /// ```
536     /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
537     #[must_use]
538     #[stable(feature = "rust1", since = "1.0.0")]
539     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
540     #[inline]
541     pub const fn is_normal(self) -> bool {
542         matches!(self.classify(), FpCategory::Normal)
543     }
544
545     /// Returns the floating point category of the number. If only one property
546     /// is going to be tested, it is generally faster to use the specific
547     /// predicate instead.
548     ///
549     /// ```
550     /// use std::num::FpCategory;
551     ///
552     /// let num = 12.4_f64;
553     /// let inf = f64::INFINITY;
554     ///
555     /// assert_eq!(num.classify(), FpCategory::Normal);
556     /// assert_eq!(inf.classify(), FpCategory::Infinite);
557     /// ```
558     #[stable(feature = "rust1", since = "1.0.0")]
559     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
560     pub const fn classify(self) -> FpCategory {
561         // A previous implementation tried to only use bitmask-based checks,
562         // using f64::to_bits to transmute the float to its bit repr and match on that.
563         // Unfortunately, floating point numbers can be much worse than that.
564         // This also needs to not result in recursive evaluations of f64::to_bits.
565         //
566         // On some processors, in some cases, LLVM will "helpfully" lower floating point ops,
567         // in spite of a request for them using f32 and f64, to things like x87 operations.
568         // These have an f64's mantissa, but can have a larger than normal exponent.
569         // FIXME(jubilee): Using x87 operations is never necessary in order to function
570         // on x86 processors for Rust-to-Rust calls, so this issue should not happen.
571         // Code generation should be adjusted to use non-C calling conventions, avoiding this.
572         //
573         // Thus, a value may compare unequal to infinity, despite having a "full" exponent mask.
574         // And it may not be NaN, as it can simply be an "overextended" finite value.
575         if self.is_nan() {
576             FpCategory::Nan
577         } else {
578             // However, std can't simply compare to zero to check for zero, either,
579             // as correctness requires avoiding equality tests that may be Subnormal == -0.0
580             // because it may be wrong under "denormals are zero" and "flush to zero" modes.
581             // Most of std's targets don't use those, but they are used for thumbv7neon.
582             // So, this does use bitpattern matching for the rest.
583
584             // SAFETY: f64 to u64 is fine. Usually.
585             // If control flow has gotten this far, the value is definitely in one of the categories
586             // that f64::partial_classify can correctly analyze.
587             unsafe { f64::partial_classify(self) }
588         }
589     }
590
591     // This doesn't actually return a right answer for NaN on purpose,
592     // seeing as how it cannot correctly discern between a floating point NaN,
593     // and some normal floating point numbers truncated from an x87 FPU.
594     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
595     const unsafe fn partial_classify(self) -> FpCategory {
596         const EXP_MASK: u64 = 0x7ff0000000000000;
597         const MAN_MASK: u64 = 0x000fffffffffffff;
598
599         // SAFETY: The caller is not asking questions for which this will tell lies.
600         let b = unsafe { mem::transmute::<f64, u64>(self) };
601         match (b & MAN_MASK, b & EXP_MASK) {
602             (0, EXP_MASK) => FpCategory::Infinite,
603             (0, 0) => FpCategory::Zero,
604             (_, 0) => FpCategory::Subnormal,
605             _ => FpCategory::Normal,
606         }
607     }
608
609     // This operates on bits, and only bits, so it can ignore concerns about weird FPUs.
610     // FIXME(jubilee): In a just world, this would be the entire impl for classify,
611     // plus a transmute. We do not live in a just world, but we can make it more so.
612     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
613     const fn classify_bits(b: u64) -> FpCategory {
614         const EXP_MASK: u64 = 0x7ff0000000000000;
615         const MAN_MASK: u64 = 0x000fffffffffffff;
616
617         match (b & MAN_MASK, b & EXP_MASK) {
618             (0, EXP_MASK) => FpCategory::Infinite,
619             (_, EXP_MASK) => FpCategory::Nan,
620             (0, 0) => FpCategory::Zero,
621             (_, 0) => FpCategory::Subnormal,
622             _ => FpCategory::Normal,
623         }
624     }
625
626     /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with
627     /// positive sign bit and positive infinity. Note that IEEE 754 doesn't assign any
628     /// meaning to the sign bit in case of a NaN, and as Rust doesn't guarantee that
629     /// the bit pattern of NaNs are conserved over arithmetic operations, the result of
630     /// `is_sign_positive` on a NaN might produce an unexpected result in some cases.
631     /// See [explanation of NaN as a special value](f32) for more info.
632     ///
633     /// ```
634     /// let f = 7.0_f64;
635     /// let g = -7.0_f64;
636     ///
637     /// assert!(f.is_sign_positive());
638     /// assert!(!g.is_sign_positive());
639     /// ```
640     #[must_use]
641     #[stable(feature = "rust1", since = "1.0.0")]
642     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
643     #[inline]
644     pub const fn is_sign_positive(self) -> bool {
645         !self.is_sign_negative()
646     }
647
648     #[must_use]
649     #[stable(feature = "rust1", since = "1.0.0")]
650     #[deprecated(since = "1.0.0", note = "renamed to is_sign_positive")]
651     #[inline]
652     #[doc(hidden)]
653     pub fn is_positive(self) -> bool {
654         self.is_sign_positive()
655     }
656
657     /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with
658     /// negative sign bit and negative infinity. Note that IEEE 754 doesn't assign any
659     /// meaning to the sign bit in case of a NaN, and as Rust doesn't guarantee that
660     /// the bit pattern of NaNs are conserved over arithmetic operations, the result of
661     /// `is_sign_negative` on a NaN might produce an unexpected result in some cases.
662     /// See [explanation of NaN as a special value](f32) for more info.
663     ///
664     /// ```
665     /// let f = 7.0_f64;
666     /// let g = -7.0_f64;
667     ///
668     /// assert!(!f.is_sign_negative());
669     /// assert!(g.is_sign_negative());
670     /// ```
671     #[must_use]
672     #[stable(feature = "rust1", since = "1.0.0")]
673     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
674     #[inline]
675     pub const fn is_sign_negative(self) -> bool {
676         // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
677         // applies to zeros and NaNs as well.
678         // SAFETY: This is just transmuting to get the sign bit, it's fine.
679         unsafe { mem::transmute::<f64, u64>(self) & 0x8000_0000_0000_0000 != 0 }
680     }
681
682     #[must_use]
683     #[stable(feature = "rust1", since = "1.0.0")]
684     #[deprecated(since = "1.0.0", note = "renamed to is_sign_negative")]
685     #[inline]
686     #[doc(hidden)]
687     pub fn is_negative(self) -> bool {
688         self.is_sign_negative()
689     }
690
691     /// Returns the least number greater than `self`.
692     ///
693     /// Let `TINY` be the smallest representable positive `f64`. Then,
694     ///  - if `self.is_nan()`, this returns `self`;
695     ///  - if `self` is [`NEG_INFINITY`], this returns [`MIN`];
696     ///  - if `self` is `-TINY`, this returns -0.0;
697     ///  - if `self` is -0.0 or +0.0, this returns `TINY`;
698     ///  - if `self` is [`MAX`] or [`INFINITY`], this returns [`INFINITY`];
699     ///  - otherwise the unique least value greater than `self` is returned.
700     ///
701     /// The identity `x.next_up() == -(-x).next_down()` holds for all non-NaN `x`. When `x`
702     /// is finite `x == x.next_up().next_down()` also holds.
703     ///
704     /// ```rust
705     /// #![feature(float_next_up_down)]
706     /// // f64::EPSILON is the difference between 1.0 and the next number up.
707     /// assert_eq!(1.0f64.next_up(), 1.0 + f64::EPSILON);
708     /// // But not for most numbers.
709     /// assert!(0.1f64.next_up() < 0.1 + f64::EPSILON);
710     /// assert_eq!(9007199254740992f64.next_up(), 9007199254740994.0);
711     /// ```
712     ///
713     /// [`NEG_INFINITY`]: Self::NEG_INFINITY
714     /// [`INFINITY`]: Self::INFINITY
715     /// [`MIN`]: Self::MIN
716     /// [`MAX`]: Self::MAX
717     #[unstable(feature = "float_next_up_down", issue = "91399")]
718     #[rustc_const_unstable(feature = "float_next_up_down", issue = "91399")]
719     pub const fn next_up(self) -> Self {
720         // We must use strictly integer arithmetic to prevent denormals from
721         // flushing to zero after an arithmetic operation on some platforms.
722         const TINY_BITS: u64 = 0x1; // Smallest positive f64.
723         const CLEAR_SIGN_MASK: u64 = 0x7fff_ffff_ffff_ffff;
724
725         let bits = self.to_bits();
726         if self.is_nan() || bits == Self::INFINITY.to_bits() {
727             return self;
728         }
729
730         let abs = bits & CLEAR_SIGN_MASK;
731         let next_bits = if abs == 0 {
732             TINY_BITS
733         } else if bits == abs {
734             bits + 1
735         } else {
736             bits - 1
737         };
738         Self::from_bits(next_bits)
739     }
740
741     /// Returns the greatest number less than `self`.
742     ///
743     /// Let `TINY` be the smallest representable positive `f64`. Then,
744     ///  - if `self.is_nan()`, this returns `self`;
745     ///  - if `self` is [`INFINITY`], this returns [`MAX`];
746     ///  - if `self` is `TINY`, this returns 0.0;
747     ///  - if `self` is -0.0 or +0.0, this returns `-TINY`;
748     ///  - if `self` is [`MIN`] or [`NEG_INFINITY`], this returns [`NEG_INFINITY`];
749     ///  - otherwise the unique greatest value less than `self` is returned.
750     ///
751     /// The identity `x.next_down() == -(-x).next_up()` holds for all non-NaN `x`. When `x`
752     /// is finite `x == x.next_down().next_up()` also holds.
753     ///
754     /// ```rust
755     /// #![feature(float_next_up_down)]
756     /// let x = 1.0f64;
757     /// // Clamp value into range [0, 1).
758     /// let clamped = x.clamp(0.0, 1.0f64.next_down());
759     /// assert!(clamped < 1.0);
760     /// assert_eq!(clamped.next_up(), 1.0);
761     /// ```
762     ///
763     /// [`NEG_INFINITY`]: Self::NEG_INFINITY
764     /// [`INFINITY`]: Self::INFINITY
765     /// [`MIN`]: Self::MIN
766     /// [`MAX`]: Self::MAX
767     #[unstable(feature = "float_next_up_down", issue = "91399")]
768     #[rustc_const_unstable(feature = "float_next_up_down", issue = "91399")]
769     pub const fn next_down(self) -> Self {
770         // We must use strictly integer arithmetic to prevent denormals from
771         // flushing to zero after an arithmetic operation on some platforms.
772         const NEG_TINY_BITS: u64 = 0x8000_0000_0000_0001; // Smallest (in magnitude) negative f64.
773         const CLEAR_SIGN_MASK: u64 = 0x7fff_ffff_ffff_ffff;
774
775         let bits = self.to_bits();
776         if self.is_nan() || bits == Self::NEG_INFINITY.to_bits() {
777             return self;
778         }
779
780         let abs = bits & CLEAR_SIGN_MASK;
781         let next_bits = if abs == 0 {
782             NEG_TINY_BITS
783         } else if bits == abs {
784             bits - 1
785         } else {
786             bits + 1
787         };
788         Self::from_bits(next_bits)
789     }
790
791     /// Takes the reciprocal (inverse) of a number, `1/x`.
792     ///
793     /// ```
794     /// let x = 2.0_f64;
795     /// let abs_difference = (x.recip() - (1.0 / x)).abs();
796     ///
797     /// assert!(abs_difference < 1e-10);
798     /// ```
799     #[must_use = "this returns the result of the operation, without modifying the original"]
800     #[stable(feature = "rust1", since = "1.0.0")]
801     #[inline]
802     pub fn recip(self) -> f64 {
803         1.0 / self
804     }
805
806     /// Converts radians to degrees.
807     ///
808     /// ```
809     /// let angle = std::f64::consts::PI;
810     ///
811     /// let abs_difference = (angle.to_degrees() - 180.0).abs();
812     ///
813     /// assert!(abs_difference < 1e-10);
814     /// ```
815     #[must_use = "this returns the result of the operation, \
816                   without modifying the original"]
817     #[stable(feature = "rust1", since = "1.0.0")]
818     #[inline]
819     pub fn to_degrees(self) -> f64 {
820         // The division here is correctly rounded with respect to the true
821         // value of 180/π. (This differs from f32, where a constant must be
822         // used to ensure a correctly rounded result.)
823         self * (180.0f64 / consts::PI)
824     }
825
826     /// Converts degrees to radians.
827     ///
828     /// ```
829     /// let angle = 180.0_f64;
830     ///
831     /// let abs_difference = (angle.to_radians() - std::f64::consts::PI).abs();
832     ///
833     /// assert!(abs_difference < 1e-10);
834     /// ```
835     #[must_use = "this returns the result of the operation, \
836                   without modifying the original"]
837     #[stable(feature = "rust1", since = "1.0.0")]
838     #[inline]
839     pub fn to_radians(self) -> f64 {
840         let value: f64 = consts::PI;
841         self * (value / 180.0)
842     }
843
844     /// Returns the maximum of the two numbers, ignoring NaN.
845     ///
846     /// If one of the arguments is NaN, then the other argument is returned.
847     /// This follows the IEEE 754-2008 semantics for maxNum, except for handling of signaling NaNs;
848     /// this function handles all NaNs the same way and avoids maxNum's problems with associativity.
849     /// This also matches the behavior of libm’s fmax.
850     ///
851     /// ```
852     /// let x = 1.0_f64;
853     /// let y = 2.0_f64;
854     ///
855     /// assert_eq!(x.max(y), y);
856     /// ```
857     #[must_use = "this returns the result of the comparison, without modifying either input"]
858     #[stable(feature = "rust1", since = "1.0.0")]
859     #[inline]
860     pub fn max(self, other: f64) -> f64 {
861         intrinsics::maxnumf64(self, other)
862     }
863
864     /// Returns the minimum of the two numbers, ignoring NaN.
865     ///
866     /// If one of the arguments is NaN, then the other argument is returned.
867     /// This follows the IEEE 754-2008 semantics for minNum, except for handling of signaling NaNs;
868     /// this function handles all NaNs the same way and avoids minNum's problems with associativity.
869     /// This also matches the behavior of libm’s fmin.
870     ///
871     /// ```
872     /// let x = 1.0_f64;
873     /// let y = 2.0_f64;
874     ///
875     /// assert_eq!(x.min(y), x);
876     /// ```
877     #[must_use = "this returns the result of the comparison, without modifying either input"]
878     #[stable(feature = "rust1", since = "1.0.0")]
879     #[inline]
880     pub fn min(self, other: f64) -> f64 {
881         intrinsics::minnumf64(self, other)
882     }
883
884     /// Returns the maximum of the two numbers, propagating NaN.
885     ///
886     /// This returns NaN when *either* argument is NaN, as opposed to
887     /// [`f64::max`] which only returns NaN when *both* arguments are NaN.
888     ///
889     /// ```
890     /// #![feature(float_minimum_maximum)]
891     /// let x = 1.0_f64;
892     /// let y = 2.0_f64;
893     ///
894     /// assert_eq!(x.maximum(y), y);
895     /// assert!(x.maximum(f64::NAN).is_nan());
896     /// ```
897     ///
898     /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the greater
899     /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
900     /// Note that this follows the semantics specified in IEEE 754-2019.
901     ///
902     /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
903     /// operand is conserved; see [explanation of NaN as a special value](f32) for more info.
904     #[must_use = "this returns the result of the comparison, without modifying either input"]
905     #[unstable(feature = "float_minimum_maximum", issue = "91079")]
906     #[inline]
907     pub fn maximum(self, other: f64) -> f64 {
908         if self > other {
909             self
910         } else if other > self {
911             other
912         } else if self == other {
913             if self.is_sign_positive() && other.is_sign_negative() { self } else { other }
914         } else {
915             self + other
916         }
917     }
918
919     /// Returns the minimum of the two numbers, propagating NaN.
920     ///
921     /// This returns NaN when *either* argument is NaN, as opposed to
922     /// [`f64::min`] which only returns NaN when *both* arguments are NaN.
923     ///
924     /// ```
925     /// #![feature(float_minimum_maximum)]
926     /// let x = 1.0_f64;
927     /// let y = 2.0_f64;
928     ///
929     /// assert_eq!(x.minimum(y), x);
930     /// assert!(x.minimum(f64::NAN).is_nan());
931     /// ```
932     ///
933     /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the lesser
934     /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
935     /// Note that this follows the semantics specified in IEEE 754-2019.
936     ///
937     /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
938     /// operand is conserved; see [explanation of NaN as a special value](f32) for more info.
939     #[must_use = "this returns the result of the comparison, without modifying either input"]
940     #[unstable(feature = "float_minimum_maximum", issue = "91079")]
941     #[inline]
942     pub fn minimum(self, other: f64) -> f64 {
943         if self < other {
944             self
945         } else if other < self {
946             other
947         } else if self == other {
948             if self.is_sign_negative() && other.is_sign_positive() { self } else { other }
949         } else {
950             self + other
951         }
952     }
953
954     /// Rounds toward zero and converts to any primitive integer type,
955     /// assuming that the value is finite and fits in that type.
956     ///
957     /// ```
958     /// let value = 4.6_f64;
959     /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
960     /// assert_eq!(rounded, 4);
961     ///
962     /// let value = -128.9_f64;
963     /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
964     /// assert_eq!(rounded, i8::MIN);
965     /// ```
966     ///
967     /// # Safety
968     ///
969     /// The value must:
970     ///
971     /// * Not be `NaN`
972     /// * Not be infinite
973     /// * Be representable in the return type `Int`, after truncating off its fractional part
974     #[must_use = "this returns the result of the operation, \
975                   without modifying the original"]
976     #[stable(feature = "float_approx_unchecked_to", since = "1.44.0")]
977     #[inline]
978     pub unsafe fn to_int_unchecked<Int>(self) -> Int
979     where
980         Self: FloatToInt<Int>,
981     {
982         // SAFETY: the caller must uphold the safety contract for
983         // `FloatToInt::to_int_unchecked`.
984         unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
985     }
986
987     /// Raw transmutation to `u64`.
988     ///
989     /// This is currently identical to `transmute::<f64, u64>(self)` on all platforms.
990     ///
991     /// See [`from_bits`](Self::from_bits) for some discussion of the
992     /// portability of this operation (there are almost no issues).
993     ///
994     /// Note that this function is distinct from `as` casting, which attempts to
995     /// preserve the *numeric* value, and not the bitwise value.
996     ///
997     /// # Examples
998     ///
999     /// ```
1000     /// assert!((1f64).to_bits() != 1f64 as u64); // to_bits() is not casting!
1001     /// assert_eq!((12.5f64).to_bits(), 0x4029000000000000);
1002     ///
1003     /// ```
1004     #[must_use = "this returns the result of the operation, \
1005                   without modifying the original"]
1006     #[stable(feature = "float_bits_conv", since = "1.20.0")]
1007     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1008     #[inline]
1009     pub const fn to_bits(self) -> u64 {
1010         // SAFETY: `u64` is a plain old datatype so we can always transmute to it.
1011         // ...sorta.
1012         //
1013         // See the SAFETY comment in f64::from_bits for more.
1014         #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1015         const fn ct_f64_to_u64(ct: f64) -> u64 {
1016             match ct.classify() {
1017                 FpCategory::Nan => {
1018                     panic!("const-eval error: cannot use f64::to_bits on a NaN")
1019                 }
1020                 FpCategory::Subnormal => {
1021                     panic!("const-eval error: cannot use f64::to_bits on a subnormal number")
1022                 }
1023                 FpCategory::Infinite | FpCategory::Normal | FpCategory::Zero => {
1024                     // SAFETY: We have a normal floating point number. Now we transmute, i.e. do a bitcopy.
1025                     unsafe { mem::transmute::<f64, u64>(ct) }
1026                 }
1027             }
1028         }
1029
1030         #[inline(always)] // See https://github.com/rust-lang/compiler-builtins/issues/491
1031         fn rt_f64_to_u64(rt: f64) -> u64 {
1032             // SAFETY: `u64` is a plain old datatype so we can always... uh...
1033             // ...look, just pretend you forgot what you just read.
1034             // Stability concerns.
1035             unsafe { mem::transmute::<f64, u64>(rt) }
1036         }
1037         // SAFETY: We use internal implementations that either always work or fail at compile time.
1038         unsafe { intrinsics::const_eval_select((self,), ct_f64_to_u64, rt_f64_to_u64) }
1039     }
1040
1041     /// Raw transmutation from `u64`.
1042     ///
1043     /// This is currently identical to `transmute::<u64, f64>(v)` on all platforms.
1044     /// It turns out this is incredibly portable, for two reasons:
1045     ///
1046     /// * Floats and Ints have the same endianness on all supported platforms.
1047     /// * IEEE 754 very precisely specifies the bit layout of floats.
1048     ///
1049     /// However there is one caveat: prior to the 2008 version of IEEE 754, how
1050     /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
1051     /// (notably x86 and ARM) picked the interpretation that was ultimately
1052     /// standardized in 2008, but some didn't (notably MIPS). As a result, all
1053     /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
1054     ///
1055     /// Rather than trying to preserve signaling-ness cross-platform, this
1056     /// implementation favors preserving the exact bits. This means that
1057     /// any payloads encoded in NaNs will be preserved even if the result of
1058     /// this method is sent over the network from an x86 machine to a MIPS one.
1059     ///
1060     /// If the results of this method are only manipulated by the same
1061     /// architecture that produced them, then there is no portability concern.
1062     ///
1063     /// If the input isn't NaN, then there is no portability concern.
1064     ///
1065     /// If you don't care about signaling-ness (very likely), then there is no
1066     /// portability concern.
1067     ///
1068     /// Note that this function is distinct from `as` casting, which attempts to
1069     /// preserve the *numeric* value, and not the bitwise value.
1070     ///
1071     /// # Examples
1072     ///
1073     /// ```
1074     /// let v = f64::from_bits(0x4029000000000000);
1075     /// assert_eq!(v, 12.5);
1076     /// ```
1077     #[stable(feature = "float_bits_conv", since = "1.20.0")]
1078     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1079     #[must_use]
1080     #[inline]
1081     pub const fn from_bits(v: u64) -> Self {
1082         // It turns out the safety issues with sNaN were overblown! Hooray!
1083         // SAFETY: `u64` is a plain old datatype so we can always transmute from it
1084         // ...sorta.
1085         //
1086         // It turns out that at runtime, it is possible for a floating point number
1087         // to be subject to floating point modes that alter nonzero subnormal numbers
1088         // to zero on reads and writes, aka "denormals are zero" and "flush to zero".
1089         // This is not a problem usually, but at least one tier2 platform for Rust
1090         // actually exhibits an FTZ behavior by default: thumbv7neon
1091         // aka "the Neon FPU in AArch32 state"
1092         //
1093         // Even with this, not all instructions exhibit the FTZ behaviors on thumbv7neon,
1094         // so this should load the same bits if LLVM emits the "correct" instructions,
1095         // but LLVM sometimes makes interesting choices about float optimization,
1096         // and other FPUs may do similar. Thus, it is wise to indulge luxuriously in caution.
1097         //
1098         // In addition, on x86 targets with SSE or SSE2 disabled and the x87 FPU enabled,
1099         // i.e. not soft-float, the way Rust does parameter passing can actually alter
1100         // a number that is "not infinity" to have the same exponent as infinity,
1101         // in a slightly unpredictable manner.
1102         //
1103         // And, of course evaluating to a NaN value is fairly nondeterministic.
1104         // More precisely: when NaN should be returned is knowable, but which NaN?
1105         // So far that's defined by a combination of LLVM and the CPU, not Rust.
1106         // This function, however, allows observing the bitstring of a NaN,
1107         // thus introspection on CTFE.
1108         //
1109         // In order to preserve, at least for the moment, const-to-runtime equivalence,
1110         // reject any of these possible situations from happening.
1111         #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1112         const fn ct_u64_to_f64(ct: u64) -> f64 {
1113             match f64::classify_bits(ct) {
1114                 FpCategory::Subnormal => {
1115                     panic!("const-eval error: cannot use f64::from_bits on a subnormal number")
1116                 }
1117                 FpCategory::Nan => {
1118                     panic!("const-eval error: cannot use f64::from_bits on NaN")
1119                 }
1120                 FpCategory::Infinite | FpCategory::Normal | FpCategory::Zero => {
1121                     // SAFETY: It's not a frumious number
1122                     unsafe { mem::transmute::<u64, f64>(ct) }
1123                 }
1124             }
1125         }
1126
1127         #[inline(always)] // See https://github.com/rust-lang/compiler-builtins/issues/491
1128         fn rt_u64_to_f64(rt: u64) -> f64 {
1129             // SAFETY: `u64` is a plain old datatype so we can always... uh...
1130             // ...look, just pretend you forgot what you just read.
1131             // Stability concerns.
1132             unsafe { mem::transmute::<u64, f64>(rt) }
1133         }
1134         // SAFETY: We use internal implementations that either always work or fail at compile time.
1135         unsafe { intrinsics::const_eval_select((v,), ct_u64_to_f64, rt_u64_to_f64) }
1136     }
1137
1138     /// Return the memory representation of this floating point number as a byte array in
1139     /// big-endian (network) byte order.
1140     ///
1141     /// See [`from_bits`](Self::from_bits) for some discussion of the
1142     /// portability of this operation (there are almost no issues).
1143     ///
1144     /// # Examples
1145     ///
1146     /// ```
1147     /// let bytes = 12.5f64.to_be_bytes();
1148     /// assert_eq!(bytes, [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1149     /// ```
1150     #[must_use = "this returns the result of the operation, \
1151                   without modifying the original"]
1152     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1153     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1154     #[inline]
1155     pub const fn to_be_bytes(self) -> [u8; 8] {
1156         self.to_bits().to_be_bytes()
1157     }
1158
1159     /// Return the memory representation of this floating point number as a byte array in
1160     /// little-endian byte order.
1161     ///
1162     /// See [`from_bits`](Self::from_bits) for some discussion of the
1163     /// portability of this operation (there are almost no issues).
1164     ///
1165     /// # Examples
1166     ///
1167     /// ```
1168     /// let bytes = 12.5f64.to_le_bytes();
1169     /// assert_eq!(bytes, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]);
1170     /// ```
1171     #[must_use = "this returns the result of the operation, \
1172                   without modifying the original"]
1173     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1174     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1175     #[inline]
1176     pub const fn to_le_bytes(self) -> [u8; 8] {
1177         self.to_bits().to_le_bytes()
1178     }
1179
1180     /// Return the memory representation of this floating point number as a byte array in
1181     /// native byte order.
1182     ///
1183     /// As the target platform's native endianness is used, portable code
1184     /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1185     ///
1186     /// [`to_be_bytes`]: f64::to_be_bytes
1187     /// [`to_le_bytes`]: f64::to_le_bytes
1188     ///
1189     /// See [`from_bits`](Self::from_bits) for some discussion of the
1190     /// portability of this operation (there are almost no issues).
1191     ///
1192     /// # Examples
1193     ///
1194     /// ```
1195     /// let bytes = 12.5f64.to_ne_bytes();
1196     /// assert_eq!(
1197     ///     bytes,
1198     ///     if cfg!(target_endian = "big") {
1199     ///         [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1200     ///     } else {
1201     ///         [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]
1202     ///     }
1203     /// );
1204     /// ```
1205     #[must_use = "this returns the result of the operation, \
1206                   without modifying the original"]
1207     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1208     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1209     #[inline]
1210     pub const fn to_ne_bytes(self) -> [u8; 8] {
1211         self.to_bits().to_ne_bytes()
1212     }
1213
1214     /// Create a floating point value from its representation as a byte array in big endian.
1215     ///
1216     /// See [`from_bits`](Self::from_bits) for some discussion of the
1217     /// portability of this operation (there are almost no issues).
1218     ///
1219     /// # Examples
1220     ///
1221     /// ```
1222     /// let value = f64::from_be_bytes([0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1223     /// assert_eq!(value, 12.5);
1224     /// ```
1225     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1226     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1227     #[must_use]
1228     #[inline]
1229     pub const fn from_be_bytes(bytes: [u8; 8]) -> Self {
1230         Self::from_bits(u64::from_be_bytes(bytes))
1231     }
1232
1233     /// Create a floating point value from its representation as a byte array in little endian.
1234     ///
1235     /// See [`from_bits`](Self::from_bits) for some discussion of the
1236     /// portability of this operation (there are almost no issues).
1237     ///
1238     /// # Examples
1239     ///
1240     /// ```
1241     /// let value = f64::from_le_bytes([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]);
1242     /// assert_eq!(value, 12.5);
1243     /// ```
1244     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1245     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1246     #[must_use]
1247     #[inline]
1248     pub const fn from_le_bytes(bytes: [u8; 8]) -> Self {
1249         Self::from_bits(u64::from_le_bytes(bytes))
1250     }
1251
1252     /// Create a floating point value from its representation as a byte array in native endian.
1253     ///
1254     /// As the target platform's native endianness is used, portable code
1255     /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1256     /// appropriate instead.
1257     ///
1258     /// [`from_be_bytes`]: f64::from_be_bytes
1259     /// [`from_le_bytes`]: f64::from_le_bytes
1260     ///
1261     /// See [`from_bits`](Self::from_bits) for some discussion of the
1262     /// portability of this operation (there are almost no issues).
1263     ///
1264     /// # Examples
1265     ///
1266     /// ```
1267     /// let value = f64::from_ne_bytes(if cfg!(target_endian = "big") {
1268     ///     [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1269     /// } else {
1270     ///     [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]
1271     /// });
1272     /// assert_eq!(value, 12.5);
1273     /// ```
1274     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1275     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1276     #[must_use]
1277     #[inline]
1278     pub const fn from_ne_bytes(bytes: [u8; 8]) -> Self {
1279         Self::from_bits(u64::from_ne_bytes(bytes))
1280     }
1281
1282     /// Return the ordering between `self` and `other`.
1283     ///
1284     /// Unlike the standard partial comparison between floating point numbers,
1285     /// this comparison always produces an ordering in accordance to
1286     /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1287     /// floating point standard. The values are ordered in the following sequence:
1288     ///
1289     /// - negative quiet NaN
1290     /// - negative signaling NaN
1291     /// - negative infinity
1292     /// - negative numbers
1293     /// - negative subnormal numbers
1294     /// - negative zero
1295     /// - positive zero
1296     /// - positive subnormal numbers
1297     /// - positive numbers
1298     /// - positive infinity
1299     /// - positive signaling NaN
1300     /// - positive quiet NaN.
1301     ///
1302     /// The ordering established by this function does not always agree with the
1303     /// [`PartialOrd`] and [`PartialEq`] implementations of `f64`. For example,
1304     /// they consider negative and positive zero equal, while `total_cmp`
1305     /// doesn't.
1306     ///
1307     /// The interpretation of the signaling NaN bit follows the definition in
1308     /// the IEEE 754 standard, which may not match the interpretation by some of
1309     /// the older, non-conformant (e.g. MIPS) hardware implementations.
1310     ///
1311     /// # Example
1312     ///
1313     /// ```
1314     /// struct GoodBoy {
1315     ///     name: String,
1316     ///     weight: f64,
1317     /// }
1318     ///
1319     /// let mut bois = vec![
1320     ///     GoodBoy { name: "Pucci".to_owned(), weight: 0.1 },
1321     ///     GoodBoy { name: "Woofer".to_owned(), weight: 99.0 },
1322     ///     GoodBoy { name: "Yapper".to_owned(), weight: 10.0 },
1323     ///     GoodBoy { name: "Chonk".to_owned(), weight: f64::INFINITY },
1324     ///     GoodBoy { name: "Abs. Unit".to_owned(), weight: f64::NAN },
1325     ///     GoodBoy { name: "Floaty".to_owned(), weight: -5.0 },
1326     /// ];
1327     ///
1328     /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1329     /// # assert!(bois.into_iter().map(|b| b.weight)
1330     /// #     .zip([-5.0, 0.1, 10.0, 99.0, f64::INFINITY, f64::NAN].iter())
1331     /// #     .all(|(a, b)| a.to_bits() == b.to_bits()))
1332     /// ```
1333     #[stable(feature = "total_cmp", since = "1.62.0")]
1334     #[must_use]
1335     #[inline]
1336     pub fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1337         let mut left = self.to_bits() as i64;
1338         let mut right = other.to_bits() as i64;
1339
1340         // In case of negatives, flip all the bits except the sign
1341         // to achieve a similar layout as two's complement integers
1342         //
1343         // Why does this work? IEEE 754 floats consist of three fields:
1344         // Sign bit, exponent and mantissa. The set of exponent and mantissa
1345         // fields as a whole have the property that their bitwise order is
1346         // equal to the numeric magnitude where the magnitude is defined.
1347         // The magnitude is not normally defined on NaN values, but
1348         // IEEE 754 totalOrder defines the NaN values also to follow the
1349         // bitwise order. This leads to order explained in the doc comment.
1350         // However, the representation of magnitude is the same for negative
1351         // and positive numbers – only the sign bit is different.
1352         // To easily compare the floats as signed integers, we need to
1353         // flip the exponent and mantissa bits in case of negative numbers.
1354         // We effectively convert the numbers to "two's complement" form.
1355         //
1356         // To do the flipping, we construct a mask and XOR against it.
1357         // We branchlessly calculate an "all-ones except for the sign bit"
1358         // mask from negative-signed values: right shifting sign-extends
1359         // the integer, so we "fill" the mask with sign bits, and then
1360         // convert to unsigned to push one more zero bit.
1361         // On positive values, the mask is all zeros, so it's a no-op.
1362         left ^= (((left >> 63) as u64) >> 1) as i64;
1363         right ^= (((right >> 63) as u64) >> 1) as i64;
1364
1365         left.cmp(&right)
1366     }
1367
1368     /// Restrict a value to a certain interval unless it is NaN.
1369     ///
1370     /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1371     /// less than `min`. Otherwise this returns `self`.
1372     ///
1373     /// Note that this function returns NaN if the initial value was NaN as
1374     /// well.
1375     ///
1376     /// # Panics
1377     ///
1378     /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1379     ///
1380     /// # Examples
1381     ///
1382     /// ```
1383     /// assert!((-3.0f64).clamp(-2.0, 1.0) == -2.0);
1384     /// assert!((0.0f64).clamp(-2.0, 1.0) == 0.0);
1385     /// assert!((2.0f64).clamp(-2.0, 1.0) == 1.0);
1386     /// assert!((f64::NAN).clamp(-2.0, 1.0).is_nan());
1387     /// ```
1388     #[must_use = "method returns a new number and does not mutate the original value"]
1389     #[stable(feature = "clamp", since = "1.50.0")]
1390     #[inline]
1391     pub fn clamp(mut self, min: f64, max: f64) -> f64 {
1392         assert!(min <= max);
1393         if self < min {
1394             self = min;
1395         }
1396         if self > max {
1397             self = max;
1398         }
1399         self
1400     }
1401 }