]>
git.proxmox.com Git - rustc.git/blob - src/libcore/num/f32.rs
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 #![stable(feature = "rust1", since = "1.0.0")]
10 #[cfg(not(bootstrap))]
11 use crate::convert
::FloatToInt
;
13 use crate::intrinsics
;
15 use crate::num
::FpCategory
;
17 /// The radix or base of the internal representation of `f32`.
18 #[stable(feature = "rust1", since = "1.0.0")]
19 pub const RADIX
: u32 = 2;
21 /// Number of significant digits in base 2.
22 #[stable(feature = "rust1", since = "1.0.0")]
23 pub const MANTISSA_DIGITS
: u32 = 24;
24 /// Approximate number of significant digits in base 10.
25 #[stable(feature = "rust1", since = "1.0.0")]
26 pub const DIGITS
: u32 = 6;
28 /// [Machine epsilon] value for `f32`.
30 /// This is the difference between `1.0` and the next larger representable number.
32 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
33 #[stable(feature = "rust1", since = "1.0.0")]
34 pub const EPSILON
: f32 = 1.19209290e-07_f32;
36 /// Smallest finite `f32` value.
37 #[stable(feature = "rust1", since = "1.0.0")]
38 pub const MIN
: f32 = -3.40282347e+38_f32;
39 /// Smallest positive normal `f32` value.
40 #[stable(feature = "rust1", since = "1.0.0")]
41 pub const MIN_POSITIVE
: f32 = 1.17549435e-38_f32;
42 /// Largest finite `f32` value.
43 #[stable(feature = "rust1", since = "1.0.0")]
44 pub const MAX
: f32 = 3.40282347e+38_f32;
46 /// One greater than the minimum possible normal power of 2 exponent.
47 #[stable(feature = "rust1", since = "1.0.0")]
48 pub const MIN_EXP
: i32 = -125;
49 /// Maximum possible power of 2 exponent.
50 #[stable(feature = "rust1", since = "1.0.0")]
51 pub const MAX_EXP
: i32 = 128;
53 /// Minimum possible normal power of 10 exponent.
54 #[stable(feature = "rust1", since = "1.0.0")]
55 pub const MIN_10_EXP
: i32 = -37;
56 /// Maximum possible power of 10 exponent.
57 #[stable(feature = "rust1", since = "1.0.0")]
58 pub const MAX_10_EXP
: i32 = 38;
60 /// Not a Number (NaN).
61 #[stable(feature = "rust1", since = "1.0.0")]
62 pub const NAN
: f32 = 0.0_f32 / 0.0_f32;
64 #[stable(feature = "rust1", since = "1.0.0")]
65 pub const INFINITY
: f32 = 1.0_f32 / 0.0_f32;
66 /// Negative infinity (-∞).
67 #[stable(feature = "rust1", since = "1.0.0")]
68 pub const NEG_INFINITY
: f32 = -1.0_f32 / 0.0_f32;
70 /// Basic mathematical constants.
71 #[stable(feature = "rust1", since = "1.0.0")]
73 // FIXME: replace with mathematical constants from cmath.
75 /// Archimedes' constant (π)
76 #[stable(feature = "rust1", since = "1.0.0")]
77 pub const PI
: f32 = 3.14159265358979323846264338327950288_f32;
79 /// The full circle constant (τ)
82 #[unstable(feature = "tau_constant", issue = "66770")]
83 pub const TAU
: f32 = 6.28318530717958647692528676655900577_f32;
86 #[stable(feature = "rust1", since = "1.0.0")]
87 pub const FRAC_PI_2
: f32 = 1.57079632679489661923132169163975144_f32;
90 #[stable(feature = "rust1", since = "1.0.0")]
91 pub const FRAC_PI_3
: f32 = 1.04719755119659774615421446109316763_f32;
94 #[stable(feature = "rust1", since = "1.0.0")]
95 pub const FRAC_PI_4
: f32 = 0.785398163397448309615660845819875721_f32;
98 #[stable(feature = "rust1", since = "1.0.0")]
99 pub const FRAC_PI_6
: f32 = 0.52359877559829887307710723054658381_f32;
102 #[stable(feature = "rust1", since = "1.0.0")]
103 pub const FRAC_PI_8
: f32 = 0.39269908169872415480783042290993786_f32;
106 #[stable(feature = "rust1", since = "1.0.0")]
107 pub const FRAC_1_PI
: f32 = 0.318309886183790671537767526745028724_f32;
110 #[stable(feature = "rust1", since = "1.0.0")]
111 pub const FRAC_2_PI
: f32 = 0.636619772367581343075535053490057448_f32;
114 #[stable(feature = "rust1", since = "1.0.0")]
115 pub const FRAC_2_SQRT_PI
: f32 = 1.12837916709551257389615890312154517_f32;
118 #[stable(feature = "rust1", since = "1.0.0")]
119 pub const SQRT_2
: f32 = 1.41421356237309504880168872420969808_f32;
122 #[stable(feature = "rust1", since = "1.0.0")]
123 pub const FRAC_1_SQRT_2
: f32 = 0.707106781186547524400844362104849039_f32;
125 /// Euler's number (e)
126 #[stable(feature = "rust1", since = "1.0.0")]
127 pub const E
: f32 = 2.71828182845904523536028747135266250_f32;
129 /// log<sub>2</sub>(e)
130 #[stable(feature = "rust1", since = "1.0.0")]
131 pub const LOG2_E
: f32 = 1.44269504088896340735992468100189214_f32;
133 /// log<sub>2</sub>(10)
134 #[unstable(feature = "extra_log_consts", issue = "50540")]
135 pub const LOG2_10
: f32 = 3.32192809488736234787031942948939018_f32;
137 /// log<sub>10</sub>(e)
138 #[stable(feature = "rust1", since = "1.0.0")]
139 pub const LOG10_E
: f32 = 0.434294481903251827651128918916605082_f32;
141 /// log<sub>10</sub>(2)
142 #[unstable(feature = "extra_log_consts", issue = "50540")]
143 pub const LOG10_2
: f32 = 0.301029995663981195213738894724493027_f32;
146 #[stable(feature = "rust1", since = "1.0.0")]
147 pub const LN_2
: f32 = 0.693147180559945309417232121458176568_f32;
150 #[stable(feature = "rust1", since = "1.0.0")]
151 pub const LN_10
: f32 = 2.30258509299404568401799145468436421_f32;
157 /// Returns `true` if this value is `NaN`.
162 /// let nan = f32::NAN;
165 /// assert!(nan.is_nan());
166 /// assert!(!f.is_nan());
168 #[stable(feature = "rust1", since = "1.0.0")]
170 pub fn is_nan(self) -> bool
{
174 // FIXME(#50145): `abs` is publicly unavailable in libcore due to
175 // concerns about portability, so this implementation is for
176 // private use internally.
178 fn abs_private(self) -> f32 {
179 f32::from_bits(self.to_bits() & 0x7fff_ffff)
182 /// Returns `true` if this value is positive infinity or negative infinity, and
183 /// `false` otherwise.
189 /// let inf = f32::INFINITY;
190 /// let neg_inf = f32::NEG_INFINITY;
191 /// let nan = f32::NAN;
193 /// assert!(!f.is_infinite());
194 /// assert!(!nan.is_infinite());
196 /// assert!(inf.is_infinite());
197 /// assert!(neg_inf.is_infinite());
199 #[stable(feature = "rust1", since = "1.0.0")]
201 pub fn is_infinite(self) -> bool
{
202 self.abs_private() == INFINITY
205 /// Returns `true` if this number is neither infinite nor `NaN`.
211 /// let inf = f32::INFINITY;
212 /// let neg_inf = f32::NEG_INFINITY;
213 /// let nan = f32::NAN;
215 /// assert!(f.is_finite());
217 /// assert!(!nan.is_finite());
218 /// assert!(!inf.is_finite());
219 /// assert!(!neg_inf.is_finite());
221 #[stable(feature = "rust1", since = "1.0.0")]
223 pub fn is_finite(self) -> bool
{
224 // There's no need to handle NaN separately: if self is NaN,
225 // the comparison is not true, exactly as desired.
226 self.abs_private() < INFINITY
229 /// Returns `true` if the number is neither zero, infinite,
230 /// [subnormal][subnormal], or `NaN`.
235 /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
236 /// let max = f32::MAX;
237 /// let lower_than_min = 1.0e-40_f32;
238 /// let zero = 0.0_f32;
240 /// assert!(min.is_normal());
241 /// assert!(max.is_normal());
243 /// assert!(!zero.is_normal());
244 /// assert!(!f32::NAN.is_normal());
245 /// assert!(!f32::INFINITY.is_normal());
246 /// // Values between `0` and `min` are Subnormal.
247 /// assert!(!lower_than_min.is_normal());
249 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
250 #[stable(feature = "rust1", since = "1.0.0")]
252 pub fn is_normal(self) -> bool
{
253 self.classify() == FpCategory
::Normal
256 /// Returns the floating point category of the number. If only one property
257 /// is going to be tested, it is generally faster to use the specific
258 /// predicate instead.
261 /// use std::num::FpCategory;
264 /// let num = 12.4_f32;
265 /// let inf = f32::INFINITY;
267 /// assert_eq!(num.classify(), FpCategory::Normal);
268 /// assert_eq!(inf.classify(), FpCategory::Infinite);
270 #[stable(feature = "rust1", since = "1.0.0")]
271 pub fn classify(self) -> FpCategory
{
272 const EXP_MASK
: u32 = 0x7f800000;
273 const MAN_MASK
: u32 = 0x007fffff;
275 let bits
= self.to_bits();
276 match (bits
& MAN_MASK
, bits
& EXP_MASK
) {
277 (0, 0) => FpCategory
::Zero
,
278 (_
, 0) => FpCategory
::Subnormal
,
279 (0, EXP_MASK
) => FpCategory
::Infinite
,
280 (_
, EXP_MASK
) => FpCategory
::Nan
,
281 _
=> FpCategory
::Normal
,
285 /// Returns `true` if `self` has a positive sign, including `+0.0`, `NaN`s with
286 /// positive sign bit and positive infinity.
290 /// let g = -7.0_f32;
292 /// assert!(f.is_sign_positive());
293 /// assert!(!g.is_sign_positive());
295 #[stable(feature = "rust1", since = "1.0.0")]
297 pub fn is_sign_positive(self) -> bool
{
298 !self.is_sign_negative()
301 /// Returns `true` if `self` has a negative sign, including `-0.0`, `NaN`s with
302 /// negative sign bit and negative infinity.
308 /// assert!(!f.is_sign_negative());
309 /// assert!(g.is_sign_negative());
311 #[stable(feature = "rust1", since = "1.0.0")]
313 pub fn is_sign_negative(self) -> bool
{
314 // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
315 // applies to zeros and NaNs as well.
316 self.to_bits() & 0x8000_0000 != 0
319 /// Takes the reciprocal (inverse) of a number, `1/x`.
325 /// let abs_difference = (x.recip() - (1.0 / x)).abs();
327 /// assert!(abs_difference <= f32::EPSILON);
329 #[stable(feature = "rust1", since = "1.0.0")]
331 pub fn recip(self) -> f32 {
335 /// Converts radians to degrees.
338 /// use std::f32::{self, consts};
340 /// let angle = consts::PI;
342 /// let abs_difference = (angle.to_degrees() - 180.0).abs();
344 /// assert!(abs_difference <= f32::EPSILON);
346 #[stable(feature = "f32_deg_rad_conversions", since="1.7.0")]
348 pub fn to_degrees(self) -> f32 {
349 // Use a constant for better precision.
350 const PIS_IN_180
: f32 = 57.2957795130823208767981548141051703_f32;
354 /// Converts degrees to radians.
357 /// use std::f32::{self, consts};
359 /// let angle = 180.0f32;
361 /// let abs_difference = (angle.to_radians() - consts::PI).abs();
363 /// assert!(abs_difference <= f32::EPSILON);
365 #[stable(feature = "f32_deg_rad_conversions", since="1.7.0")]
367 pub fn to_radians(self) -> f32 {
368 let value
: f32 = consts
::PI
;
369 self * (value
/ 180.0f32)
372 /// Returns the maximum of the two numbers.
378 /// assert_eq!(x.max(y), y);
381 /// If one of the arguments is NaN, then the other argument is returned.
382 #[stable(feature = "rust1", since = "1.0.0")]
384 pub fn max(self, other
: f32) -> f32 {
385 intrinsics
::maxnumf32(self, other
)
388 /// Returns the minimum of the two numbers.
394 /// assert_eq!(x.min(y), x);
397 /// If one of the arguments is NaN, then the other argument is returned.
398 #[stable(feature = "rust1", since = "1.0.0")]
400 pub fn min(self, other
: f32) -> f32 {
401 intrinsics
::minnumf32(self, other
)
404 /// Rounds toward zero and converts to any primitive integer type,
405 /// assuming that the value is finite and fits in that type.
408 /// #![feature(float_approx_unchecked_to)]
410 /// let value = 4.6_f32;
411 /// let rounded = unsafe { value.approx_unchecked_to::<u16>() };
412 /// assert_eq!(rounded, 4);
414 /// let value = -128.9_f32;
415 /// let rounded = unsafe { value.approx_unchecked_to::<i8>() };
416 /// assert_eq!(rounded, std::i8::MIN);
424 /// * Not be infinite
425 /// * Be representable in the return type `Int`, after truncating off its fractional part
426 #[cfg(not(bootstrap))]
427 #[unstable(feature = "float_approx_unchecked_to", issue = "67058")]
429 pub unsafe fn approx_unchecked_to
<Int
>(self) -> Int
where Self: FloatToInt
<Int
> {
430 FloatToInt
::<Int
>::approx_unchecked(self)
433 /// Raw transmutation to `u32`.
435 /// This is currently identical to `transmute::<f32, u32>(self)` on all platforms.
437 /// See `from_bits` for some discussion of the portability of this operation
438 /// (there are almost no issues).
440 /// Note that this function is distinct from `as` casting, which attempts to
441 /// preserve the *numeric* value, and not the bitwise value.
446 /// assert_ne!((1f32).to_bits(), 1f32 as u32); // to_bits() is not casting!
447 /// assert_eq!((12.5f32).to_bits(), 0x41480000);
450 #[stable(feature = "float_bits_conv", since = "1.20.0")]
452 pub fn to_bits(self) -> u32 {
453 // SAFETY: `u32` is a plain old datatype so we can always transmute to it
454 unsafe { mem::transmute(self) }
457 /// Raw transmutation from `u32`.
459 /// This is currently identical to `transmute::<u32, f32>(v)` on all platforms.
460 /// It turns out this is incredibly portable, for two reasons:
462 /// * Floats and Ints have the same endianness on all supported platforms.
463 /// * IEEE-754 very precisely specifies the bit layout of floats.
465 /// However there is one caveat: prior to the 2008 version of IEEE-754, how
466 /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
467 /// (notably x86 and ARM) picked the interpretation that was ultimately
468 /// standardized in 2008, but some didn't (notably MIPS). As a result, all
469 /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
471 /// Rather than trying to preserve signaling-ness cross-platform, this
472 /// implementation favors preserving the exact bits. This means that
473 /// any payloads encoded in NaNs will be preserved even if the result of
474 /// this method is sent over the network from an x86 machine to a MIPS one.
476 /// If the results of this method are only manipulated by the same
477 /// architecture that produced them, then there is no portability concern.
479 /// If the input isn't NaN, then there is no portability concern.
481 /// If you don't care about signalingness (very likely), then there is no
482 /// portability concern.
484 /// Note that this function is distinct from `as` casting, which attempts to
485 /// preserve the *numeric* value, and not the bitwise value.
490 /// let v = f32::from_bits(0x41480000);
491 /// assert_eq!(v, 12.5);
493 #[stable(feature = "float_bits_conv", since = "1.20.0")]
495 pub fn from_bits(v
: u32) -> Self {
496 // SAFETY: `u32` is a plain old datatype so we can always transmute from it
497 // It turns out the safety issues with sNaN were overblown! Hooray!
498 unsafe { mem::transmute(v) }
501 /// Return the memory representation of this floating point number as a byte array in
502 /// big-endian (network) byte order.
507 /// let bytes = 12.5f32.to_be_bytes();
508 /// assert_eq!(bytes, [0x41, 0x48, 0x00, 0x00]);
510 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
512 pub fn to_be_bytes(self) -> [u8; 4] {
513 self.to_bits().to_be_bytes()
516 /// Return the memory representation of this floating point number as a byte array in
517 /// little-endian byte order.
522 /// let bytes = 12.5f32.to_le_bytes();
523 /// assert_eq!(bytes, [0x00, 0x00, 0x48, 0x41]);
525 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
527 pub fn to_le_bytes(self) -> [u8; 4] {
528 self.to_bits().to_le_bytes()
531 /// Return the memory representation of this floating point number as a byte array in
532 /// native byte order.
534 /// As the target platform's native endianness is used, portable code
535 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
537 /// [`to_be_bytes`]: #method.to_be_bytes
538 /// [`to_le_bytes`]: #method.to_le_bytes
543 /// let bytes = 12.5f32.to_ne_bytes();
546 /// if cfg!(target_endian = "big") {
547 /// [0x41, 0x48, 0x00, 0x00]
549 /// [0x00, 0x00, 0x48, 0x41]
553 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
555 pub fn to_ne_bytes(self) -> [u8; 4] {
556 self.to_bits().to_ne_bytes()
559 /// Create a floating point value from its representation as a byte array in big endian.
564 /// let value = f32::from_be_bytes([0x41, 0x48, 0x00, 0x00]);
565 /// assert_eq!(value, 12.5);
567 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
569 pub fn from_be_bytes(bytes
: [u8; 4]) -> Self {
570 Self::from_bits(u32::from_be_bytes(bytes
))
573 /// Create a floating point value from its representation as a byte array in little endian.
578 /// let value = f32::from_le_bytes([0x00, 0x00, 0x48, 0x41]);
579 /// assert_eq!(value, 12.5);
581 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
583 pub fn from_le_bytes(bytes
: [u8; 4]) -> Self {
584 Self::from_bits(u32::from_le_bytes(bytes
))
587 /// Create a floating point value from its representation as a byte array in native endian.
589 /// As the target platform's native endianness is used, portable code
590 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
591 /// appropriate instead.
593 /// [`from_be_bytes`]: #method.from_be_bytes
594 /// [`from_le_bytes`]: #method.from_le_bytes
599 /// let value = f32::from_ne_bytes(if cfg!(target_endian = "big") {
600 /// [0x41, 0x48, 0x00, 0x00]
602 /// [0x00, 0x00, 0x48, 0x41]
604 /// assert_eq!(value, 12.5);
606 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
608 pub fn from_ne_bytes(bytes
: [u8; 4]) -> Self {
609 Self::from_bits(u32::from_ne_bytes(bytes
))