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