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