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