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