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