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