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