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