]> git.lizzy.rs Git - rust.git/blob - src/libcore/num/f64.rs
4a2a35dfb099928ef79a262b8e3b1f779eea845e
[rust.git] / src / libcore / num / f64.rs
1 //! This module provides constants which are specific to the implementation
2 //! of the `f64` floating point data type.
3 //!
4 //! *[See also the `f64` primitive type](../../std/primitive.f64.html).*
5 //!
6 //! Mathematically significant numbers are provided in the `consts` sub-module.
7
8 #![stable(feature = "rust1", since = "1.0.0")]
9
10 #[cfg(not(test))]
11 use crate::intrinsics;
12
13 use crate::mem;
14 use crate::num::FpCategory;
15
16 /// The radix or base of the internal representation of `f64`.
17 #[stable(feature = "rust1", since = "1.0.0")]
18 pub const RADIX: u32 = 2;
19
20 /// Number of significant digits in base 2.
21 #[stable(feature = "rust1", since = "1.0.0")]
22 pub const MANTISSA_DIGITS: u32 = 53;
23 /// Approximate number of significant digits in base 10.
24 #[stable(feature = "rust1", since = "1.0.0")]
25 pub const DIGITS: u32 = 15;
26
27 /// [Machine epsilon] value for `f64`.
28 ///
29 /// This is the difference between `1.0` and the next largest representable number.
30 ///
31 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
32 #[stable(feature = "rust1", since = "1.0.0")]
33 pub const EPSILON: f64 = 2.2204460492503131e-16_f64;
34
35 /// Smallest finite `f64` value.
36 #[stable(feature = "rust1", since = "1.0.0")]
37 pub const MIN: f64 = -1.7976931348623157e+308_f64;
38 /// Smallest positive normal `f64` value.
39 #[stable(feature = "rust1", since = "1.0.0")]
40 pub const MIN_POSITIVE: f64 = 2.2250738585072014e-308_f64;
41 /// Largest finite `f64` value.
42 #[stable(feature = "rust1", since = "1.0.0")]
43 pub const MAX: f64 = 1.7976931348623157e+308_f64;
44
45 /// One greater than the minimum possible normal power of 2 exponent.
46 #[stable(feature = "rust1", since = "1.0.0")]
47 pub const MIN_EXP: i32 = -1021;
48 /// Maximum possible power of 2 exponent.
49 #[stable(feature = "rust1", since = "1.0.0")]
50 pub const MAX_EXP: i32 = 1024;
51
52 /// Minimum possible normal power of 10 exponent.
53 #[stable(feature = "rust1", since = "1.0.0")]
54 pub const MIN_10_EXP: i32 = -307;
55 /// Maximum possible power of 10 exponent.
56 #[stable(feature = "rust1", since = "1.0.0")]
57 pub const MAX_10_EXP: i32 = 308;
58
59 /// Not a Number (NaN).
60 #[stable(feature = "rust1", since = "1.0.0")]
61 pub const NAN: f64 = 0.0_f64 / 0.0_f64;
62 /// Infinity (∞).
63 #[stable(feature = "rust1", since = "1.0.0")]
64 pub const INFINITY: f64 = 1.0_f64 / 0.0_f64;
65 /// Negative infinity (-∞).
66 #[stable(feature = "rust1", since = "1.0.0")]
67 pub const NEG_INFINITY: f64 = -1.0_f64 / 0.0_f64;
68
69 /// Basic mathematical constants.
70 #[stable(feature = "rust1", since = "1.0.0")]
71 pub mod consts {
72     // FIXME: replace with mathematical constants from cmath.
73
74     /// Archimedes' constant (π)
75     #[stable(feature = "rust1", since = "1.0.0")]
76     pub const PI: f64 = 3.14159265358979323846264338327950288_f64;
77
78     /// π/2
79     #[stable(feature = "rust1", since = "1.0.0")]
80     pub const FRAC_PI_2: f64 = 1.57079632679489661923132169163975144_f64;
81
82     /// π/3
83     #[stable(feature = "rust1", since = "1.0.0")]
84     pub const FRAC_PI_3: f64 = 1.04719755119659774615421446109316763_f64;
85
86     /// π/4
87     #[stable(feature = "rust1", since = "1.0.0")]
88     pub const FRAC_PI_4: f64 = 0.785398163397448309615660845819875721_f64;
89
90     /// π/6
91     #[stable(feature = "rust1", since = "1.0.0")]
92     pub const FRAC_PI_6: f64 = 0.52359877559829887307710723054658381_f64;
93
94     /// π/8
95     #[stable(feature = "rust1", since = "1.0.0")]
96     pub const FRAC_PI_8: f64 = 0.39269908169872415480783042290993786_f64;
97
98     /// 1/π
99     #[stable(feature = "rust1", since = "1.0.0")]
100     pub const FRAC_1_PI: f64 = 0.318309886183790671537767526745028724_f64;
101
102     /// 2/π
103     #[stable(feature = "rust1", since = "1.0.0")]
104     pub const FRAC_2_PI: f64 = 0.636619772367581343075535053490057448_f64;
105
106     /// 2/sqrt(π)
107     #[stable(feature = "rust1", since = "1.0.0")]
108     pub const FRAC_2_SQRT_PI: f64 = 1.12837916709551257389615890312154517_f64;
109
110     /// sqrt(2)
111     #[stable(feature = "rust1", since = "1.0.0")]
112     pub const SQRT_2: f64 = 1.41421356237309504880168872420969808_f64;
113
114     /// 1/sqrt(2)
115     #[stable(feature = "rust1", since = "1.0.0")]
116     pub const FRAC_1_SQRT_2: f64 = 0.707106781186547524400844362104849039_f64;
117
118     /// Euler's number (e)
119     #[stable(feature = "rust1", since = "1.0.0")]
120     pub const E: f64 = 2.71828182845904523536028747135266250_f64;
121
122     /// log<sub>2</sub>(10)
123     #[unstable(feature = "extra_log_consts", issue = "50540")]
124     pub const LOG2_10: f64 = 3.32192809488736234787031942948939018_f64;
125
126     /// log<sub>2</sub>(e)
127     #[stable(feature = "rust1", since = "1.0.0")]
128     pub const LOG2_E: f64 = 1.44269504088896340735992468100189214_f64;
129
130     /// log<sub>10</sub>(2)
131     #[unstable(feature = "extra_log_consts", issue = "50540")]
132     pub const LOG10_2: f64 = 0.301029995663981195213738894724493027_f64;
133
134     /// log<sub>10</sub>(e)
135     #[stable(feature = "rust1", since = "1.0.0")]
136     pub const LOG10_E: f64 = 0.434294481903251827651128918916605082_f64;
137
138     /// ln(2)
139     #[stable(feature = "rust1", since = "1.0.0")]
140     pub const LN_2: f64 = 0.693147180559945309417232121458176568_f64;
141
142     /// ln(10)
143     #[stable(feature = "rust1", since = "1.0.0")]
144     pub const LN_10: f64 = 2.30258509299404568401799145468436421_f64;
145 }
146
147 #[lang = "f64"]
148 #[cfg(not(test))]
149 impl f64 {
150     /// Returns `true` if this value is `NaN`.
151     ///
152     /// ```
153     /// use std::f64;
154     ///
155     /// let nan = f64::NAN;
156     /// let f = 7.0_f64;
157     ///
158     /// assert!(nan.is_nan());
159     /// assert!(!f.is_nan());
160     /// ```
161     #[stable(feature = "rust1", since = "1.0.0")]
162     #[inline]
163     pub fn is_nan(self) -> bool {
164         self != self
165     }
166
167     // FIXME(#50145): `abs` is publicly unavailable in libcore due to
168     // concerns about portability, so this implementation is for
169     // private use internally.
170     #[inline]
171     fn abs_private(self) -> f64 {
172         f64::from_bits(self.to_bits() & 0x7fff_ffff_ffff_ffff)
173     }
174
175     /// Returns `true` if this value is positive infinity or negative infinity, and
176     /// `false` otherwise.
177     ///
178     /// ```
179     /// use std::f64;
180     ///
181     /// let f = 7.0f64;
182     /// let inf = f64::INFINITY;
183     /// let neg_inf = f64::NEG_INFINITY;
184     /// let nan = f64::NAN;
185     ///
186     /// assert!(!f.is_infinite());
187     /// assert!(!nan.is_infinite());
188     ///
189     /// assert!(inf.is_infinite());
190     /// assert!(neg_inf.is_infinite());
191     /// ```
192     #[stable(feature = "rust1", since = "1.0.0")]
193     #[inline]
194     pub fn is_infinite(self) -> bool {
195         self.abs_private() == INFINITY
196     }
197
198     /// Returns `true` if this number is neither infinite nor `NaN`.
199     ///
200     /// ```
201     /// use std::f64;
202     ///
203     /// let f = 7.0f64;
204     /// let inf: f64 = f64::INFINITY;
205     /// let neg_inf: f64 = f64::NEG_INFINITY;
206     /// let nan: f64 = f64::NAN;
207     ///
208     /// assert!(f.is_finite());
209     ///
210     /// assert!(!nan.is_finite());
211     /// assert!(!inf.is_finite());
212     /// assert!(!neg_inf.is_finite());
213     /// ```
214     #[stable(feature = "rust1", since = "1.0.0")]
215     #[inline]
216     pub fn is_finite(self) -> bool {
217         // There's no need to handle NaN separately: if self is NaN,
218         // the comparison is not true, exactly as desired.
219         self.abs_private() < INFINITY
220     }
221
222     /// Returns `true` if the number is neither zero, infinite,
223     /// [subnormal][subnormal], or `NaN`.
224     ///
225     /// ```
226     /// use std::f64;
227     ///
228     /// let min = f64::MIN_POSITIVE; // 2.2250738585072014e-308f64
229     /// let max = f64::MAX;
230     /// let lower_than_min = 1.0e-308_f64;
231     /// let zero = 0.0f64;
232     ///
233     /// assert!(min.is_normal());
234     /// assert!(max.is_normal());
235     ///
236     /// assert!(!zero.is_normal());
237     /// assert!(!f64::NAN.is_normal());
238     /// assert!(!f64::INFINITY.is_normal());
239     /// // Values between `0` and `min` are Subnormal.
240     /// assert!(!lower_than_min.is_normal());
241     /// ```
242     /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
243     #[stable(feature = "rust1", since = "1.0.0")]
244     #[inline]
245     pub fn is_normal(self) -> bool {
246         self.classify() == FpCategory::Normal
247     }
248
249     /// Returns the floating point category of the number. If only one property
250     /// is going to be tested, it is generally faster to use the specific
251     /// predicate instead.
252     ///
253     /// ```
254     /// use std::num::FpCategory;
255     /// use std::f64;
256     ///
257     /// let num = 12.4_f64;
258     /// let inf = f64::INFINITY;
259     ///
260     /// assert_eq!(num.classify(), FpCategory::Normal);
261     /// assert_eq!(inf.classify(), FpCategory::Infinite);
262     /// ```
263     #[stable(feature = "rust1", since = "1.0.0")]
264     pub fn classify(self) -> FpCategory {
265         const EXP_MASK: u64 = 0x7ff0000000000000;
266         const MAN_MASK: u64 = 0x000fffffffffffff;
267
268         let bits = self.to_bits();
269         match (bits & MAN_MASK, bits & EXP_MASK) {
270             (0, 0) => FpCategory::Zero,
271             (_, 0) => FpCategory::Subnormal,
272             (0, EXP_MASK) => FpCategory::Infinite,
273             (_, EXP_MASK) => FpCategory::Nan,
274             _ => FpCategory::Normal,
275         }
276     }
277
278     /// Returns `true` if `self` has a positive sign, including `+0.0`, `NaN`s with
279     /// positive sign bit and positive infinity.
280     ///
281     /// ```
282     /// let f = 7.0_f64;
283     /// let g = -7.0_f64;
284     ///
285     /// assert!(f.is_sign_positive());
286     /// assert!(!g.is_sign_positive());
287     /// ```
288     #[stable(feature = "rust1", since = "1.0.0")]
289     #[inline]
290     pub fn is_sign_positive(self) -> bool {
291         !self.is_sign_negative()
292     }
293
294     #[stable(feature = "rust1", since = "1.0.0")]
295     #[rustc_deprecated(since = "1.0.0", reason = "renamed to is_sign_positive")]
296     #[inline]
297     #[doc(hidden)]
298     pub fn is_positive(self) -> bool {
299         self.is_sign_positive()
300     }
301
302     /// Returns `true` if `self` has a negative sign, including `-0.0`, `NaN`s with
303     /// negative sign bit and negative infinity.
304     ///
305     /// ```
306     /// let f = 7.0_f64;
307     /// let g = -7.0_f64;
308     ///
309     /// assert!(!f.is_sign_negative());
310     /// assert!(g.is_sign_negative());
311     /// ```
312     #[stable(feature = "rust1", since = "1.0.0")]
313     #[inline]
314     pub fn is_sign_negative(self) -> bool {
315         self.to_bits() & 0x8000_0000_0000_0000 != 0
316     }
317
318     #[stable(feature = "rust1", since = "1.0.0")]
319     #[rustc_deprecated(since = "1.0.0", reason = "renamed to is_sign_negative")]
320     #[inline]
321     #[doc(hidden)]
322     pub fn is_negative(self) -> bool {
323         self.is_sign_negative()
324     }
325
326     /// Takes the reciprocal (inverse) of a number, `1/x`.
327     ///
328     /// ```
329     /// let x = 2.0_f64;
330     /// let abs_difference = (x.recip() - (1.0 / x)).abs();
331     ///
332     /// assert!(abs_difference < 1e-10);
333     /// ```
334     #[stable(feature = "rust1", since = "1.0.0")]
335     #[inline]
336     pub fn recip(self) -> f64 {
337         1.0 / self
338     }
339
340     /// Converts radians to degrees.
341     ///
342     /// ```
343     /// use std::f64::consts;
344     ///
345     /// let angle = consts::PI;
346     ///
347     /// let abs_difference = (angle.to_degrees() - 180.0).abs();
348     ///
349     /// assert!(abs_difference < 1e-10);
350     /// ```
351     #[stable(feature = "rust1", since = "1.0.0")]
352     #[inline]
353     pub fn to_degrees(self) -> f64 {
354         // The division here is correctly rounded with respect to the true
355         // value of 180/π. (This differs from f32, where a constant must be
356         // used to ensure a correctly rounded result.)
357         self * (180.0f64 / consts::PI)
358     }
359
360     /// Converts degrees to radians.
361     ///
362     /// ```
363     /// use std::f64::consts;
364     ///
365     /// let angle = 180.0_f64;
366     ///
367     /// let abs_difference = (angle.to_radians() - consts::PI).abs();
368     ///
369     /// assert!(abs_difference < 1e-10);
370     /// ```
371     #[stable(feature = "rust1", since = "1.0.0")]
372     #[inline]
373     pub fn to_radians(self) -> f64 {
374         let value: f64 = consts::PI;
375         self * (value / 180.0)
376     }
377
378     /// Returns the maximum of the two numbers.
379     ///
380     /// ```
381     /// let x = 1.0_f64;
382     /// let y = 2.0_f64;
383     ///
384     /// assert_eq!(x.max(y), y);
385     /// ```
386     ///
387     /// If one of the arguments is NaN, then the other argument is returned.
388     #[stable(feature = "rust1", since = "1.0.0")]
389     #[inline]
390     pub fn max(self, other: f64) -> f64 {
391         intrinsics::maxnumf64(self, other)
392     }
393
394     /// Returns the minimum of the two numbers.
395     ///
396     /// ```
397     /// let x = 1.0_f64;
398     /// let y = 2.0_f64;
399     ///
400     /// assert_eq!(x.min(y), x);
401     /// ```
402     ///
403     /// If one of the arguments is NaN, then the other argument is returned.
404     #[stable(feature = "rust1", since = "1.0.0")]
405     #[inline]
406     pub fn min(self, other: f64) -> f64 {
407         intrinsics::minnumf64(self, other)
408     }
409
410     /// Raw transmutation to `u64`.
411     ///
412     /// This is currently identical to `transmute::<f64, u64>(self)` on all platforms.
413     ///
414     /// See `from_bits` for some discussion of the portability of this operation
415     /// (there are almost no issues).
416     ///
417     /// Note that this function is distinct from `as` casting, which attempts to
418     /// preserve the *numeric* value, and not the bitwise value.
419     ///
420     /// # Examples
421     ///
422     /// ```
423     /// assert!((1f64).to_bits() != 1f64 as u64); // to_bits() is not casting!
424     /// assert_eq!((12.5f64).to_bits(), 0x4029000000000000);
425     ///
426     /// ```
427     #[stable(feature = "float_bits_conv", since = "1.20.0")]
428     #[inline]
429     pub fn to_bits(self) -> u64 {
430         // SAFETY: `u64` is a plain old datatype so we can always transmute to it
431         unsafe { mem::transmute(self) }
432     }
433
434     /// Raw transmutation from `u64`.
435     ///
436     /// This is currently identical to `transmute::<u64, f64>(v)` on all platforms.
437     /// It turns out this is incredibly portable, for two reasons:
438     ///
439     /// * Floats and Ints have the same endianness on all supported platforms.
440     /// * IEEE-754 very precisely specifies the bit layout of floats.
441     ///
442     /// However there is one caveat: prior to the 2008 version of IEEE-754, how
443     /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
444     /// (notably x86 and ARM) picked the interpretation that was ultimately
445     /// standardized in 2008, but some didn't (notably MIPS). As a result, all
446     /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
447     ///
448     /// Rather than trying to preserve signaling-ness cross-platform, this
449     /// implementation favours preserving the exact bits. This means that
450     /// any payloads encoded in NaNs will be preserved even if the result of
451     /// this method is sent over the network from an x86 machine to a MIPS one.
452     ///
453     /// If the results of this method are only manipulated by the same
454     /// architecture that produced them, then there is no portability concern.
455     ///
456     /// If the input isn't NaN, then there is no portability concern.
457     ///
458     /// If you don't care about signalingness (very likely), then there is no
459     /// portability concern.
460     ///
461     /// Note that this function is distinct from `as` casting, which attempts to
462     /// preserve the *numeric* value, and not the bitwise value.
463     ///
464     /// # Examples
465     ///
466     /// ```
467     /// let v = f64::from_bits(0x4029000000000000);
468     /// assert_eq!(v, 12.5);
469     /// ```
470     #[stable(feature = "float_bits_conv", since = "1.20.0")]
471     #[inline]
472     pub fn from_bits(v: u64) -> Self {
473         // SAFETY: `u64` is a plain old datatype so we can always transmute from it
474         // It turns out the safety issues with sNaN were overblown! Hooray!
475         unsafe { mem::transmute(v) }
476     }
477
478     /// Return the memory representation of this floating point number as a byte array in
479     /// big-endian (network) byte order.
480     ///
481     /// # Examples
482     ///
483     /// ```
484     /// let bytes = 12.5f64.to_be_bytes();
485     /// assert_eq!(bytes, [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
486     /// ```
487     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
488     #[inline]
489     pub fn to_be_bytes(self) -> [u8; 8] {
490         self.to_bits().to_be_bytes()
491     }
492
493     /// Return the memory representation of this floating point number as a byte array in
494     /// little-endian byte order.
495     ///
496     /// # Examples
497     ///
498     /// ```
499     /// let bytes = 12.5f64.to_le_bytes();
500     /// assert_eq!(bytes, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]);
501     /// ```
502     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
503     #[inline]
504     pub fn to_le_bytes(self) -> [u8; 8] {
505         self.to_bits().to_le_bytes()
506     }
507
508     /// Return the memory representation of this floating point number as a byte array in
509     /// native byte order.
510     ///
511     /// As the target platform's native endianness is used, portable code
512     /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
513     ///
514     /// [`to_be_bytes`]: #method.to_be_bytes
515     /// [`to_le_bytes`]: #method.to_le_bytes
516     ///
517     /// # Examples
518     ///
519     /// ```
520     /// let bytes = 12.5f64.to_ne_bytes();
521     /// assert_eq!(
522     ///     bytes,
523     ///     if cfg!(target_endian = "big") {
524     ///         [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
525     ///     } else {
526     ///         [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]
527     ///     }
528     /// );
529     /// ```
530     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
531     #[inline]
532     pub fn to_ne_bytes(self) -> [u8; 8] {
533         self.to_bits().to_ne_bytes()
534     }
535
536     /// Create a floating point value from its representation as a byte array in big endian.
537     ///
538     /// # Examples
539     ///
540     /// ```
541     /// let value = f64::from_be_bytes([0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
542     /// assert_eq!(value, 12.5);
543     /// ```
544     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
545     #[inline]
546     pub fn from_be_bytes(bytes: [u8; 8]) -> Self {
547         Self::from_bits(u64::from_be_bytes(bytes))
548     }
549
550     /// Create a floating point value from its representation as a byte array in little endian.
551     ///
552     /// # Examples
553     ///
554     /// ```
555     /// let value = f64::from_le_bytes([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]);
556     /// assert_eq!(value, 12.5);
557     /// ```
558     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
559     #[inline]
560     pub fn from_le_bytes(bytes: [u8; 8]) -> Self {
561         Self::from_bits(u64::from_le_bytes(bytes))
562     }
563
564     /// Create a floating point value from its representation as a byte array in native endian.
565     ///
566     /// As the target platform's native endianness is used, portable code
567     /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
568     /// appropriate instead.
569     ///
570     /// [`from_be_bytes`]: #method.from_be_bytes
571     /// [`from_le_bytes`]: #method.from_le_bytes
572     ///
573     /// # Examples
574     ///
575     /// ```
576     /// let value = f64::from_ne_bytes(if cfg!(target_endian = "big") {
577     ///     [0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
578     /// } else {
579     ///     [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40]
580     /// });
581     /// assert_eq!(value, 12.5);
582     /// ```
583     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
584     #[inline]
585     pub fn from_ne_bytes(bytes: [u8; 8]) -> Self {
586         Self::from_bits(u64::from_ne_bytes(bytes))
587     }
588 }