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