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