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