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 #[ferrocene::prevalidated]
667 pub const fn is_nan(self) -> bool {
668 self != self
669 }
670
671 /// Returns `true` if this value is positive infinity or negative infinity, and
672 /// `false` otherwise.
673 ///
674 /// ```
675 /// let f = 7.0f64;
676 /// let inf = f64::INFINITY;
677 /// let neg_inf = f64::NEG_INFINITY;
678 /// let nan = f64::NAN;
679 ///
680 /// assert!(!f.is_infinite());
681 /// assert!(!nan.is_infinite());
682 ///
683 /// assert!(inf.is_infinite());
684 /// assert!(neg_inf.is_infinite());
685 /// ```
686 #[must_use]
687 #[stable(feature = "rust1", since = "1.0.0")]
688 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
689 #[inline]
690 #[ferrocene::prevalidated]
691 pub const fn is_infinite(self) -> bool {
692 // Getting clever with transmutation can result in incorrect answers on some FPUs
693 // FIXME: alter the Rust <-> Rust calling convention to prevent this problem.
694 // See https://github.com/rust-lang/rust/issues/72327
695 (self == f64::INFINITY) | (self == f64::NEG_INFINITY)
696 }
697
698 /// Returns `true` if this number is neither infinite nor NaN.
699 ///
700 /// ```
701 /// let f = 7.0f64;
702 /// let inf: f64 = f64::INFINITY;
703 /// let neg_inf: f64 = f64::NEG_INFINITY;
704 /// let nan: f64 = f64::NAN;
705 ///
706 /// assert!(f.is_finite());
707 ///
708 /// assert!(!nan.is_finite());
709 /// assert!(!inf.is_finite());
710 /// assert!(!neg_inf.is_finite());
711 /// ```
712 #[must_use]
713 #[stable(feature = "rust1", since = "1.0.0")]
714 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
715 #[inline]
716 pub const fn is_finite(self) -> bool {
717 // There's no need to handle NaN separately: if self is NaN,
718 // the comparison is not true, exactly as desired.
719 self.abs() < Self::INFINITY
720 }
721
722 /// Returns `true` if the number is [subnormal].
723 ///
724 /// ```
725 /// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308_f64
726 /// let max = f64::MAX;
727 /// let lower_than_min = 1.0e-308_f64;
728 /// let zero = 0.0_f64;
729 ///
730 /// assert!(!min.is_subnormal());
731 /// assert!(!max.is_subnormal());
732 ///
733 /// assert!(!zero.is_subnormal());
734 /// assert!(!f64::NAN.is_subnormal());
735 /// assert!(!f64::INFINITY.is_subnormal());
736 /// // Values between `0` and `min` are Subnormal.
737 /// assert!(lower_than_min.is_subnormal());
738 /// ```
739 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
740 #[must_use]
741 #[stable(feature = "is_subnormal", since = "1.53.0")]
742 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
743 #[inline]
744 pub const fn is_subnormal(self) -> bool {
745 matches!(self.classify(), FpCategory::Subnormal)
746 }
747
748 /// Returns `true` if the number is neither zero, infinite,
749 /// [subnormal], or NaN.
750 ///
751 /// ```
752 /// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308f64
753 /// let max = f64::MAX;
754 /// let lower_than_min = 1.0e-308_f64;
755 /// let zero = 0.0f64;
756 ///
757 /// assert!(min.is_normal());
758 /// assert!(max.is_normal());
759 ///
760 /// assert!(!zero.is_normal());
761 /// assert!(!f64::NAN.is_normal());
762 /// assert!(!f64::INFINITY.is_normal());
763 /// // Values between `0` and `min` are Subnormal.
764 /// assert!(!lower_than_min.is_normal());
765 /// ```
766 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
767 #[must_use]
768 #[stable(feature = "rust1", since = "1.0.0")]
769 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
770 #[inline]
771 pub const fn is_normal(self) -> bool {
772 matches!(self.classify(), FpCategory::Normal)
773 }
774
775 /// Returns the floating point category of the number. If only one property
776 /// is going to be tested, it is generally faster to use the specific
777 /// predicate instead.
778 ///
779 /// ```
780 /// use std::num::FpCategory;
781 ///
782 /// let num = 12.4_f64;
783 /// let inf = f64::INFINITY;
784 ///
785 /// assert_eq!(num.classify(), FpCategory::Normal);
786 /// assert_eq!(inf.classify(), FpCategory::Infinite);
787 /// ```
788 #[ferrocene::prevalidated]
789 #[stable(feature = "rust1", since = "1.0.0")]
790 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
791 #[must_use]
792 pub const fn classify(self) -> FpCategory {
793 // We used to have complicated logic here that avoids the simple bit-based tests to work
794 // around buggy codegen for x87 targets (see
795 // https://github.com/rust-lang/rust/issues/114479). However, some LLVM versions later, none
796 // of our tests is able to find any difference between the complicated and the naive
797 // version, so now we are back to the naive version.
798 let b = self.to_bits();
799 match (b & Self::MANTISSA_MASK, b & Self::EXPONENT_MASK) {
800 (0, Self::EXPONENT_MASK) => FpCategory::Infinite,
801 (_, Self::EXPONENT_MASK) => FpCategory::Nan,
802 (0, 0) => FpCategory::Zero,
803 (_, 0) => FpCategory::Subnormal,
804 _ => FpCategory::Normal,
805 }
806 }
807
808 /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with
809 /// positive sign bit and positive infinity.
810 ///
811 /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
812 /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
813 /// conserved over arithmetic operations, the result of `is_sign_positive` on
814 /// a NaN might produce an unexpected or non-portable result. See the [specification
815 /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == 1.0`
816 /// if you need fully portable behavior (will return NaN for all NaNs).
817 ///
818 /// ```
819 /// let f = 7.0_f64;
820 /// let g = -7.0_f64;
821 ///
822 /// assert!(f.is_sign_positive());
823 /// assert!(!g.is_sign_positive());
824 /// ```
825 #[must_use]
826 #[stable(feature = "rust1", since = "1.0.0")]
827 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
828 #[inline]
829 #[ferrocene::prevalidated]
830 pub const fn is_sign_positive(self) -> bool {
831 !self.is_sign_negative()
832 }
833
834 /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with
835 /// negative sign bit and negative infinity.
836 ///
837 /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
838 /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
839 /// conserved over arithmetic operations, the result of `is_sign_negative` on
840 /// a NaN might produce an unexpected or non-portable result. See the [specification
841 /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == -1.0`
842 /// if you need fully portable behavior (will return NaN for all NaNs).
843 ///
844 /// ```
845 /// let f = 7.0_f64;
846 /// let g = -7.0_f64;
847 ///
848 /// assert!(!f.is_sign_negative());
849 /// assert!(g.is_sign_negative());
850 /// ```
851 #[must_use]
852 #[stable(feature = "rust1", since = "1.0.0")]
853 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
854 #[inline]
855 #[ferrocene::prevalidated]
856 pub const fn is_sign_negative(self) -> bool {
857 // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
858 // applies to zeros and NaNs as well.
859 self.to_bits() & Self::SIGN_MASK != 0
860 }
861
862 /// Returns the least number greater than `self`.
863 ///
864 /// Let `TINY` be the smallest representable positive `f64`. Then,
865 /// - if `self.is_nan()`, this returns `self`;
866 /// - if `self` is [`NEG_INFINITY`], this returns [`MIN`];
867 /// - if `self` is `-TINY`, this returns -0.0;
868 /// - if `self` is -0.0 or +0.0, this returns `TINY`;
869 /// - if `self` is [`MAX`] or [`INFINITY`], this returns [`INFINITY`];
870 /// - otherwise the unique least value greater than `self` is returned.
871 ///
872 /// The identity `x.next_up() == -(-x).next_down()` holds for all non-NaN `x`. When `x`
873 /// is finite `x == x.next_up().next_down()` also holds.
874 ///
875 /// ```rust
876 /// // f64::EPSILON is the difference between 1.0 and the next number up.
877 /// assert_eq!(1.0f64.next_up(), 1.0 + f64::EPSILON);
878 /// // But not for most numbers.
879 /// assert!(0.1f64.next_up() < 0.1 + f64::EPSILON);
880 /// assert_eq!(9007199254740992f64.next_up(), 9007199254740994.0);
881 /// ```
882 ///
883 /// This operation corresponds to IEEE-754 `nextUp`.
884 ///
885 /// [`NEG_INFINITY`]: Self::NEG_INFINITY
886 /// [`INFINITY`]: Self::INFINITY
887 /// [`MIN`]: Self::MIN
888 /// [`MAX`]: Self::MAX
889 #[inline]
890 #[doc(alias = "nextUp")]
891 #[stable(feature = "float_next_up_down", since = "1.86.0")]
892 #[rustc_const_stable(feature = "float_next_up_down", since = "1.86.0")]
893 #[must_use = "method returns a new number and does not mutate the original value"]
894 pub const fn next_up(self) -> Self {
895 // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
896 // denormals to zero. This is in general unsound and unsupported, but here
897 // we do our best to still produce the correct result on such targets.
898 let bits = self.to_bits();
899 if self.is_nan() || bits == Self::INFINITY.to_bits() {
900 return self;
901 }
902
903 let abs = bits & !Self::SIGN_MASK;
904 let next_bits = if abs == 0 {
905 Self::TINY_BITS
906 } else if bits == abs {
907 bits + 1
908 } else {
909 bits - 1
910 };
911 Self::from_bits(next_bits)
912 }
913
914 /// Returns the greatest number less than `self`.
915 ///
916 /// Let `TINY` be the smallest representable positive `f64`. Then,
917 /// - if `self.is_nan()`, this returns `self`;
918 /// - if `self` is [`INFINITY`], this returns [`MAX`];
919 /// - if `self` is `TINY`, this returns 0.0;
920 /// - if `self` is -0.0 or +0.0, this returns `-TINY`;
921 /// - if `self` is [`MIN`] or [`NEG_INFINITY`], this returns [`NEG_INFINITY`];
922 /// - otherwise the unique greatest value less than `self` is returned.
923 ///
924 /// The identity `x.next_down() == -(-x).next_up()` holds for all non-NaN `x`. When `x`
925 /// is finite `x == x.next_down().next_up()` also holds.
926 ///
927 /// ```rust
928 /// let x = 1.0f64;
929 /// // Clamp value into range [0, 1).
930 /// let clamped = x.clamp(0.0, 1.0f64.next_down());
931 /// assert!(clamped < 1.0);
932 /// assert_eq!(clamped.next_up(), 1.0);
933 /// ```
934 ///
935 /// This operation corresponds to IEEE-754 `nextDown`.
936 ///
937 /// [`NEG_INFINITY`]: Self::NEG_INFINITY
938 /// [`INFINITY`]: Self::INFINITY
939 /// [`MIN`]: Self::MIN
940 /// [`MAX`]: Self::MAX
941 #[inline]
942 #[doc(alias = "nextDown")]
943 #[stable(feature = "float_next_up_down", since = "1.86.0")]
944 #[rustc_const_stable(feature = "float_next_up_down", since = "1.86.0")]
945 #[must_use = "method returns a new number and does not mutate the original value"]
946 pub const fn next_down(self) -> Self {
947 // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
948 // denormals to zero. This is in general unsound and unsupported, but here
949 // we do our best to still produce the correct result on such targets.
950 let bits = self.to_bits();
951 if self.is_nan() || bits == Self::NEG_INFINITY.to_bits() {
952 return self;
953 }
954
955 let abs = bits & !Self::SIGN_MASK;
956 let next_bits = if abs == 0 {
957 Self::NEG_TINY_BITS
958 } else if bits == abs {
959 bits - 1
960 } else {
961 bits + 1
962 };
963 Self::from_bits(next_bits)
964 }
965
966 /// Takes the reciprocal (inverse) of a number, `1/x`.
967 ///
968 /// ```
969 /// let x = 2.0_f64;
970 /// let abs_difference = (x.recip() - (1.0 / x)).abs();
971 ///
972 /// assert!(abs_difference < 1e-10);
973 /// ```
974 #[must_use = "this returns the result of the operation, without modifying the original"]
975 #[stable(feature = "rust1", since = "1.0.0")]
976 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
977 #[inline]
978 pub const fn recip(self) -> f64 {
979 1.0 / self
980 }
981
982 /// Converts radians to degrees.
983 ///
984 /// # Unspecified precision
985 ///
986 /// The precision of this function is non-deterministic. This means it varies by platform,
987 /// Rust version, and can even differ within the same execution from one invocation to the next.
988 ///
989 /// # Examples
990 ///
991 /// ```
992 /// let angle = std::f64::consts::PI;
993 ///
994 /// let abs_difference = (angle.to_degrees() - 180.0).abs();
995 ///
996 /// assert!(abs_difference < 1e-10);
997 /// ```
998 #[must_use = "this returns the result of the operation, \
999 without modifying the original"]
1000 #[stable(feature = "rust1", since = "1.0.0")]
1001 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1002 #[inline]
1003 pub const fn to_degrees(self) -> f64 {
1004 // The division here is correctly rounded with respect to the true value of 180/π.
1005 // Although π is irrational and already rounded, the double rounding happens
1006 // to produce correct result for f64.
1007 const PIS_IN_180: f64 = 180.0 / consts::PI;
1008 self * PIS_IN_180
1009 }
1010
1011 /// Converts degrees to radians.
1012 ///
1013 /// # Unspecified precision
1014 ///
1015 /// The precision of this function is non-deterministic. This means it varies by platform,
1016 /// Rust version, and can even differ within the same execution from one invocation to the next.
1017 ///
1018 /// # Examples
1019 ///
1020 /// ```
1021 /// let angle = 180.0_f64;
1022 ///
1023 /// let abs_difference = (angle.to_radians() - std::f64::consts::PI).abs();
1024 ///
1025 /// assert!(abs_difference < 1e-10);
1026 /// ```
1027 #[must_use = "this returns the result of the operation, \
1028 without modifying the original"]
1029 #[stable(feature = "rust1", since = "1.0.0")]
1030 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1031 #[inline]
1032 pub const fn to_radians(self) -> f64 {
1033 // The division here is correctly rounded with respect to the true value of π/180.
1034 // Although π is irrational and already rounded, the double rounding happens
1035 // to produce correct result for f64.
1036 const RADS_PER_DEG: f64 = consts::PI / 180.0;
1037 self * RADS_PER_DEG
1038 }
1039
1040 /// Returns the maximum of the two numbers, ignoring NaN.
1041 ///
1042 /// If exactly one of the arguments is NaN (quiet or signaling), then the other argument is
1043 /// returned. If both arguments are NaN, the return value is NaN, with the bit pattern picked
1044 /// using the usual [rules for arithmetic operations](f32#nan-bit-patterns). If the inputs
1045 /// compare equal (such as for the case of `+0.0` and `-0.0`), either input may be returned
1046 /// non-deterministically.
1047 ///
1048 /// The handling of NaNs follows the IEEE 754-2019 semantics for `maximumNumber`, treating all
1049 /// NaNs the same way to ensure the operation is associative. The handling of signed zeros
1050 /// follows the IEEE 754-2008 semantics for `maxNum`.
1051 ///
1052 /// ```
1053 /// let x = 1.0_f64;
1054 /// let y = 2.0_f64;
1055 ///
1056 /// assert_eq!(x.max(y), y);
1057 /// assert_eq!(x.max(f64::NAN), x);
1058 /// ```
1059 #[must_use = "this returns the result of the comparison, without modifying either input"]
1060 #[stable(feature = "rust1", since = "1.0.0")]
1061 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1062 #[inline]
1063 pub const fn max(self, other: f64) -> f64 {
1064 intrinsics::maximum_number_nsz_f64(self, other)
1065 }
1066
1067 /// Returns the minimum of the two numbers, ignoring NaN.
1068 ///
1069 /// If exactly one of the arguments is NaN (quiet or signaling), then the other argument is
1070 /// returned. If both arguments are NaN, the return value is NaN, with the bit pattern picked
1071 /// using the usual [rules for arithmetic operations](f32#nan-bit-patterns). If the inputs
1072 /// compare equal (such as for the case of `+0.0` and `-0.0`), either input may be returned
1073 /// non-deterministically.
1074 ///
1075 /// The handling of NaNs follows the IEEE 754-2019 semantics for `minimumNumber`, treating all
1076 /// NaNs the same way to ensure the operation is associative. The handling of signed zeros
1077 /// follows the IEEE 754-2008 semantics for `minNum`.
1078 ///
1079 /// ```
1080 /// let x = 1.0_f64;
1081 /// let y = 2.0_f64;
1082 ///
1083 /// assert_eq!(x.min(y), x);
1084 /// assert_eq!(x.min(f64::NAN), x);
1085 /// ```
1086 #[must_use = "this returns the result of the comparison, without modifying either input"]
1087 #[stable(feature = "rust1", since = "1.0.0")]
1088 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1089 #[inline]
1090 pub const fn min(self, other: f64) -> f64 {
1091 intrinsics::minimum_number_nsz_f64(self, other)
1092 }
1093
1094 /// Returns the maximum of the two numbers, propagating NaN.
1095 ///
1096 /// If at least one of the arguments is NaN, the return value is NaN, with the bit pattern
1097 /// picked using the usual [rules for arithmetic operations](f32#nan-bit-patterns). Furthermore,
1098 /// `-0.0` is considered to be less than `+0.0`, making this function fully deterministic for
1099 /// non-NaN inputs.
1100 ///
1101 /// This is in contrast to [`f64::max`] which only returns NaN when *both* arguments are NaN,
1102 /// and which does not reliably order `-0.0` and `+0.0`.
1103 ///
1104 /// This follows the IEEE 754-2019 semantics for `maximum`.
1105 ///
1106 /// ```
1107 /// #![feature(float_minimum_maximum)]
1108 /// let x = 1.0_f64;
1109 /// let y = 2.0_f64;
1110 ///
1111 /// assert_eq!(x.maximum(y), y);
1112 /// assert!(x.maximum(f64::NAN).is_nan());
1113 /// ```
1114 #[must_use = "this returns the result of the comparison, without modifying either input"]
1115 #[unstable(feature = "float_minimum_maximum", issue = "91079")]
1116 #[inline]
1117 pub const fn maximum(self, other: f64) -> f64 {
1118 intrinsics::maximumf64(self, other)
1119 }
1120
1121 /// Returns the minimum of the two numbers, propagating NaN.
1122 ///
1123 /// If at least one of the arguments is NaN, the return value is NaN, with the bit pattern
1124 /// picked using the usual [rules for arithmetic operations](f32#nan-bit-patterns). Furthermore,
1125 /// `-0.0` is considered to be less than `+0.0`, making this function fully deterministic for
1126 /// non-NaN inputs.
1127 ///
1128 /// This is in contrast to [`f64::min`] which only returns NaN when *both* arguments are NaN,
1129 /// and which does not reliably order `-0.0` and `+0.0`.
1130 ///
1131 /// This follows the IEEE 754-2019 semantics for `minimum`.
1132 ///
1133 /// ```
1134 /// #![feature(float_minimum_maximum)]
1135 /// let x = 1.0_f64;
1136 /// let y = 2.0_f64;
1137 ///
1138 /// assert_eq!(x.minimum(y), x);
1139 /// assert!(x.minimum(f64::NAN).is_nan());
1140 /// ```
1141 #[must_use = "this returns the result of the comparison, without modifying either input"]
1142 #[unstable(feature = "float_minimum_maximum", issue = "91079")]
1143 #[inline]
1144 pub const fn minimum(self, other: f64) -> f64 {
1145 intrinsics::minimumf64(self, other)
1146 }
1147
1148 /// Calculates the midpoint (average) between `self` and `rhs`.
1149 ///
1150 /// This returns NaN when *either* argument is NaN or if a combination of
1151 /// +inf and -inf is provided as arguments.
1152 ///
1153 /// # Examples
1154 ///
1155 /// ```
1156 /// assert_eq!(1f64.midpoint(4.0), 2.5);
1157 /// assert_eq!((-5.5f64).midpoint(8.0), 1.25);
1158 /// ```
1159 #[inline]
1160 #[doc(alias = "average")]
1161 #[stable(feature = "num_midpoint", since = "1.85.0")]
1162 #[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
1163 #[must_use = "this returns the result of the operation, \
1164 without modifying the original"]
1165 pub const fn midpoint(self, other: f64) -> f64 {
1166 const HI: f64 = f64::MAX * 0.5;
1167
1168 let (a, b) = (self, other);
1169 let abs_a = a.abs();
1170 let abs_b = b.abs();
1171
1172 if abs_a <= HI && abs_b <= HI {
1173 // Overflow is impossible
1174 (a + b) * 0.5
1175 } else {
1176 (a * 0.5) + (b * 0.5)
1177 }
1178 }
1179
1180 /// Rounds toward zero and converts to any primitive integer type,
1181 /// assuming that the value is finite and fits in that type.
1182 ///
1183 /// ```
1184 /// let value = 4.6_f64;
1185 /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
1186 /// assert_eq!(rounded, 4);
1187 ///
1188 /// let value = -128.9_f64;
1189 /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
1190 /// assert_eq!(rounded, i8::MIN);
1191 /// ```
1192 ///
1193 /// # Safety
1194 ///
1195 /// The value must:
1196 ///
1197 /// * Not be `NaN`
1198 /// * Not be infinite
1199 /// * Be representable in the return type `Int`, after truncating off its fractional part
1200 #[must_use = "this returns the result of the operation, \
1201 without modifying the original"]
1202 #[stable(feature = "float_approx_unchecked_to", since = "1.44.0")]
1203 #[inline]
1204 pub unsafe fn to_int_unchecked<Int>(self) -> Int
1205 where
1206 Self: FloatToInt<Int>,
1207 {
1208 // SAFETY: the caller must uphold the safety contract for
1209 // `FloatToInt::to_int_unchecked`.
1210 unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
1211 }
1212
1213 /// Converts to the target float type, rounding as defined in IEEE 754.
1214 ///
1215 /// This is equivalent to `self as Flt`. Narrowing to a smaller type can
1216 /// produce an infinity.
1217 ///
1218 /// ```
1219 /// #![feature(float_conversions)]
1220 ///
1221 /// let x = 1.5_f64;
1222 /// assert_eq!(x.cast::<f32>(), 1.5_f32);
1223 /// ```
1224 #[unstable(feature = "float_conversions", issue = "159913")]
1225 #[must_use = "this returns the result of the operation, without modifying the original"]
1226 #[inline]
1227 pub fn cast<Flt>(self) -> Flt
1228 where
1229 Self: FloatToFloat<Flt>,
1230 {
1231 FloatToFloat::<Flt>::cast(self)
1232 }
1233
1234 /// Rounds toward zero and converts to any primitive integer type, saturating
1235 /// at the type's boundaries and mapping `NaN` to zero.
1236 ///
1237 /// This is equivalent to `self as Int`.
1238 ///
1239 /// ```
1240 /// #![feature(float_conversions)]
1241 ///
1242 /// assert_eq!(255.5_f64.to_int_saturating::<u8>(), 255);
1243 /// assert_eq!(300.0_f64.to_int_saturating::<u8>(), 255);
1244 /// assert_eq!((-1.0_f64).to_int_saturating::<u8>(), 0);
1245 /// assert_eq!(f64::NAN.to_int_saturating::<u8>(), 0);
1246 /// ```
1247 #[unstable(feature = "float_conversions", issue = "159913")]
1248 #[must_use = "this returns the result of the operation, without modifying the original"]
1249 #[inline]
1250 pub fn to_int_saturating<Int>(self) -> Int
1251 where
1252 Self: FloatToInt<Int>,
1253 {
1254 FloatToInt::<Int>::to_int_saturating(self)
1255 }
1256
1257 /// Rounds toward zero and converts to any primitive integer type, returning
1258 /// `None` if the value is `NaN`, infinite, or does not fit in the target type.
1259 ///
1260 /// ```
1261 /// #![feature(float_conversions)]
1262 ///
1263 /// assert_eq!(255.5_f64.to_int_checked::<u8>(), Some(255));
1264 /// assert_eq!(256.0_f64.to_int_checked::<u8>(), None);
1265 /// assert_eq!(f64::NAN.to_int_checked::<u8>(), None);
1266 /// ```
1267 #[unstable(feature = "float_conversions", issue = "159913")]
1268 #[must_use = "this returns the result of the operation, without modifying the original"]
1269 #[inline]
1270 pub fn to_int_checked<Int>(self) -> Option<Int>
1271 where
1272 Self: FloatToInt<Int>,
1273 {
1274 FloatToInt::<Int>::to_int_checked(self)
1275 }
1276
1277 /// Rounds toward zero and converts to any primitive integer type.
1278 ///
1279 /// This is equivalent to `self.to_int_checked().unwrap()`.
1280 ///
1281 /// # Panics
1282 ///
1283 /// Panics if the value is `NaN`, infinite, or does not fit in the target type.
1284 ///
1285 /// ```
1286 /// #![feature(float_conversions)]
1287 ///
1288 /// assert_eq!(255.5_f64.to_int_strict::<u8>(), 255);
1289 /// ```
1290 #[unstable(feature = "float_conversions", issue = "159913")]
1291 #[must_use = "this returns the result of the operation, without modifying the original"]
1292 #[inline]
1293 #[track_caller]
1294 pub fn to_int_strict<Int>(self) -> Int
1295 where
1296 Self: FloatToInt<Int>,
1297 {
1298 self.to_int_checked::<Int>()
1299 .expect("the value cannot be represented in the target integer type")
1300 }
1301
1302 /// Raw transmutation to `u64`.
1303 ///
1304 /// This is currently identical to `transmute::<f64, u64>(self)` on all platforms.
1305 ///
1306 /// See [`from_bits`](Self::from_bits) for some discussion of the
1307 /// portability of this operation (there are almost no issues).
1308 ///
1309 /// Note that this function is distinct from `as` casting, which attempts to
1310 /// preserve the *numeric* value, and not the bitwise value.
1311 ///
1312 /// # Examples
1313 ///
1314 /// ```
1315 /// assert!((1f64).to_bits() != 1f64 as u64); // to_bits() is not casting!
1316 /// assert_eq!((12.5f64).to_bits(), 0x4029000000000000);
1317 /// ```
1318 #[must_use = "this returns the result of the operation, \
1319 without modifying the original"]
1320 #[stable(feature = "float_bits_conv", since = "1.20.0")]
1321 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1322 #[allow(unnecessary_transmutes)]
1323 #[inline]
1324 #[ferrocene::prevalidated]
1325 pub const fn to_bits(self) -> u64 {
1326 // SAFETY: `u64` is a plain old datatype so we can always transmute to it.
1327 unsafe { mem::transmute(self) }
1328 }
1329
1330 /// Raw transmutation from `u64`.
1331 ///
1332 /// This is currently identical to `transmute::<u64, f64>(v)` on all platforms.
1333 /// It turns out this is incredibly portable, for two reasons:
1334 ///
1335 /// * Floats and Ints have the same endianness on all supported platforms.
1336 /// * IEEE 754 very precisely specifies the bit layout of floats.
1337 ///
1338 /// However there is one caveat: prior to the 2008 version of IEEE 754, how
1339 /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
1340 /// (notably x86 and ARM) picked the interpretation that was ultimately
1341 /// standardized in 2008, but some didn't (notably MIPS). As a result, all
1342 /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
1343 ///
1344 /// Rather than trying to preserve signaling-ness cross-platform, this
1345 /// implementation favors preserving the exact bits. This means that
1346 /// any payloads encoded in NaNs will be preserved even if the result of
1347 /// this method is sent over the network from an x86 machine to a MIPS one.
1348 ///
1349 /// If the results of this method are only manipulated by the same
1350 /// architecture that produced them, then there is no portability concern.
1351 ///
1352 /// If the input isn't NaN, then there is no portability concern.
1353 ///
1354 /// If you don't care about signaling-ness (very likely), then there is no
1355 /// portability concern.
1356 ///
1357 /// Note that this function is distinct from `as` casting, which attempts to
1358 /// preserve the *numeric* value, and not the bitwise value.
1359 ///
1360 /// # Examples
1361 ///
1362 /// ```
1363 /// let v = f64::from_bits(0x4029000000000000);
1364 /// assert_eq!(v, 12.5);
1365 /// ```
1366 #[stable(feature = "float_bits_conv", since = "1.20.0")]
1367 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1368 #[must_use]
1369 #[inline]
1370 #[allow(unnecessary_transmutes)]
1371 #[ferrocene::prevalidated]
1372 pub const fn from_bits(v: u64) -> Self {
1373 // It turns out the safety issues with sNaN were overblown! Hooray!
1374 // SAFETY: `u64` is a plain old datatype so we can always transmute from it.
1375 unsafe { mem::transmute(v) }
1376 }
1377
1378 /// Returns the memory representation of this floating point number as a byte array in
1379 /// big-endian (network) byte order.
1380 ///
1381 /// See [`from_bits`](Self::from_bits) for some discussion of the
1382 /// portability of this operation (there are almost no issues).
1383 ///
1384 /// # Examples
1385 ///
1386 /// ```
1387 /// let bytes = 12.5f64.to_be_bytes();
1388 /// assert_eq!(bytes, [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1389 /// ```
1390 #[must_use = "this returns the result of the operation, \
1391 without modifying the original"]
1392 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1393 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1394 #[inline]
1395 pub const fn to_be_bytes(self) -> [u8; 8] {
1396 self.to_bits().to_be_bytes()
1397 }
1398
1399 /// Returns the memory representation of this floating point number as a byte array in
1400 /// little-endian byte order.
1401 ///
1402 /// See [`from_bits`](Self::from_bits) for some discussion of the
1403 /// portability of this operation (there are almost no issues).
1404 ///
1405 /// # Examples
1406 ///
1407 /// ```
1408 /// let bytes = 12.5f64.to_le_bytes();
1409 /// assert_eq!(bytes, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]);
1410 /// ```
1411 #[must_use = "this returns the result of the operation, \
1412 without modifying the original"]
1413 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1414 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1415 #[inline]
1416 #[ferrocene::prevalidated]
1417 pub const fn to_le_bytes(self) -> [u8; 8] {
1418 self.to_bits().to_le_bytes()
1419 }
1420
1421 /// Returns the memory representation of this floating point number as a byte array in
1422 /// native byte order.
1423 ///
1424 /// As the target platform's native endianness is used, portable code
1425 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1426 ///
1427 /// [`to_be_bytes`]: f64::to_be_bytes
1428 /// [`to_le_bytes`]: f64::to_le_bytes
1429 ///
1430 /// See [`from_bits`](Self::from_bits) for some discussion of the
1431 /// portability of this operation (there are almost no issues).
1432 ///
1433 /// # Examples
1434 ///
1435 /// ```
1436 /// let bytes = 12.5f64.to_ne_bytes();
1437 /// assert_eq!(
1438 /// bytes,
1439 /// if cfg!(target_endian = "big") {
1440 /// [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1441 /// } else {
1442 /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]
1443 /// }
1444 /// );
1445 /// ```
1446 #[must_use = "this returns the result of the operation, \
1447 without modifying the original"]
1448 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1449 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1450 #[inline]
1451 pub const fn to_ne_bytes(self) -> [u8; 8] {
1452 self.to_bits().to_ne_bytes()
1453 }
1454
1455 /// Creates a floating point value from its representation as a byte array in big endian.
1456 ///
1457 /// See [`from_bits`](Self::from_bits) for some discussion of the
1458 /// portability of this operation (there are almost no issues).
1459 ///
1460 /// # Examples
1461 ///
1462 /// ```
1463 /// let value = f64::from_be_bytes([0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1464 /// assert_eq!(value, 12.5);
1465 /// ```
1466 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1467 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1468 #[must_use]
1469 #[inline]
1470 pub const fn from_be_bytes(bytes: [u8; 8]) -> Self {
1471 Self::from_bits(u64::from_be_bytes(bytes))
1472 }
1473
1474 /// Creates a floating point value from its representation as a byte array in little endian.
1475 ///
1476 /// See [`from_bits`](Self::from_bits) for some discussion of the
1477 /// portability of this operation (there are almost no issues).
1478 ///
1479 /// # Examples
1480 ///
1481 /// ```
1482 /// let value = f64::from_le_bytes([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]);
1483 /// assert_eq!(value, 12.5);
1484 /// ```
1485 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1486 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1487 #[must_use]
1488 #[inline]
1489 #[ferrocene::prevalidated]
1490 pub const fn from_le_bytes(bytes: [u8; 8]) -> Self {
1491 Self::from_bits(u64::from_le_bytes(bytes))
1492 }
1493
1494 /// Creates a floating point value from its representation as a byte array in native endian.
1495 ///
1496 /// As the target platform's native endianness is used, portable code
1497 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1498 /// appropriate instead.
1499 ///
1500 /// [`from_be_bytes`]: f64::from_be_bytes
1501 /// [`from_le_bytes`]: f64::from_le_bytes
1502 ///
1503 /// See [`from_bits`](Self::from_bits) for some discussion of the
1504 /// portability of this operation (there are almost no issues).
1505 ///
1506 /// # Examples
1507 ///
1508 /// ```
1509 /// let value = f64::from_ne_bytes(if cfg!(target_endian = "big") {
1510 /// [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1511 /// } else {
1512 /// [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]
1513 /// });
1514 /// assert_eq!(value, 12.5);
1515 /// ```
1516 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1517 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1518 #[must_use]
1519 #[inline]
1520 pub const fn from_ne_bytes(bytes: [u8; 8]) -> Self {
1521 Self::from_bits(u64::from_ne_bytes(bytes))
1522 }
1523
1524 /// Returns the ordering between `self` and `other`.
1525 ///
1526 /// Unlike the standard partial comparison between floating point numbers,
1527 /// this comparison always produces an ordering in accordance to
1528 /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1529 /// floating point standard. The values are ordered in the following sequence:
1530 ///
1531 /// - negative quiet NaN
1532 /// - negative signaling NaN
1533 /// - negative infinity
1534 /// - negative numbers
1535 /// - negative subnormal numbers
1536 /// - negative zero
1537 /// - positive zero
1538 /// - positive subnormal numbers
1539 /// - positive numbers
1540 /// - positive infinity
1541 /// - positive signaling NaN
1542 /// - positive quiet NaN.
1543 ///
1544 /// The ordering established by this function does not always agree with the
1545 /// [`PartialOrd`] and [`PartialEq`] implementations of `f64`. For example,
1546 /// they consider negative and positive zero equal, while `total_cmp`
1547 /// doesn't.
1548 ///
1549 /// The interpretation of the signaling NaN bit follows the definition in
1550 /// the IEEE 754 standard, which may not match the interpretation by some of
1551 /// the older, non-conformant (e.g. MIPS) hardware implementations.
1552 ///
1553 /// # Example
1554 ///
1555 /// ```
1556 /// struct GoodBoy {
1557 /// name: String,
1558 /// weight: f64,
1559 /// }
1560 ///
1561 /// let mut bois = vec![
1562 /// GoodBoy { name: "Pucci".to_owned(), weight: 0.1 },
1563 /// GoodBoy { name: "Woofer".to_owned(), weight: 99.0 },
1564 /// GoodBoy { name: "Yapper".to_owned(), weight: 10.0 },
1565 /// GoodBoy { name: "Chonk".to_owned(), weight: f64::INFINITY },
1566 /// GoodBoy { name: "Abs. Unit".to_owned(), weight: f64::NAN },
1567 /// GoodBoy { name: "Floaty".to_owned(), weight: -5.0 },
1568 /// ];
1569 ///
1570 /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1571 ///
1572 /// // `f64::NAN` could be positive or negative, which will affect the sort order.
1573 /// if f64::NAN.is_sign_negative() {
1574 /// assert!(bois.into_iter().map(|b| b.weight)
1575 /// .zip([f64::NAN, -5.0, 0.1, 10.0, 99.0, f64::INFINITY].iter())
1576 /// .all(|(a, b)| a.to_bits() == b.to_bits()))
1577 /// } else {
1578 /// assert!(bois.into_iter().map(|b| b.weight)
1579 /// .zip([-5.0, 0.1, 10.0, 99.0, f64::INFINITY, f64::NAN].iter())
1580 /// .all(|(a, b)| a.to_bits() == b.to_bits()))
1581 /// }
1582 /// ```
1583 #[stable(feature = "total_cmp", since = "1.62.0")]
1584 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1585 #[must_use]
1586 #[inline]
1587 pub const fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1588 let mut left = self.to_bits() as i64;
1589 let mut right = other.to_bits() as i64;
1590
1591 // In case of negatives, flip all the bits except the sign
1592 // to achieve a similar layout as two's complement integers
1593 //
1594 // Why does this work? IEEE 754 floats consist of three fields:
1595 // Sign bit, exponent and mantissa. The set of exponent and mantissa
1596 // fields as a whole have the property that their bitwise order is
1597 // equal to the numeric magnitude where the magnitude is defined.
1598 // The magnitude is not normally defined on NaN values, but
1599 // IEEE 754 totalOrder defines the NaN values also to follow the
1600 // bitwise order. This leads to order explained in the doc comment.
1601 // However, the representation of magnitude is the same for negative
1602 // and positive numbers – only the sign bit is different.
1603 // To easily compare the floats as signed integers, we need to
1604 // flip the exponent and mantissa bits in case of negative numbers.
1605 // We effectively convert the numbers to "two's complement" form.
1606 //
1607 // To do the flipping, we construct a mask and XOR against it.
1608 // We branchlessly calculate an "all-ones except for the sign bit"
1609 // mask from negative-signed values: right shifting sign-extends
1610 // the integer, so we "fill" the mask with sign bits, and then
1611 // convert to unsigned to push one more zero bit.
1612 // On positive values, the mask is all zeros, so it's a no-op.
1613 left ^= (((left >> 63) as u64) >> 1) as i64;
1614 right ^= (((right >> 63) as u64) >> 1) as i64;
1615
1616 left.cmp(&right)
1617 }
1618
1619 /// Restrict a value to a certain interval unless it is NaN.
1620 ///
1621 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1622 /// less than `min`. Otherwise this returns `self`.
1623 ///
1624 /// Note that this function returns NaN if the initial value was NaN as
1625 /// well. If the result is zero and among the three inputs `self`, `min`, and `max` there are
1626 /// zeros with different sign, either `0.0` or `-0.0` is returned non-deterministically.
1627 ///
1628 /// # Panics
1629 ///
1630 /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1631 ///
1632 /// # Examples
1633 ///
1634 /// ```
1635 /// assert!((-3.0f64).clamp(-2.0, 1.0) == -2.0);
1636 /// assert!((0.0f64).clamp(-2.0, 1.0) == 0.0);
1637 /// assert!((2.0f64).clamp(-2.0, 1.0) == 1.0);
1638 /// assert!((f64::NAN).clamp(-2.0, 1.0).is_nan());
1639 ///
1640 /// // These always returns zero, but the sign (which is ignored by `==`) is non-deterministic.
1641 /// assert!((0.0f64).clamp(-0.0, -0.0) == 0.0);
1642 /// assert!((1.0f64).clamp(-0.0, 0.0) == 0.0);
1643 /// // This is definitely a negative zero.
1644 /// assert!((-1.0f64).clamp(-0.0, 1.0).is_sign_negative());
1645 /// ```
1646 #[must_use = "method returns a new number and does not mutate the original value"]
1647 #[stable(feature = "clamp", since = "1.50.0")]
1648 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1649 #[inline]
1650 #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "NaN is also invalid")]
1651 pub const fn clamp(mut self, min: f64, max: f64) -> f64 {
1652 const_assert!(
1653 min <= max,
1654 "min > max, or either was NaN",
1655 "min > max, or either was NaN. min = {min:?}, max = {max:?}",
1656 min: f64,
1657 max: f64,
1658 );
1659
1660 if self < min {
1661 self = min;
1662 }
1663 if self > max {
1664 self = max;
1665 }
1666 self
1667 }
1668
1669 /// Clamps this number to a symmetric range centered around zero.
1670 ///
1671 /// The method clamps the number's magnitude (absolute value) to be at most `limit`.
1672 ///
1673 /// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more
1674 /// explicit about the intent.
1675 ///
1676 /// # Panics
1677 ///
1678 /// Panics if `limit` is negative or NaN, as this indicates a logic error.
1679 ///
1680 /// # Examples
1681 ///
1682 /// ```
1683 /// #![feature(clamp_magnitude)]
1684 /// assert_eq!(5.0f64.clamp_magnitude(3.0), 3.0);
1685 /// assert_eq!((-5.0f64).clamp_magnitude(3.0), -3.0);
1686 /// assert_eq!(2.0f64.clamp_magnitude(3.0), 2.0);
1687 /// assert_eq!((-2.0f64).clamp_magnitude(3.0), -2.0);
1688 /// ```
1689 #[must_use = "this returns the clamped value and does not modify the original"]
1690 #[unstable(feature = "clamp_magnitude", issue = "148519")]
1691 #[inline]
1692 #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "NaN is also invalid")]
1693 pub fn clamp_magnitude(self, limit: f64) -> f64 {
1694 assert!(limit >= 0.0, "limit must be non-negative and not NaN");
1695 let limit = limit.abs(); // Canonicalises -0.0 to 0.0
1696 self.clamp(-limit, limit)
1697 }
1698
1699 /// Restrict a value to a certain range, unless it is NaN.
1700 ///
1701 /// This is largely equal to `max`, `min`, or `clamp`, depending on whether the range is
1702 /// `min..`, `..=max`, or `min..=max`, respectively. However, unlike `max` and `min`, it will
1703 /// panic if any bound is NaN.
1704 ///
1705 /// Note that this function returns NaN if the initial value was NaN as
1706 /// well.
1707 ///
1708 /// Exclusive ranges are not permitted.
1709 ///
1710 /// # Panics
1711 ///
1712 /// Panics on `min..=max` if `min > max`, or if any bound is NaN.
1713 ///
1714 /// # Examples
1715 ///
1716 /// ```
1717 /// #![feature(clamp_to)]
1718 /// assert_eq!((-3.0f64).clamp_to(-2.0..=1.0), -2.0);
1719 /// assert_eq!(0.0f64.clamp_to(-2.0..=1.0), 0.0);
1720 /// assert_eq!(2.0f64.clamp_to(..=1.0), 1.0);
1721 /// assert_eq!(5.0f64.clamp_to(7.0..), 7.0);
1722 /// assert!(f64::NAN.clamp_to(1.0..=2.0).is_nan());
1723 /// ```
1724 #[must_use]
1725 #[inline]
1726 #[unstable(feature = "clamp_to", issue = "147781")]
1727 pub fn clamp_to<R>(self, range: R) -> Self
1728 where
1729 R: crate::cmp::ClampBounds<Self>,
1730 {
1731 range.clamp(self)
1732 }
1733
1734 /// Computes the absolute value of `self`.
1735 ///
1736 /// This function always returns the precise result.
1737 ///
1738 /// # Examples
1739 ///
1740 /// ```
1741 /// let x = 3.5_f64;
1742 /// let y = -3.5_f64;
1743 ///
1744 /// assert_eq!(x.abs(), x);
1745 /// assert_eq!(y.abs(), -y);
1746 ///
1747 /// assert!(f64::NAN.abs().is_nan());
1748 /// ```
1749 #[must_use = "method returns a new number and does not mutate the original value"]
1750 #[stable(feature = "rust1", since = "1.0.0")]
1751 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1752 #[inline]
1753 #[ferrocene::prevalidated]
1754 pub const fn abs(self) -> f64 {
1755 intrinsics::fabs(self)
1756 }
1757
1758 /// Returns a number that represents the sign of `self`.
1759 ///
1760 /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
1761 /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
1762 /// - NaN if the number is NaN
1763 ///
1764 /// # Examples
1765 ///
1766 /// ```
1767 /// let f = 3.5_f64;
1768 ///
1769 /// assert_eq!(f.signum(), 1.0);
1770 /// assert_eq!(f64::NEG_INFINITY.signum(), -1.0);
1771 ///
1772 /// assert!(f64::NAN.signum().is_nan());
1773 /// ```
1774 #[must_use = "method returns a new number and does not mutate the original value"]
1775 #[stable(feature = "rust1", since = "1.0.0")]
1776 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1777 #[inline]
1778 pub const fn signum(self) -> f64 {
1779 if self.is_nan() { Self::NAN } else { 1.0_f64.copysign(self) }
1780 }
1781
1782 /// Returns a number composed of the magnitude of `self` and the sign of
1783 /// `sign`.
1784 ///
1785 /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`.
1786 /// If `self` is a NaN, then a NaN with the same payload as `self` and the sign bit of `sign` is
1787 /// returned.
1788 ///
1789 /// If `sign` is a NaN, then this operation will still carry over its sign into the result. Note
1790 /// that IEEE 754 doesn't assign any meaning to the sign bit in case of a NaN, and as Rust
1791 /// doesn't guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the
1792 /// result of `copysign` with `sign` being a NaN might produce an unexpected or non-portable
1793 /// result. See the [specification of NaN bit patterns](primitive@f32#nan-bit-patterns) for more
1794 /// info.
1795 ///
1796 /// # Examples
1797 ///
1798 /// ```
1799 /// let f = 3.5_f64;
1800 ///
1801 /// assert_eq!(f.copysign(0.42), 3.5_f64);
1802 /// assert_eq!(f.copysign(-0.42), -3.5_f64);
1803 /// assert_eq!((-f).copysign(0.42), 3.5_f64);
1804 /// assert_eq!((-f).copysign(-0.42), -3.5_f64);
1805 ///
1806 /// assert!(f64::NAN.copysign(1.0).is_nan());
1807 /// ```
1808 #[must_use = "method returns a new number and does not mutate the original value"]
1809 #[stable(feature = "copysign", since = "1.35.0")]
1810 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1811 #[inline]
1812 #[ferrocene::prevalidated]
1813 pub const fn copysign(self, sign: f64) -> f64 {
1814 intrinsics::copysignf64(self, sign)
1815 }
1816
1817 /// Float addition that allows optimizations based on algebraic rules.
1818 ///
1819 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1820 #[must_use = "method returns a new number and does not mutate the original value"]
1821 #[stable(feature = "float_algebraic", since = "1.98.0")]
1822 #[rustc_const_stable(feature = "float_algebraic", since = "1.98.0")]
1823 #[inline]
1824 pub const fn algebraic_add(self, rhs: f64) -> f64 {
1825 intrinsics::fadd_algebraic(self, rhs)
1826 }
1827
1828 /// Float subtraction that allows optimizations based on algebraic rules.
1829 ///
1830 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1831 #[must_use = "method returns a new number and does not mutate the original value"]
1832 #[stable(feature = "float_algebraic", since = "1.98.0")]
1833 #[rustc_const_stable(feature = "float_algebraic", since = "1.98.0")]
1834 #[inline]
1835 pub const fn algebraic_sub(self, rhs: f64) -> f64 {
1836 intrinsics::fsub_algebraic(self, rhs)
1837 }
1838
1839 /// Float multiplication that allows optimizations based on algebraic rules.
1840 ///
1841 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1842 #[must_use = "method returns a new number and does not mutate the original value"]
1843 #[stable(feature = "float_algebraic", since = "1.98.0")]
1844 #[rustc_const_stable(feature = "float_algebraic", since = "1.98.0")]
1845 #[inline]
1846 pub const fn algebraic_mul(self, rhs: f64) -> f64 {
1847 intrinsics::fmul_algebraic(self, rhs)
1848 }
1849
1850 /// Float division that allows optimizations based on algebraic rules.
1851 ///
1852 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1853 #[must_use = "method returns a new number and does not mutate the original value"]
1854 #[stable(feature = "float_algebraic", since = "1.98.0")]
1855 #[rustc_const_stable(feature = "float_algebraic", since = "1.98.0")]
1856 #[inline]
1857 pub const fn algebraic_div(self, rhs: f64) -> f64 {
1858 intrinsics::fdiv_algebraic(self, rhs)
1859 }
1860
1861 /// Float remainder that allows optimizations based on algebraic rules.
1862 ///
1863 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1864 #[must_use = "method returns a new number and does not mutate the original value"]
1865 #[stable(feature = "float_algebraic", since = "1.98.0")]
1866 #[rustc_const_stable(feature = "float_algebraic", since = "1.98.0")]
1867 #[inline]
1868 pub const fn algebraic_rem(self, rhs: f64) -> f64 {
1869 intrinsics::frem_algebraic(self, rhs)
1870 }
1871
1872 /// Returns `self` if the value is not NaN, otherwise returns `replacement`
1873 /// if `self` is NaN.
1874 ///
1875 /// # Examples
1876 ///
1877 /// ```
1878 /// #![feature(float_nan_to)]
1879 ///
1880 /// let n = f64::NAN;
1881 /// let x = 2.0f64;
1882 /// let y = f64::INFINITY;
1883 ///
1884 /// assert_eq!(n.nan_to(0.0f64), 0.0f64);
1885 /// assert_eq!(x.nan_to(0.0f64), 2.0f64);
1886 /// assert_eq!(y.nan_to(0.0f64), f64::INFINITY);
1887 /// ```
1888 #[must_use = "method returns a new float and does not mutate the original value"]
1889 #[unstable(feature = "float_nan_to", issue = "161248")]
1890 #[rustc_const_unstable(feature = "float_nan_to", issue = "161248")]
1891 #[inline]
1892 pub const fn nan_to(self, replacement: f64) -> f64 {
1893 if self.is_nan() { replacement } else { self }
1894 }
1895}
1896
1897#[unstable(feature = "core_float_math", issue = "137578")]
1898/// Experimental implementations of floating point functions in `core`.
1899///
1900/// _The standalone functions in this module are for testing only.
1901/// They will be stabilized as inherent methods._
1902pub mod math {
1903 use crate::intrinsics;
1904 use crate::num::imp::libm;
1905
1906 /// Experimental version of `floor` in `core`. See [`f64::floor`] for details.
1907 ///
1908 /// # Examples
1909 ///
1910 /// ```
1911 /// #![feature(core_float_math)]
1912 ///
1913 /// use core::f64;
1914 ///
1915 /// let f = 3.7_f64;
1916 /// let g = 3.0_f64;
1917 /// let h = -3.7_f64;
1918 ///
1919 /// assert_eq!(f64::math::floor(f), 3.0);
1920 /// assert_eq!(f64::math::floor(g), 3.0);
1921 /// assert_eq!(f64::math::floor(h), -4.0);
1922 /// ```
1923 ///
1924 /// _This standalone function is for testing only.
1925 /// It will be stabilized as an inherent method._
1926 ///
1927 /// [`f64::floor`]: ../../../std/primitive.f64.html#method.floor
1928 #[inline]
1929 #[unstable(feature = "core_float_math", issue = "137578")]
1930 #[must_use = "method returns a new number and does not mutate the original value"]
1931 pub const fn floor(x: f64) -> f64 {
1932 intrinsics::floorf64(x)
1933 }
1934
1935 /// Experimental version of `ceil` in `core`. See [`f64::ceil`] for details.
1936 ///
1937 /// # Examples
1938 ///
1939 /// ```
1940 /// #![feature(core_float_math)]
1941 ///
1942 /// use core::f64;
1943 ///
1944 /// let f = 3.01_f64;
1945 /// let g = 4.0_f64;
1946 ///
1947 /// assert_eq!(f64::math::ceil(f), 4.0);
1948 /// assert_eq!(f64::math::ceil(g), 4.0);
1949 /// ```
1950 ///
1951 /// _This standalone function is for testing only.
1952 /// It will be stabilized as an inherent method._
1953 ///
1954 /// [`f64::ceil`]: ../../../std/primitive.f64.html#method.ceil
1955 #[inline]
1956 #[doc(alias = "ceiling")]
1957 #[unstable(feature = "core_float_math", issue = "137578")]
1958 #[must_use = "method returns a new number and does not mutate the original value"]
1959 pub const fn ceil(x: f64) -> f64 {
1960 intrinsics::ceilf64(x)
1961 }
1962
1963 /// Experimental version of `round` in `core`. See [`f64::round`] for details.
1964 ///
1965 /// # Examples
1966 ///
1967 /// ```
1968 /// #![feature(core_float_math)]
1969 ///
1970 /// use core::f64;
1971 ///
1972 /// let f = 3.3_f64;
1973 /// let g = -3.3_f64;
1974 /// let h = -3.7_f64;
1975 /// let i = 3.5_f64;
1976 /// let j = 4.5_f64;
1977 ///
1978 /// assert_eq!(f64::math::round(f), 3.0);
1979 /// assert_eq!(f64::math::round(g), -3.0);
1980 /// assert_eq!(f64::math::round(h), -4.0);
1981 /// assert_eq!(f64::math::round(i), 4.0);
1982 /// assert_eq!(f64::math::round(j), 5.0);
1983 /// ```
1984 ///
1985 /// _This standalone function is for testing only.
1986 /// It will be stabilized as an inherent method._
1987 ///
1988 /// [`f64::round`]: ../../../std/primitive.f64.html#method.round
1989 #[inline]
1990 #[unstable(feature = "core_float_math", issue = "137578")]
1991 #[must_use = "method returns a new number and does not mutate the original value"]
1992 pub const fn round(x: f64) -> f64 {
1993 intrinsics::roundf64(x)
1994 }
1995
1996 /// Experimental version of `round_ties_even` in `core`. See [`f64::round_ties_even`] for
1997 /// details.
1998 ///
1999 /// # Examples
2000 ///
2001 /// ```
2002 /// #![feature(core_float_math)]
2003 ///
2004 /// use core::f64;
2005 ///
2006 /// let f = 3.3_f64;
2007 /// let g = -3.3_f64;
2008 /// let h = 3.5_f64;
2009 /// let i = 4.5_f64;
2010 ///
2011 /// assert_eq!(f64::math::round_ties_even(f), 3.0);
2012 /// assert_eq!(f64::math::round_ties_even(g), -3.0);
2013 /// assert_eq!(f64::math::round_ties_even(h), 4.0);
2014 /// assert_eq!(f64::math::round_ties_even(i), 4.0);
2015 /// ```
2016 ///
2017 /// _This standalone function is for testing only.
2018 /// It will be stabilized as an inherent method._
2019 ///
2020 /// [`f64::round_ties_even`]: ../../../std/primitive.f64.html#method.round_ties_even
2021 #[inline]
2022 #[unstable(feature = "core_float_math", issue = "137578")]
2023 #[must_use = "method returns a new number and does not mutate the original value"]
2024 pub const fn round_ties_even(x: f64) -> f64 {
2025 intrinsics::round_ties_even_f64(x)
2026 }
2027
2028 /// Experimental version of `trunc` in `core`. See [`f64::trunc`] for details.
2029 ///
2030 /// # Examples
2031 ///
2032 /// ```
2033 /// #![feature(core_float_math)]
2034 ///
2035 /// use core::f64;
2036 ///
2037 /// let f = 3.7_f64;
2038 /// let g = 3.0_f64;
2039 /// let h = -3.7_f64;
2040 ///
2041 /// assert_eq!(f64::math::trunc(f), 3.0);
2042 /// assert_eq!(f64::math::trunc(g), 3.0);
2043 /// assert_eq!(f64::math::trunc(h), -3.0);
2044 /// ```
2045 ///
2046 /// _This standalone function is for testing only.
2047 /// It will be stabilized as an inherent method._
2048 ///
2049 /// [`f64::trunc`]: ../../../std/primitive.f64.html#method.trunc
2050 #[inline]
2051 #[doc(alias = "truncate")]
2052 #[unstable(feature = "core_float_math", issue = "137578")]
2053 #[must_use = "method returns a new number and does not mutate the original value"]
2054 pub const fn trunc(x: f64) -> f64 {
2055 intrinsics::truncf64(x)
2056 }
2057
2058 /// Experimental version of `fract` in `core`. See [`f64::fract`] for details.
2059 ///
2060 /// # Examples
2061 ///
2062 /// ```
2063 /// #![feature(core_float_math)]
2064 ///
2065 /// use core::f64;
2066 ///
2067 /// let x = 3.6_f64;
2068 /// let y = -3.6_f64;
2069 /// let abs_difference_x = (f64::math::fract(x) - 0.6).abs();
2070 /// let abs_difference_y = (f64::math::fract(y) - (-0.6)).abs();
2071 ///
2072 /// assert!(abs_difference_x < 1e-10);
2073 /// assert!(abs_difference_y < 1e-10);
2074 /// ```
2075 ///
2076 /// _This standalone function is for testing only.
2077 /// It will be stabilized as an inherent method._
2078 ///
2079 /// [`f64::fract`]: ../../../std/primitive.f64.html#method.fract
2080 #[inline]
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 fract(x: f64) -> f64 {
2084 x - trunc(x)
2085 }
2086
2087 /// Experimental version of `mul_add` in `core`. See [`f64::mul_add`] for details.
2088 ///
2089 /// # Examples
2090 ///
2091 /// ```
2092 /// # #![allow(unused_features)]
2093 /// #![feature(core_float_math)]
2094 ///
2095 /// # // FIXME(#140515): mingw has an incorrect fma
2096 /// # // https://sourceforge.net/p/mingw-w64/bugs/848/
2097 /// # #[cfg(all(target_os = "windows", target_env = "gnu", not(target_abi = "llvm")))] {
2098 /// use core::f64;
2099 ///
2100 /// let m = 10.0_f64;
2101 /// let x = 4.0_f64;
2102 /// let b = 60.0_f64;
2103 ///
2104 /// assert_eq!(f64::math::mul_add(m, x, b), 100.0);
2105 /// assert_eq!(m * x + b, 100.0);
2106 ///
2107 /// let one_plus_eps = 1.0_f64 + f64::EPSILON;
2108 /// let one_minus_eps = 1.0_f64 - f64::EPSILON;
2109 /// let minus_one = -1.0_f64;
2110 ///
2111 /// // The exact result (1 + eps) * (1 - eps) = 1 - eps * eps.
2112 /// assert_eq!(
2113 /// f64::math::mul_add(one_plus_eps, one_minus_eps, minus_one),
2114 /// -f64::EPSILON * f64::EPSILON
2115 /// );
2116 /// // Different rounding with the non-fused multiply and add.
2117 /// assert_eq!(one_plus_eps * one_minus_eps + minus_one, 0.0);
2118 /// # }
2119 /// ```
2120 ///
2121 /// _This standalone function is for testing only.
2122 /// It will be stabilized as an inherent method._
2123 ///
2124 /// [`f64::mul_add`]: ../../../std/primitive.f64.html#method.mul_add
2125 #[inline]
2126 #[doc(alias = "fma", alias = "fusedMultiplyAdd")]
2127 #[unstable(feature = "core_float_math", issue = "137578")]
2128 #[must_use = "method returns a new number and does not mutate the original value"]
2129 pub const fn mul_add(x: f64, a: f64, b: f64) -> f64 {
2130 intrinsics::fmaf64(x, a, b)
2131 }
2132
2133 /// Experimental version of `div_euclid` in `core`. See [`f64::div_euclid`] for details.
2134 ///
2135 /// # Examples
2136 ///
2137 /// ```
2138 /// #![feature(core_float_math)]
2139 ///
2140 /// use core::f64;
2141 ///
2142 /// let a: f64 = 7.0;
2143 /// let b = 4.0;
2144 /// assert_eq!(f64::math::div_euclid(a, b), 1.0); // 7.0 > 4.0 * 1.0
2145 /// assert_eq!(f64::math::div_euclid(-a, b), -2.0); // -7.0 >= 4.0 * -2.0
2146 /// assert_eq!(f64::math::div_euclid(a, -b), -1.0); // 7.0 >= -4.0 * -1.0
2147 /// assert_eq!(f64::math::div_euclid(-a, -b), 2.0); // -7.0 >= -4.0 * 2.0
2148 /// ```
2149 ///
2150 /// _This standalone function is for testing only.
2151 /// It will be stabilized as an inherent method._
2152 ///
2153 /// [`f64::div_euclid`]: ../../../std/primitive.f64.html#method.div_euclid
2154 #[inline]
2155 #[unstable(feature = "core_float_math", issue = "137578")]
2156 #[must_use = "method returns a new number and does not mutate the original value"]
2157 pub fn div_euclid(x: f64, rhs: f64) -> f64 {
2158 let q = trunc(x / rhs);
2159 if x % rhs < 0.0 {
2160 return if rhs > 0.0 { q - 1.0 } else { q + 1.0 };
2161 }
2162 q
2163 }
2164
2165 /// Experimental version of `rem_euclid` in `core`. See [`f64::rem_euclid`] for details.
2166 ///
2167 /// # Examples
2168 ///
2169 /// ```
2170 /// #![feature(core_float_math)]
2171 ///
2172 /// use core::f64;
2173 ///
2174 /// let a: f64 = 7.0;
2175 /// let b = 4.0;
2176 /// assert_eq!(f64::math::rem_euclid(a, b), 3.0);
2177 /// assert_eq!(f64::math::rem_euclid(-a, b), 1.0);
2178 /// assert_eq!(f64::math::rem_euclid(a, -b), 3.0);
2179 /// assert_eq!(f64::math::rem_euclid(-a, -b), 1.0);
2180 /// // limitation due to round-off error
2181 /// assert!(f64::math::rem_euclid(-f64::EPSILON, 3.0) != 0.0);
2182 /// ```
2183 ///
2184 /// _This standalone function is for testing only.
2185 /// It will be stabilized as an inherent method._
2186 ///
2187 /// [`f64::rem_euclid`]: ../../../std/primitive.f64.html#method.rem_euclid
2188 #[inline]
2189 #[doc(alias = "modulo", alias = "mod")]
2190 #[unstable(feature = "core_float_math", issue = "137578")]
2191 #[must_use = "method returns a new number and does not mutate the original value"]
2192 pub fn rem_euclid(x: f64, rhs: f64) -> f64 {
2193 let r = x % rhs;
2194 if r < 0.0 { r + rhs.abs() } else { r }
2195 }
2196
2197 /// Experimental version of `powi` in `core`. See [`f64::powi`] for details.
2198 ///
2199 /// # Examples
2200 ///
2201 /// ```
2202 /// #![feature(core_float_math)]
2203 ///
2204 /// use core::f64;
2205 ///
2206 /// let x = 2.0_f64;
2207 /// let abs_difference = (f64::math::powi(x, 2) - (x * x)).abs();
2208 /// assert!(abs_difference <= 1e-6);
2209 ///
2210 /// assert_eq!(f64::math::powi(f64::NAN, 0), 1.0);
2211 /// ```
2212 ///
2213 /// _This standalone function is for testing only.
2214 /// It will be stabilized as an inherent method._
2215 ///
2216 /// [`f64::powi`]: ../../../std/primitive.f64.html#method.powi
2217 #[inline]
2218 #[unstable(feature = "core_float_math", issue = "137578")]
2219 #[must_use = "method returns a new number and does not mutate the original value"]
2220 pub fn powi(x: f64, n: i32) -> f64 {
2221 intrinsics::powif64(x, n)
2222 }
2223
2224 /// Experimental version of `sqrt` in `core`. See [`f64::sqrt`] for details.
2225 ///
2226 /// # Examples
2227 ///
2228 /// ```
2229 /// #![feature(core_float_math)]
2230 ///
2231 /// use core::f64;
2232 ///
2233 /// let positive = 4.0_f64;
2234 /// let negative = -4.0_f64;
2235 /// let negative_zero = -0.0_f64;
2236 ///
2237 /// assert_eq!(f64::math::sqrt(positive), 2.0);
2238 /// assert!(f64::math::sqrt(negative).is_nan());
2239 /// assert_eq!(f64::math::sqrt(negative_zero), negative_zero);
2240 /// ```
2241 ///
2242 /// _This standalone function is for testing only.
2243 /// It will be stabilized as an inherent method._
2244 ///
2245 /// [`f64::sqrt`]: ../../../std/primitive.f64.html#method.sqrt
2246 #[inline]
2247 #[doc(alias = "squareRoot")]
2248 #[unstable(feature = "core_float_math", issue = "137578")]
2249 #[must_use = "method returns a new number and does not mutate the original value"]
2250 pub fn sqrt(x: f64) -> f64 {
2251 intrinsics::sqrtf64(x)
2252 }
2253
2254 /// Experimental version of `abs_sub` in `core`. See [`f64::abs_sub`] for details.
2255 ///
2256 /// # Examples
2257 ///
2258 /// ```
2259 /// #![feature(core_float_math)]
2260 ///
2261 /// use core::f64;
2262 ///
2263 /// let x = 3.0_f64;
2264 /// let y = -3.0_f64;
2265 ///
2266 /// let abs_difference_x = (f64::math::abs_sub(x, 1.0) - 2.0).abs();
2267 /// let abs_difference_y = (f64::math::abs_sub(y, 1.0) - 0.0).abs();
2268 ///
2269 /// assert!(abs_difference_x < 1e-10);
2270 /// assert!(abs_difference_y < 1e-10);
2271 /// ```
2272 ///
2273 /// _This standalone function is for testing only.
2274 /// It will be stabilized as an inherent method._
2275 ///
2276 /// [`f64::abs_sub`]: ../../../std/primitive.f64.html#method.abs_sub
2277 #[inline]
2278 #[unstable(feature = "core_float_math", issue = "137578")]
2279 #[deprecated(
2280 since = "1.10.0",
2281 note = "you probably meant `(self - other).abs()`: \
2282 this operation is `(self - other).max(0.0)` \
2283 except that `abs_sub` also propagates NaNs (also \
2284 known as `fdim` in C). If you truly need the positive \
2285 difference, consider using that expression or the C function \
2286 `fdim`, depending on how you wish to handle NaN (please consider \
2287 filing an issue describing your use-case too)."
2288 )]
2289 #[must_use = "method returns a new number and does not mutate the original value"]
2290 pub fn abs_sub(x: f64, other: f64) -> f64 {
2291 libm::fdim(x, other)
2292 }
2293
2294 /// Experimental version of `cbrt` in `core`. See [`f64::cbrt`] for details.
2295 ///
2296 /// # Examples
2297 ///
2298 /// ```
2299 /// #![feature(core_float_math)]
2300 ///
2301 /// use core::f64;
2302 ///
2303 /// let x = 8.0_f64;
2304 ///
2305 /// // x^(1/3) - 2 == 0
2306 /// let abs_difference = (f64::math::cbrt(x) - 2.0).abs();
2307 ///
2308 /// assert!(abs_difference < 1e-10);
2309 /// ```
2310 ///
2311 /// _This standalone function is for testing only.
2312 /// It will be stabilized as an inherent method._
2313 ///
2314 /// [`f64::cbrt`]: ../../../std/primitive.f64.html#method.cbrt
2315 #[inline]
2316 #[unstable(feature = "core_float_math", issue = "137578")]
2317 #[must_use = "method returns a new number and does not mutate the original value"]
2318 pub fn cbrt(x: f64) -> f64 {
2319 libm::cbrt(x)
2320 }
2321}