1 //! This module provides constants which are specific to the implementation
2 //! of the `f32` floating point data type.
4 //! *[See also the `f32` primitive type](../../std/primitive.f32.html).*
6 //! Mathematically significant numbers are provided in the `consts` sub-module.
8 //! Although using these constants won’t cause compilation warnings,
9 //! new code should use the associated constants directly on the primitive type.
11 #![stable(feature = "rust1", since = "1.0.0")]
13 use crate::convert::FloatToInt;
15 use crate::intrinsics;
17 use crate::num::FpCategory;
19 /// The radix or base of the internal representation of `f32`.
20 /// Use [`f32::RADIX`](../../std/primitive.f32.html#associatedconstant.RADIX) instead.
21 #[stable(feature = "rust1", since = "1.0.0")]
22 pub const RADIX: u32 = f32::RADIX;
24 /// Number of significant digits in base 2.
25 /// Use [`f32::MANTISSA_DIGITS`](../../std/primitive.f32.html#associatedconstant.MANTISSA_DIGITS) instead.
26 #[stable(feature = "rust1", since = "1.0.0")]
27 pub const MANTISSA_DIGITS: u32 = f32::MANTISSA_DIGITS;
28 /// Approximate number of significant digits in base 10.
29 /// Use [`f32::DIGITS`](../../std/primitive.f32.html#associatedconstant.DIGITS) instead.
30 #[stable(feature = "rust1", since = "1.0.0")]
31 pub const DIGITS: u32 = f32::DIGITS;
33 /// [Machine epsilon] value for `f32`.
34 /// Use [`f32::EPSILON`](../../std/primitive.f32.html#associatedconstant.EPSILON) instead.
36 /// This is the difference between `1.0` and the next larger representable number.
38 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
39 #[stable(feature = "rust1", since = "1.0.0")]
40 pub const EPSILON: f32 = f32::EPSILON;
42 /// Smallest finite `f32` value.
43 /// Use [`f32::MIN`](../../std/primitive.f32.html#associatedconstant.MIN) instead.
44 #[stable(feature = "rust1", since = "1.0.0")]
45 pub const MIN: f32 = f32::MIN;
46 /// Smallest positive normal `f32` value.
47 /// Use [`f32::MIN_POSITIVE`](../../std/primitive.f32.html#associatedconstant.MIN_POSITIVE) instead.
48 #[stable(feature = "rust1", since = "1.0.0")]
49 pub const MIN_POSITIVE: f32 = f32::MIN_POSITIVE;
50 /// Largest finite `f32` value.
51 /// Use [`f32::MAX`](../../std/primitive.f32.html#associatedconstant.MAX) instead.
52 #[stable(feature = "rust1", since = "1.0.0")]
53 pub const MAX: f32 = f32::MAX;
55 /// One greater than the minimum possible normal power of 2 exponent.
56 /// Use [`f32::MIN_EXP`](../../std/primitive.f32.html#associatedconstant.MIN_EXP) instead.
57 #[stable(feature = "rust1", since = "1.0.0")]
58 pub const MIN_EXP: i32 = f32::MIN_EXP;
59 /// Maximum possible power of 2 exponent.
60 /// Use [`f32::MAX_EXP`](../../std/primitive.f32.html#associatedconstant.MAX_EXP) instead.
61 #[stable(feature = "rust1", since = "1.0.0")]
62 pub const MAX_EXP: i32 = f32::MAX_EXP;
64 /// Minimum possible normal power of 10 exponent.
65 /// Use [`f32::MIN_10_EXP`](../../std/primitive.f32.html#associatedconstant.MIN_10_EXP) instead.
66 #[stable(feature = "rust1", since = "1.0.0")]
67 pub const MIN_10_EXP: i32 = f32::MIN_10_EXP;
68 /// Maximum possible power of 10 exponent.
69 /// Use [`f32::MAX_10_EXP`](../../std/primitive.f32.html#associatedconstant.MAX_10_EXP) instead.
70 #[stable(feature = "rust1", since = "1.0.0")]
71 pub const MAX_10_EXP: i32 = f32::MAX_10_EXP;
73 /// Not a Number (NaN).
74 /// Use [`f32::NAN`](../../std/primitive.f32.html#associatedconstant.NAN) instead.
75 #[stable(feature = "rust1", since = "1.0.0")]
76 pub const NAN: f32 = f32::NAN;
78 /// Use [`f32::INFINITY`](../../std/primitive.f32.html#associatedconstant.INFINITY) instead.
79 #[stable(feature = "rust1", since = "1.0.0")]
80 pub const INFINITY: f32 = f32::INFINITY;
81 /// Negative infinity (−∞).
82 /// Use [`f32::NEG_INFINITY`](../../std/primitive.f32.html#associatedconstant.NEG_INFINITY) instead.
83 #[stable(feature = "rust1", since = "1.0.0")]
84 pub const NEG_INFINITY: f32 = f32::NEG_INFINITY;
86 /// Basic mathematical constants.
87 #[stable(feature = "rust1", since = "1.0.0")]
89 // FIXME: replace with mathematical constants from cmath.
91 /// Archimedes' constant (π)
92 #[stable(feature = "rust1", since = "1.0.0")]
93 pub const PI: f32 = 3.14159265358979323846264338327950288_f32;
95 /// The full circle constant (τ)
98 #[unstable(feature = "tau_constant", issue = "66770")]
99 pub const TAU: f32 = 6.28318530717958647692528676655900577_f32;
102 #[stable(feature = "rust1", since = "1.0.0")]
103 pub const FRAC_PI_2: f32 = 1.57079632679489661923132169163975144_f32;
106 #[stable(feature = "rust1", since = "1.0.0")]
107 pub const FRAC_PI_3: f32 = 1.04719755119659774615421446109316763_f32;
110 #[stable(feature = "rust1", since = "1.0.0")]
111 pub const FRAC_PI_4: f32 = 0.785398163397448309615660845819875721_f32;
114 #[stable(feature = "rust1", since = "1.0.0")]
115 pub const FRAC_PI_6: f32 = 0.52359877559829887307710723054658381_f32;
118 #[stable(feature = "rust1", since = "1.0.0")]
119 pub const FRAC_PI_8: f32 = 0.39269908169872415480783042290993786_f32;
122 #[stable(feature = "rust1", since = "1.0.0")]
123 pub const FRAC_1_PI: f32 = 0.318309886183790671537767526745028724_f32;
126 #[stable(feature = "rust1", since = "1.0.0")]
127 pub const FRAC_2_PI: f32 = 0.636619772367581343075535053490057448_f32;
130 #[stable(feature = "rust1", since = "1.0.0")]
131 pub const FRAC_2_SQRT_PI: f32 = 1.12837916709551257389615890312154517_f32;
134 #[stable(feature = "rust1", since = "1.0.0")]
135 pub const SQRT_2: f32 = 1.41421356237309504880168872420969808_f32;
138 #[stable(feature = "rust1", since = "1.0.0")]
139 pub const FRAC_1_SQRT_2: f32 = 0.707106781186547524400844362104849039_f32;
141 /// Euler's number (e)
142 #[stable(feature = "rust1", since = "1.0.0")]
143 pub const E: f32 = 2.71828182845904523536028747135266250_f32;
145 /// log<sub>2</sub>(e)
146 #[stable(feature = "rust1", since = "1.0.0")]
147 pub const LOG2_E: f32 = 1.44269504088896340735992468100189214_f32;
149 /// log<sub>2</sub>(10)
150 #[stable(feature = "extra_log_consts", since = "1.43.0")]
151 pub const LOG2_10: f32 = 3.32192809488736234787031942948939018_f32;
153 /// log<sub>10</sub>(e)
154 #[stable(feature = "rust1", since = "1.0.0")]
155 pub const LOG10_E: f32 = 0.434294481903251827651128918916605082_f32;
157 /// log<sub>10</sub>(2)
158 #[stable(feature = "extra_log_consts", since = "1.43.0")]
159 pub const LOG10_2: f32 = 0.301029995663981195213738894724493027_f32;
162 #[stable(feature = "rust1", since = "1.0.0")]
163 pub const LN_2: f32 = 0.693147180559945309417232121458176568_f32;
166 #[stable(feature = "rust1", since = "1.0.0")]
167 pub const LN_10: f32 = 2.30258509299404568401799145468436421_f32;
173 /// The radix or base of the internal representation of `f32`.
174 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
175 pub const RADIX: u32 = 2;
177 /// Number of significant digits in base 2.
178 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
179 pub const MANTISSA_DIGITS: u32 = 24;
181 /// Approximate number of significant digits in base 10.
182 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
183 pub const DIGITS: u32 = 6;
185 /// [Machine epsilon] value for `f32`.
187 /// This is the difference between `1.0` and the next larger representable number.
189 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
190 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
191 pub const EPSILON: f32 = 1.19209290e-07_f32;
193 /// Smallest finite `f32` value.
194 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
195 pub const MIN: f32 = -3.40282347e+38_f32;
196 /// Smallest positive normal `f32` value.
197 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
198 pub const MIN_POSITIVE: f32 = 1.17549435e-38_f32;
199 /// Largest finite `f32` value.
200 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
201 pub const MAX: f32 = 3.40282347e+38_f32;
203 /// One greater than the minimum possible normal power of 2 exponent.
204 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
205 pub const MIN_EXP: i32 = -125;
206 /// Maximum possible power of 2 exponent.
207 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
208 pub const MAX_EXP: i32 = 128;
210 /// Minimum possible normal power of 10 exponent.
211 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
212 pub const MIN_10_EXP: i32 = -37;
213 /// Maximum possible power of 10 exponent.
214 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
215 pub const MAX_10_EXP: i32 = 38;
217 /// Not a Number (NaN).
218 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
219 pub const NAN: f32 = 0.0_f32 / 0.0_f32;
221 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
222 pub const INFINITY: f32 = 1.0_f32 / 0.0_f32;
223 /// Negative infinity (-∞).
224 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
225 pub const NEG_INFINITY: f32 = -1.0_f32 / 0.0_f32;
227 /// Returns `true` if this value is `NaN`.
230 /// let nan = f32::NAN;
233 /// assert!(nan.is_nan());
234 /// assert!(!f.is_nan());
236 #[stable(feature = "rust1", since = "1.0.0")]
238 pub fn is_nan(self) -> bool {
242 // FIXME(#50145): `abs` is publicly unavailable in libcore due to
243 // concerns about portability, so this implementation is for
244 // private use internally.
246 fn abs_private(self) -> f32 {
247 f32::from_bits(self.to_bits() & 0x7fff_ffff)
250 /// Returns `true` if this value is positive infinity or negative infinity, and
251 /// `false` otherwise.
255 /// let inf = f32::INFINITY;
256 /// let neg_inf = f32::NEG_INFINITY;
257 /// let nan = f32::NAN;
259 /// assert!(!f.is_infinite());
260 /// assert!(!nan.is_infinite());
262 /// assert!(inf.is_infinite());
263 /// assert!(neg_inf.is_infinite());
265 #[stable(feature = "rust1", since = "1.0.0")]
267 pub fn is_infinite(self) -> bool {
268 self.abs_private() == INFINITY
271 /// Returns `true` if this number is neither infinite nor `NaN`.
275 /// let inf = f32::INFINITY;
276 /// let neg_inf = f32::NEG_INFINITY;
277 /// let nan = f32::NAN;
279 /// assert!(f.is_finite());
281 /// assert!(!nan.is_finite());
282 /// assert!(!inf.is_finite());
283 /// assert!(!neg_inf.is_finite());
285 #[stable(feature = "rust1", since = "1.0.0")]
287 pub fn is_finite(self) -> bool {
288 // There's no need to handle NaN separately: if self is NaN,
289 // the comparison is not true, exactly as desired.
290 self.abs_private() < INFINITY
293 /// Returns `true` if the number is neither zero, infinite,
294 /// [subnormal], or `NaN`.
297 /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
298 /// let max = f32::MAX;
299 /// let lower_than_min = 1.0e-40_f32;
300 /// let zero = 0.0_f32;
302 /// assert!(min.is_normal());
303 /// assert!(max.is_normal());
305 /// assert!(!zero.is_normal());
306 /// assert!(!f32::NAN.is_normal());
307 /// assert!(!f32::INFINITY.is_normal());
308 /// // Values between `0` and `min` are Subnormal.
309 /// assert!(!lower_than_min.is_normal());
311 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
312 #[stable(feature = "rust1", since = "1.0.0")]
314 pub fn is_normal(self) -> bool {
315 self.classify() == FpCategory::Normal
318 /// Returns the floating point category of the number. If only one property
319 /// is going to be tested, it is generally faster to use the specific
320 /// predicate instead.
323 /// use std::num::FpCategory;
325 /// let num = 12.4_f32;
326 /// let inf = f32::INFINITY;
328 /// assert_eq!(num.classify(), FpCategory::Normal);
329 /// assert_eq!(inf.classify(), FpCategory::Infinite);
331 #[stable(feature = "rust1", since = "1.0.0")]
332 pub fn classify(self) -> FpCategory {
333 const EXP_MASK: u32 = 0x7f800000;
334 const MAN_MASK: u32 = 0x007fffff;
336 let bits = self.to_bits();
337 match (bits & MAN_MASK, bits & EXP_MASK) {
338 (0, 0) => FpCategory::Zero,
339 (_, 0) => FpCategory::Subnormal,
340 (0, EXP_MASK) => FpCategory::Infinite,
341 (_, EXP_MASK) => FpCategory::Nan,
342 _ => FpCategory::Normal,
346 /// Returns `true` if `self` has a positive sign, including `+0.0`, `NaN`s with
347 /// positive sign bit and positive infinity.
351 /// let g = -7.0_f32;
353 /// assert!(f.is_sign_positive());
354 /// assert!(!g.is_sign_positive());
356 #[stable(feature = "rust1", since = "1.0.0")]
358 pub fn is_sign_positive(self) -> bool {
359 !self.is_sign_negative()
362 /// Returns `true` if `self` has a negative sign, including `-0.0`, `NaN`s with
363 /// negative sign bit and negative infinity.
369 /// assert!(!f.is_sign_negative());
370 /// assert!(g.is_sign_negative());
372 #[stable(feature = "rust1", since = "1.0.0")]
374 pub fn is_sign_negative(self) -> bool {
375 // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
376 // applies to zeros and NaNs as well.
377 self.to_bits() & 0x8000_0000 != 0
380 /// Takes the reciprocal (inverse) of a number, `1/x`.
384 /// let abs_difference = (x.recip() - (1.0 / x)).abs();
386 /// assert!(abs_difference <= f32::EPSILON);
388 #[stable(feature = "rust1", since = "1.0.0")]
390 pub fn recip(self) -> f32 {
394 /// Converts radians to degrees.
397 /// use std::f32::consts;
399 /// let angle = consts::PI;
401 /// let abs_difference = (angle.to_degrees() - 180.0).abs();
403 /// assert!(abs_difference <= f32::EPSILON);
405 #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
407 pub fn to_degrees(self) -> f32 {
408 // Use a constant for better precision.
409 const PIS_IN_180: f32 = 57.2957795130823208767981548141051703_f32;
413 /// Converts degrees to radians.
416 /// use std::f32::consts;
418 /// let angle = 180.0f32;
420 /// let abs_difference = (angle.to_radians() - consts::PI).abs();
422 /// assert!(abs_difference <= f32::EPSILON);
424 #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
426 pub fn to_radians(self) -> f32 {
427 let value: f32 = consts::PI;
428 self * (value / 180.0f32)
431 /// Returns the maximum of the two numbers.
437 /// assert_eq!(x.max(y), y);
440 /// If one of the arguments is NaN, then the other argument is returned.
441 #[stable(feature = "rust1", since = "1.0.0")]
443 pub fn max(self, other: f32) -> f32 {
444 intrinsics::maxnumf32(self, other)
447 /// Returns the minimum of the two numbers.
453 /// assert_eq!(x.min(y), x);
456 /// If one of the arguments is NaN, then the other argument is returned.
457 #[stable(feature = "rust1", since = "1.0.0")]
459 pub fn min(self, other: f32) -> f32 {
460 intrinsics::minnumf32(self, other)
463 /// Rounds toward zero and converts to any primitive integer type,
464 /// assuming that the value is finite and fits in that type.
467 /// #![feature(float_approx_unchecked_to)]
469 /// let value = 4.6_f32;
470 /// let rounded = unsafe { value.approx_unchecked_to::<u16>() };
471 /// assert_eq!(rounded, 4);
473 /// let value = -128.9_f32;
474 /// let rounded = unsafe { value.approx_unchecked_to::<i8>() };
475 /// assert_eq!(rounded, std::i8::MIN);
483 /// * Not be infinite
484 /// * Be representable in the return type `Int`, after truncating off its fractional part
485 #[unstable(feature = "float_approx_unchecked_to", issue = "67058")]
487 pub unsafe fn approx_unchecked_to<Int>(self) -> Int
489 Self: FloatToInt<Int>,
491 FloatToInt::<Int>::approx_unchecked(self)
494 /// Raw transmutation to `u32`.
496 /// This is currently identical to `transmute::<f32, u32>(self)` on all platforms.
498 /// See `from_bits` for some discussion of the portability of this operation
499 /// (there are almost no issues).
501 /// Note that this function is distinct from `as` casting, which attempts to
502 /// preserve the *numeric* value, and not the bitwise value.
507 /// assert_ne!((1f32).to_bits(), 1f32 as u32); // to_bits() is not casting!
508 /// assert_eq!((12.5f32).to_bits(), 0x41480000);
511 #[stable(feature = "float_bits_conv", since = "1.20.0")]
513 pub fn to_bits(self) -> u32 {
514 // SAFETY: `u32` is a plain old datatype so we can always transmute to it
515 unsafe { mem::transmute(self) }
518 /// Raw transmutation from `u32`.
520 /// This is currently identical to `transmute::<u32, f32>(v)` on all platforms.
521 /// It turns out this is incredibly portable, for two reasons:
523 /// * Floats and Ints have the same endianness on all supported platforms.
524 /// * IEEE-754 very precisely specifies the bit layout of floats.
526 /// However there is one caveat: prior to the 2008 version of IEEE-754, how
527 /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
528 /// (notably x86 and ARM) picked the interpretation that was ultimately
529 /// standardized in 2008, but some didn't (notably MIPS). As a result, all
530 /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
532 /// Rather than trying to preserve signaling-ness cross-platform, this
533 /// implementation favors preserving the exact bits. This means that
534 /// any payloads encoded in NaNs will be preserved even if the result of
535 /// this method is sent over the network from an x86 machine to a MIPS one.
537 /// If the results of this method are only manipulated by the same
538 /// architecture that produced them, then there is no portability concern.
540 /// If the input isn't NaN, then there is no portability concern.
542 /// If you don't care about signalingness (very likely), then there is no
543 /// portability concern.
545 /// Note that this function is distinct from `as` casting, which attempts to
546 /// preserve the *numeric* value, and not the bitwise value.
551 /// let v = f32::from_bits(0x41480000);
552 /// assert_eq!(v, 12.5);
554 #[stable(feature = "float_bits_conv", since = "1.20.0")]
556 pub fn from_bits(v: u32) -> Self {
557 // SAFETY: `u32` is a plain old datatype so we can always transmute from it
558 // It turns out the safety issues with sNaN were overblown! Hooray!
559 unsafe { mem::transmute(v) }
562 /// Return the memory representation of this floating point number as a byte array in
563 /// big-endian (network) byte order.
568 /// let bytes = 12.5f32.to_be_bytes();
569 /// assert_eq!(bytes, [0x41, 0x48, 0x00, 0x00]);
571 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
573 pub fn to_be_bytes(self) -> [u8; 4] {
574 self.to_bits().to_be_bytes()
577 /// Return the memory representation of this floating point number as a byte array in
578 /// little-endian byte order.
583 /// let bytes = 12.5f32.to_le_bytes();
584 /// assert_eq!(bytes, [0x00, 0x00, 0x48, 0x41]);
586 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
588 pub fn to_le_bytes(self) -> [u8; 4] {
589 self.to_bits().to_le_bytes()
592 /// Return the memory representation of this floating point number as a byte array in
593 /// native byte order.
595 /// As the target platform's native endianness is used, portable code
596 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
598 /// [`to_be_bytes`]: #method.to_be_bytes
599 /// [`to_le_bytes`]: #method.to_le_bytes
604 /// let bytes = 12.5f32.to_ne_bytes();
607 /// if cfg!(target_endian = "big") {
608 /// [0x41, 0x48, 0x00, 0x00]
610 /// [0x00, 0x00, 0x48, 0x41]
614 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
616 pub fn to_ne_bytes(self) -> [u8; 4] {
617 self.to_bits().to_ne_bytes()
620 /// Create a floating point value from its representation as a byte array in big endian.
625 /// let value = f32::from_be_bytes([0x41, 0x48, 0x00, 0x00]);
626 /// assert_eq!(value, 12.5);
628 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
630 pub fn from_be_bytes(bytes: [u8; 4]) -> Self {
631 Self::from_bits(u32::from_be_bytes(bytes))
634 /// Create a floating point value from its representation as a byte array in little endian.
639 /// let value = f32::from_le_bytes([0x00, 0x00, 0x48, 0x41]);
640 /// assert_eq!(value, 12.5);
642 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
644 pub fn from_le_bytes(bytes: [u8; 4]) -> Self {
645 Self::from_bits(u32::from_le_bytes(bytes))
648 /// Create a floating point value from its representation as a byte array in native endian.
650 /// As the target platform's native endianness is used, portable code
651 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
652 /// appropriate instead.
654 /// [`from_be_bytes`]: #method.from_be_bytes
655 /// [`from_le_bytes`]: #method.from_le_bytes
660 /// let value = f32::from_ne_bytes(if cfg!(target_endian = "big") {
661 /// [0x41, 0x48, 0x00, 0x00]
663 /// [0x00, 0x00, 0x48, 0x41]
665 /// assert_eq!(value, 12.5);
667 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
669 pub fn from_ne_bytes(bytes: [u8; 4]) -> Self {
670 Self::from_bits(u32::from_ne_bytes(bytes))