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