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