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