]> git.proxmox.com Git - rustc.git/blob - src/libcore/num/f32.rs
New upstream version 1.41.1+dfsg1
[rustc.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 #[cfg(not(bootstrap))]
11 use crate::convert::FloatToInt;
12 #[cfg(not(test))]
13 use crate::intrinsics;
14 use crate::mem;
15 use crate::num::FpCategory;
16
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;
20
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;
27
28 /// [Machine epsilon] value for `f32`.
29 ///
30 /// This is the difference between `1.0` and the next larger representable number.
31 ///
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;
35
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;
45
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;
52
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;
59
60 /// Not a Number (NaN).
61 #[stable(feature = "rust1", since = "1.0.0")]
62 pub const NAN: f32 = 0.0_f32 / 0.0_f32;
63 /// Infinity (∞).
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;
69
70 /// Basic mathematical constants.
71 #[stable(feature = "rust1", since = "1.0.0")]
72 pub mod consts {
73 // FIXME: replace with mathematical constants from cmath.
74
75 /// Archimedes' constant (π)
76 #[stable(feature = "rust1", since = "1.0.0")]
77 pub const PI: f32 = 3.14159265358979323846264338327950288_f32;
78
79 /// The full circle constant (τ)
80 ///
81 /// Equal to 2π.
82 #[unstable(feature = "tau_constant", issue = "66770")]
83 pub const TAU: f32 = 6.28318530717958647692528676655900577_f32;
84
85 /// π/2
86 #[stable(feature = "rust1", since = "1.0.0")]
87 pub const FRAC_PI_2: f32 = 1.57079632679489661923132169163975144_f32;
88
89 /// π/3
90 #[stable(feature = "rust1", since = "1.0.0")]
91 pub const FRAC_PI_3: f32 = 1.04719755119659774615421446109316763_f32;
92
93 /// π/4
94 #[stable(feature = "rust1", since = "1.0.0")]
95 pub const FRAC_PI_4: f32 = 0.785398163397448309615660845819875721_f32;
96
97 /// π/6
98 #[stable(feature = "rust1", since = "1.0.0")]
99 pub const FRAC_PI_6: f32 = 0.52359877559829887307710723054658381_f32;
100
101 /// π/8
102 #[stable(feature = "rust1", since = "1.0.0")]
103 pub const FRAC_PI_8: f32 = 0.39269908169872415480783042290993786_f32;
104
105 /// 1/π
106 #[stable(feature = "rust1", since = "1.0.0")]
107 pub const FRAC_1_PI: f32 = 0.318309886183790671537767526745028724_f32;
108
109 /// 2/π
110 #[stable(feature = "rust1", since = "1.0.0")]
111 pub const FRAC_2_PI: f32 = 0.636619772367581343075535053490057448_f32;
112
113 /// 2/sqrt(π)
114 #[stable(feature = "rust1", since = "1.0.0")]
115 pub const FRAC_2_SQRT_PI: f32 = 1.12837916709551257389615890312154517_f32;
116
117 /// sqrt(2)
118 #[stable(feature = "rust1", since = "1.0.0")]
119 pub const SQRT_2: f32 = 1.41421356237309504880168872420969808_f32;
120
121 /// 1/sqrt(2)
122 #[stable(feature = "rust1", since = "1.0.0")]
123 pub const FRAC_1_SQRT_2: f32 = 0.707106781186547524400844362104849039_f32;
124
125 /// Euler's number (e)
126 #[stable(feature = "rust1", since = "1.0.0")]
127 pub const E: f32 = 2.71828182845904523536028747135266250_f32;
128
129 /// log<sub>2</sub>(e)
130 #[stable(feature = "rust1", since = "1.0.0")]
131 pub const LOG2_E: f32 = 1.44269504088896340735992468100189214_f32;
132
133 /// log<sub>2</sub>(10)
134 #[unstable(feature = "extra_log_consts", issue = "50540")]
135 pub const LOG2_10: f32 = 3.32192809488736234787031942948939018_f32;
136
137 /// log<sub>10</sub>(e)
138 #[stable(feature = "rust1", since = "1.0.0")]
139 pub const LOG10_E: f32 = 0.434294481903251827651128918916605082_f32;
140
141 /// log<sub>10</sub>(2)
142 #[unstable(feature = "extra_log_consts", issue = "50540")]
143 pub const LOG10_2: f32 = 0.301029995663981195213738894724493027_f32;
144
145 /// ln(2)
146 #[stable(feature = "rust1", since = "1.0.0")]
147 pub const LN_2: f32 = 0.693147180559945309417232121458176568_f32;
148
149 /// ln(10)
150 #[stable(feature = "rust1", since = "1.0.0")]
151 pub const LN_10: f32 = 2.30258509299404568401799145468436421_f32;
152 }
153
154 #[lang = "f32"]
155 #[cfg(not(test))]
156 impl f32 {
157 /// Returns `true` if this value is `NaN`.
158 ///
159 /// ```
160 /// use std::f32;
161 ///
162 /// let nan = f32::NAN;
163 /// let f = 7.0_f32;
164 ///
165 /// assert!(nan.is_nan());
166 /// assert!(!f.is_nan());
167 /// ```
168 #[stable(feature = "rust1", since = "1.0.0")]
169 #[inline]
170 pub fn is_nan(self) -> bool {
171 self != self
172 }
173
174 // FIXME(#50145): `abs` is publicly unavailable in libcore due to
175 // concerns about portability, so this implementation is for
176 // private use internally.
177 #[inline]
178 fn abs_private(self) -> f32 {
179 f32::from_bits(self.to_bits() & 0x7fff_ffff)
180 }
181
182 /// Returns `true` if this value is positive infinity or negative infinity, and
183 /// `false` otherwise.
184 ///
185 /// ```
186 /// use std::f32;
187 ///
188 /// let f = 7.0f32;
189 /// let inf = f32::INFINITY;
190 /// let neg_inf = f32::NEG_INFINITY;
191 /// let nan = f32::NAN;
192 ///
193 /// assert!(!f.is_infinite());
194 /// assert!(!nan.is_infinite());
195 ///
196 /// assert!(inf.is_infinite());
197 /// assert!(neg_inf.is_infinite());
198 /// ```
199 #[stable(feature = "rust1", since = "1.0.0")]
200 #[inline]
201 pub fn is_infinite(self) -> bool {
202 self.abs_private() == INFINITY
203 }
204
205 /// Returns `true` if this number is neither infinite nor `NaN`.
206 ///
207 /// ```
208 /// use std::f32;
209 ///
210 /// let f = 7.0f32;
211 /// let inf = f32::INFINITY;
212 /// let neg_inf = f32::NEG_INFINITY;
213 /// let nan = f32::NAN;
214 ///
215 /// assert!(f.is_finite());
216 ///
217 /// assert!(!nan.is_finite());
218 /// assert!(!inf.is_finite());
219 /// assert!(!neg_inf.is_finite());
220 /// ```
221 #[stable(feature = "rust1", since = "1.0.0")]
222 #[inline]
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
227 }
228
229 /// Returns `true` if the number is neither zero, infinite,
230 /// [subnormal][subnormal], or `NaN`.
231 ///
232 /// ```
233 /// use std::f32;
234 ///
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;
239 ///
240 /// assert!(min.is_normal());
241 /// assert!(max.is_normal());
242 ///
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());
248 /// ```
249 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
250 #[stable(feature = "rust1", since = "1.0.0")]
251 #[inline]
252 pub fn is_normal(self) -> bool {
253 self.classify() == FpCategory::Normal
254 }
255
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.
259 ///
260 /// ```
261 /// use std::num::FpCategory;
262 /// use std::f32;
263 ///
264 /// let num = 12.4_f32;
265 /// let inf = f32::INFINITY;
266 ///
267 /// assert_eq!(num.classify(), FpCategory::Normal);
268 /// assert_eq!(inf.classify(), FpCategory::Infinite);
269 /// ```
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;
274
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,
282 }
283 }
284
285 /// Returns `true` if `self` has a positive sign, including `+0.0`, `NaN`s with
286 /// positive sign bit and positive infinity.
287 ///
288 /// ```
289 /// let f = 7.0_f32;
290 /// let g = -7.0_f32;
291 ///
292 /// assert!(f.is_sign_positive());
293 /// assert!(!g.is_sign_positive());
294 /// ```
295 #[stable(feature = "rust1", since = "1.0.0")]
296 #[inline]
297 pub fn is_sign_positive(self) -> bool {
298 !self.is_sign_negative()
299 }
300
301 /// Returns `true` if `self` has a negative sign, including `-0.0`, `NaN`s with
302 /// negative sign bit and negative infinity.
303 ///
304 /// ```
305 /// let f = 7.0f32;
306 /// let g = -7.0f32;
307 ///
308 /// assert!(!f.is_sign_negative());
309 /// assert!(g.is_sign_negative());
310 /// ```
311 #[stable(feature = "rust1", since = "1.0.0")]
312 #[inline]
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
317 }
318
319 /// Takes the reciprocal (inverse) of a number, `1/x`.
320 ///
321 /// ```
322 /// use std::f32;
323 ///
324 /// let x = 2.0_f32;
325 /// let abs_difference = (x.recip() - (1.0 / x)).abs();
326 ///
327 /// assert!(abs_difference <= f32::EPSILON);
328 /// ```
329 #[stable(feature = "rust1", since = "1.0.0")]
330 #[inline]
331 pub fn recip(self) -> f32 {
332 1.0 / self
333 }
334
335 /// Converts radians to degrees.
336 ///
337 /// ```
338 /// use std::f32::{self, consts};
339 ///
340 /// let angle = consts::PI;
341 ///
342 /// let abs_difference = (angle.to_degrees() - 180.0).abs();
343 ///
344 /// assert!(abs_difference <= f32::EPSILON);
345 /// ```
346 #[stable(feature = "f32_deg_rad_conversions", since="1.7.0")]
347 #[inline]
348 pub fn to_degrees(self) -> f32 {
349 // Use a constant for better precision.
350 const PIS_IN_180: f32 = 57.2957795130823208767981548141051703_f32;
351 self * PIS_IN_180
352 }
353
354 /// Converts degrees to radians.
355 ///
356 /// ```
357 /// use std::f32::{self, consts};
358 ///
359 /// let angle = 180.0f32;
360 ///
361 /// let abs_difference = (angle.to_radians() - consts::PI).abs();
362 ///
363 /// assert!(abs_difference <= f32::EPSILON);
364 /// ```
365 #[stable(feature = "f32_deg_rad_conversions", since="1.7.0")]
366 #[inline]
367 pub fn to_radians(self) -> f32 {
368 let value: f32 = consts::PI;
369 self * (value / 180.0f32)
370 }
371
372 /// Returns the maximum of the two numbers.
373 ///
374 /// ```
375 /// let x = 1.0f32;
376 /// let y = 2.0f32;
377 ///
378 /// assert_eq!(x.max(y), y);
379 /// ```
380 ///
381 /// If one of the arguments is NaN, then the other argument is returned.
382 #[stable(feature = "rust1", since = "1.0.0")]
383 #[inline]
384 pub fn max(self, other: f32) -> f32 {
385 intrinsics::maxnumf32(self, other)
386 }
387
388 /// Returns the minimum of the two numbers.
389 ///
390 /// ```
391 /// let x = 1.0f32;
392 /// let y = 2.0f32;
393 ///
394 /// assert_eq!(x.min(y), x);
395 /// ```
396 ///
397 /// If one of the arguments is NaN, then the other argument is returned.
398 #[stable(feature = "rust1", since = "1.0.0")]
399 #[inline]
400 pub fn min(self, other: f32) -> f32 {
401 intrinsics::minnumf32(self, other)
402 }
403
404 /// Rounds toward zero and converts to any primitive integer type,
405 /// assuming that the value is finite and fits in that type.
406 ///
407 /// ```
408 /// #![feature(float_approx_unchecked_to)]
409 ///
410 /// let value = 4.6_f32;
411 /// let rounded = unsafe { value.approx_unchecked_to::<u16>() };
412 /// assert_eq!(rounded, 4);
413 ///
414 /// let value = -128.9_f32;
415 /// let rounded = unsafe { value.approx_unchecked_to::<i8>() };
416 /// assert_eq!(rounded, std::i8::MIN);
417 /// ```
418 ///
419 /// # Safety
420 ///
421 /// The value must:
422 ///
423 /// * Not be `NaN`
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")]
428 #[inline]
429 pub unsafe fn approx_unchecked_to<Int>(self) -> Int where Self: FloatToInt<Int> {
430 FloatToInt::<Int>::approx_unchecked(self)
431 }
432
433 /// Raw transmutation to `u32`.
434 ///
435 /// This is currently identical to `transmute::<f32, u32>(self)` on all platforms.
436 ///
437 /// See `from_bits` for some discussion of the portability of this operation
438 /// (there are almost no issues).
439 ///
440 /// Note that this function is distinct from `as` casting, which attempts to
441 /// preserve the *numeric* value, and not the bitwise value.
442 ///
443 /// # Examples
444 ///
445 /// ```
446 /// assert_ne!((1f32).to_bits(), 1f32 as u32); // to_bits() is not casting!
447 /// assert_eq!((12.5f32).to_bits(), 0x41480000);
448 ///
449 /// ```
450 #[stable(feature = "float_bits_conv", since = "1.20.0")]
451 #[inline]
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) }
455 }
456
457 /// Raw transmutation from `u32`.
458 ///
459 /// This is currently identical to `transmute::<u32, f32>(v)` on all platforms.
460 /// It turns out this is incredibly portable, for two reasons:
461 ///
462 /// * Floats and Ints have the same endianness on all supported platforms.
463 /// * IEEE-754 very precisely specifies the bit layout of floats.
464 ///
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.
470 ///
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.
475 ///
476 /// If the results of this method are only manipulated by the same
477 /// architecture that produced them, then there is no portability concern.
478 ///
479 /// If the input isn't NaN, then there is no portability concern.
480 ///
481 /// If you don't care about signalingness (very likely), then there is no
482 /// portability concern.
483 ///
484 /// Note that this function is distinct from `as` casting, which attempts to
485 /// preserve the *numeric* value, and not the bitwise value.
486 ///
487 /// # Examples
488 ///
489 /// ```
490 /// let v = f32::from_bits(0x41480000);
491 /// assert_eq!(v, 12.5);
492 /// ```
493 #[stable(feature = "float_bits_conv", since = "1.20.0")]
494 #[inline]
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) }
499 }
500
501 /// Return the memory representation of this floating point number as a byte array in
502 /// big-endian (network) byte order.
503 ///
504 /// # Examples
505 ///
506 /// ```
507 /// let bytes = 12.5f32.to_be_bytes();
508 /// assert_eq!(bytes, [0x41, 0x48, 0x00, 0x00]);
509 /// ```
510 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
511 #[inline]
512 pub fn to_be_bytes(self) -> [u8; 4] {
513 self.to_bits().to_be_bytes()
514 }
515
516 /// Return the memory representation of this floating point number as a byte array in
517 /// little-endian byte order.
518 ///
519 /// # Examples
520 ///
521 /// ```
522 /// let bytes = 12.5f32.to_le_bytes();
523 /// assert_eq!(bytes, [0x00, 0x00, 0x48, 0x41]);
524 /// ```
525 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
526 #[inline]
527 pub fn to_le_bytes(self) -> [u8; 4] {
528 self.to_bits().to_le_bytes()
529 }
530
531 /// Return the memory representation of this floating point number as a byte array in
532 /// native byte order.
533 ///
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.
536 ///
537 /// [`to_be_bytes`]: #method.to_be_bytes
538 /// [`to_le_bytes`]: #method.to_le_bytes
539 ///
540 /// # Examples
541 ///
542 /// ```
543 /// let bytes = 12.5f32.to_ne_bytes();
544 /// assert_eq!(
545 /// bytes,
546 /// if cfg!(target_endian = "big") {
547 /// [0x41, 0x48, 0x00, 0x00]
548 /// } else {
549 /// [0x00, 0x00, 0x48, 0x41]
550 /// }
551 /// );
552 /// ```
553 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
554 #[inline]
555 pub fn to_ne_bytes(self) -> [u8; 4] {
556 self.to_bits().to_ne_bytes()
557 }
558
559 /// Create a floating point value from its representation as a byte array in big endian.
560 ///
561 /// # Examples
562 ///
563 /// ```
564 /// let value = f32::from_be_bytes([0x41, 0x48, 0x00, 0x00]);
565 /// assert_eq!(value, 12.5);
566 /// ```
567 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
568 #[inline]
569 pub fn from_be_bytes(bytes: [u8; 4]) -> Self {
570 Self::from_bits(u32::from_be_bytes(bytes))
571 }
572
573 /// Create a floating point value from its representation as a byte array in little endian.
574 ///
575 /// # Examples
576 ///
577 /// ```
578 /// let value = f32::from_le_bytes([0x00, 0x00, 0x48, 0x41]);
579 /// assert_eq!(value, 12.5);
580 /// ```
581 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
582 #[inline]
583 pub fn from_le_bytes(bytes: [u8; 4]) -> Self {
584 Self::from_bits(u32::from_le_bytes(bytes))
585 }
586
587 /// Create a floating point value from its representation as a byte array in native endian.
588 ///
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.
592 ///
593 /// [`from_be_bytes`]: #method.from_be_bytes
594 /// [`from_le_bytes`]: #method.from_le_bytes
595 ///
596 /// # Examples
597 ///
598 /// ```
599 /// let value = f32::from_ne_bytes(if cfg!(target_endian = "big") {
600 /// [0x41, 0x48, 0x00, 0x00]
601 /// } else {
602 /// [0x00, 0x00, 0x48, 0x41]
603 /// });
604 /// assert_eq!(value, 12.5);
605 /// ```
606 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
607 #[inline]
608 pub fn from_ne_bytes(bytes: [u8; 4]) -> Self {
609 Self::from_bits(u32::from_ne_bytes(bytes))
610 }
611 }