]> git.lizzy.rs Git - rust.git/blob - src/libcore/num/f32.rs
Rollup merge of #58273 - taiki-e:rename-dependency, r=matthewjasper
[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 mem;
11 use num::FpCategory;
12
13 /// The radix or base of the internal representation of `f32`.
14 #[stable(feature = "rust1", since = "1.0.0")]
15 pub const RADIX: u32 = 2;
16
17 /// Number of significant digits in base 2.
18 #[stable(feature = "rust1", since = "1.0.0")]
19 pub const MANTISSA_DIGITS: u32 = 24;
20 /// Approximate number of significant digits in base 10.
21 #[stable(feature = "rust1", since = "1.0.0")]
22 pub const DIGITS: u32 = 6;
23
24 /// [Machine epsilon] value for `f32`.
25 ///
26 /// This is the difference between `1.0` and the next largest representable number.
27 ///
28 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
29 #[stable(feature = "rust1", since = "1.0.0")]
30 pub const EPSILON: f32 = 1.19209290e-07_f32;
31
32 /// Smallest finite `f32` value.
33 #[stable(feature = "rust1", since = "1.0.0")]
34 pub const MIN: f32 = -3.40282347e+38_f32;
35 /// Smallest positive normal `f32` value.
36 #[stable(feature = "rust1", since = "1.0.0")]
37 pub const MIN_POSITIVE: f32 = 1.17549435e-38_f32;
38 /// Largest finite `f32` value.
39 #[stable(feature = "rust1", since = "1.0.0")]
40 pub const MAX: f32 = 3.40282347e+38_f32;
41
42 /// One greater than the minimum possible normal power of 2 exponent.
43 #[stable(feature = "rust1", since = "1.0.0")]
44 pub const MIN_EXP: i32 = -125;
45 /// Maximum possible power of 2 exponent.
46 #[stable(feature = "rust1", since = "1.0.0")]
47 pub const MAX_EXP: i32 = 128;
48
49 /// Minimum possible normal power of 10 exponent.
50 #[stable(feature = "rust1", since = "1.0.0")]
51 pub const MIN_10_EXP: i32 = -37;
52 /// Maximum possible power of 10 exponent.
53 #[stable(feature = "rust1", since = "1.0.0")]
54 pub const MAX_10_EXP: i32 = 38;
55
56 /// Not a Number (NaN).
57 #[stable(feature = "rust1", since = "1.0.0")]
58 pub const NAN: f32 = 0.0_f32 / 0.0_f32;
59 /// Infinity (∞).
60 #[stable(feature = "rust1", since = "1.0.0")]
61 pub const INFINITY: f32 = 1.0_f32 / 0.0_f32;
62 /// Negative infinity (-∞).
63 #[stable(feature = "rust1", since = "1.0.0")]
64 pub const NEG_INFINITY: f32 = -1.0_f32 / 0.0_f32;
65
66 /// Basic mathematical constants.
67 #[stable(feature = "rust1", since = "1.0.0")]
68 pub mod consts {
69     // FIXME: replace with mathematical constants from cmath.
70
71     /// Archimedes' constant (π)
72     #[stable(feature = "rust1", since = "1.0.0")]
73     pub const PI: f32 = 3.14159265358979323846264338327950288_f32;
74
75     /// π/2
76     #[stable(feature = "rust1", since = "1.0.0")]
77     pub const FRAC_PI_2: f32 = 1.57079632679489661923132169163975144_f32;
78
79     /// π/3
80     #[stable(feature = "rust1", since = "1.0.0")]
81     pub const FRAC_PI_3: f32 = 1.04719755119659774615421446109316763_f32;
82
83     /// π/4
84     #[stable(feature = "rust1", since = "1.0.0")]
85     pub const FRAC_PI_4: f32 = 0.785398163397448309615660845819875721_f32;
86
87     /// π/6
88     #[stable(feature = "rust1", since = "1.0.0")]
89     pub const FRAC_PI_6: f32 = 0.52359877559829887307710723054658381_f32;
90
91     /// π/8
92     #[stable(feature = "rust1", since = "1.0.0")]
93     pub const FRAC_PI_8: f32 = 0.39269908169872415480783042290993786_f32;
94
95     /// 1/π
96     #[stable(feature = "rust1", since = "1.0.0")]
97     pub const FRAC_1_PI: f32 = 0.318309886183790671537767526745028724_f32;
98
99     /// 2/π
100     #[stable(feature = "rust1", since = "1.0.0")]
101     pub const FRAC_2_PI: f32 = 0.636619772367581343075535053490057448_f32;
102
103     /// 2/sqrt(π)
104     #[stable(feature = "rust1", since = "1.0.0")]
105     pub const FRAC_2_SQRT_PI: f32 = 1.12837916709551257389615890312154517_f32;
106
107     /// sqrt(2)
108     #[stable(feature = "rust1", since = "1.0.0")]
109     pub const SQRT_2: f32 = 1.41421356237309504880168872420969808_f32;
110
111     /// 1/sqrt(2)
112     #[stable(feature = "rust1", since = "1.0.0")]
113     pub const FRAC_1_SQRT_2: f32 = 0.707106781186547524400844362104849039_f32;
114
115     /// Euler's number (e)
116     #[stable(feature = "rust1", since = "1.0.0")]
117     pub const E: f32 = 2.71828182845904523536028747135266250_f32;
118
119     /// log<sub>2</sub>(e)
120     #[stable(feature = "rust1", since = "1.0.0")]
121     pub const LOG2_E: f32 = 1.44269504088896340735992468100189214_f32;
122
123     /// log<sub>2</sub>(10)
124     #[unstable(feature = "extra_log_consts", issue = "50540")]
125     pub const LOG2_10: f32 = 3.32192809488736234787031942948939018_f32;
126
127     /// log<sub>10</sub>(e)
128     #[stable(feature = "rust1", since = "1.0.0")]
129     pub const LOG10_E: f32 = 0.434294481903251827651128918916605082_f32;
130
131     /// log<sub>10</sub>(2)
132     #[unstable(feature = "extra_log_consts", issue = "50540")]
133     pub const LOG10_2: f32 = 0.301029995663981195213738894724493027_f32;
134
135     /// ln(2)
136     #[stable(feature = "rust1", since = "1.0.0")]
137     pub const LN_2: f32 = 0.693147180559945309417232121458176568_f32;
138
139     /// ln(10)
140     #[stable(feature = "rust1", since = "1.0.0")]
141     pub const LN_10: f32 = 2.30258509299404568401799145468436421_f32;
142 }
143
144 #[lang = "f32"]
145 #[cfg(not(test))]
146 impl f32 {
147     /// Returns `true` if this value is `NaN`.
148     ///
149     /// ```
150     /// use std::f32;
151     ///
152     /// let nan = f32::NAN;
153     /// let f = 7.0_f32;
154     ///
155     /// assert!(nan.is_nan());
156     /// assert!(!f.is_nan());
157     /// ```
158     #[stable(feature = "rust1", since = "1.0.0")]
159     #[inline]
160     pub fn is_nan(self) -> bool {
161         self != self
162     }
163
164     // FIXME(#50145): `abs` is publicly unavailable in libcore due to
165     // concerns about portability, so this implementation is for
166     // private use internally.
167     #[inline]
168     fn abs_private(self) -> f32 {
169         f32::from_bits(self.to_bits() & 0x7fff_ffff)
170     }
171
172     /// Returns `true` if this value is positive infinity or negative infinity, and
173     /// `false` otherwise.
174     ///
175     /// ```
176     /// use std::f32;
177     ///
178     /// let f = 7.0f32;
179     /// let inf = f32::INFINITY;
180     /// let neg_inf = f32::NEG_INFINITY;
181     /// let nan = f32::NAN;
182     ///
183     /// assert!(!f.is_infinite());
184     /// assert!(!nan.is_infinite());
185     ///
186     /// assert!(inf.is_infinite());
187     /// assert!(neg_inf.is_infinite());
188     /// ```
189     #[stable(feature = "rust1", since = "1.0.0")]
190     #[inline]
191     pub fn is_infinite(self) -> bool {
192         self.abs_private() == INFINITY
193     }
194
195     /// Returns `true` if this number is neither infinite nor `NaN`.
196     ///
197     /// ```
198     /// use std::f32;
199     ///
200     /// let f = 7.0f32;
201     /// let inf = f32::INFINITY;
202     /// let neg_inf = f32::NEG_INFINITY;
203     /// let nan = f32::NAN;
204     ///
205     /// assert!(f.is_finite());
206     ///
207     /// assert!(!nan.is_finite());
208     /// assert!(!inf.is_finite());
209     /// assert!(!neg_inf.is_finite());
210     /// ```
211     #[stable(feature = "rust1", since = "1.0.0")]
212     #[inline]
213     pub fn is_finite(self) -> bool {
214         // There's no need to handle NaN separately: if self is NaN,
215         // the comparison is not true, exactly as desired.
216         self.abs_private() < INFINITY
217     }
218
219     /// Returns `true` if the number is neither zero, infinite,
220     /// [subnormal][subnormal], or `NaN`.
221     ///
222     /// ```
223     /// use std::f32;
224     ///
225     /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
226     /// let max = f32::MAX;
227     /// let lower_than_min = 1.0e-40_f32;
228     /// let zero = 0.0_f32;
229     ///
230     /// assert!(min.is_normal());
231     /// assert!(max.is_normal());
232     ///
233     /// assert!(!zero.is_normal());
234     /// assert!(!f32::NAN.is_normal());
235     /// assert!(!f32::INFINITY.is_normal());
236     /// // Values between `0` and `min` are Subnormal.
237     /// assert!(!lower_than_min.is_normal());
238     /// ```
239     /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
240     #[stable(feature = "rust1", since = "1.0.0")]
241     #[inline]
242     pub fn is_normal(self) -> bool {
243         self.classify() == FpCategory::Normal
244     }
245
246     /// Returns the floating point category of the number. If only one property
247     /// is going to be tested, it is generally faster to use the specific
248     /// predicate instead.
249     ///
250     /// ```
251     /// use std::num::FpCategory;
252     /// use std::f32;
253     ///
254     /// let num = 12.4_f32;
255     /// let inf = f32::INFINITY;
256     ///
257     /// assert_eq!(num.classify(), FpCategory::Normal);
258     /// assert_eq!(inf.classify(), FpCategory::Infinite);
259     /// ```
260     #[stable(feature = "rust1", since = "1.0.0")]
261     pub fn classify(self) -> FpCategory {
262         const EXP_MASK: u32 = 0x7f800000;
263         const MAN_MASK: u32 = 0x007fffff;
264
265         let bits = self.to_bits();
266         match (bits & MAN_MASK, bits & EXP_MASK) {
267             (0, 0) => FpCategory::Zero,
268             (_, 0) => FpCategory::Subnormal,
269             (0, EXP_MASK) => FpCategory::Infinite,
270             (_, EXP_MASK) => FpCategory::Nan,
271             _ => FpCategory::Normal,
272         }
273     }
274
275     /// Returns `true` if `self` has a positive sign, including `+0.0`, `NaN`s with
276     /// positive sign bit and positive infinity.
277     ///
278     /// ```
279     /// let f = 7.0_f32;
280     /// let g = -7.0_f32;
281     ///
282     /// assert!(f.is_sign_positive());
283     /// assert!(!g.is_sign_positive());
284     /// ```
285     #[stable(feature = "rust1", since = "1.0.0")]
286     #[inline]
287     pub fn is_sign_positive(self) -> bool {
288         !self.is_sign_negative()
289     }
290
291     /// Returns `true` if `self` has a negative sign, including `-0.0`, `NaN`s with
292     /// negative sign bit and negative infinity.
293     ///
294     /// ```
295     /// let f = 7.0f32;
296     /// let g = -7.0f32;
297     ///
298     /// assert!(!f.is_sign_negative());
299     /// assert!(g.is_sign_negative());
300     /// ```
301     #[stable(feature = "rust1", since = "1.0.0")]
302     #[inline]
303     pub fn is_sign_negative(self) -> bool {
304         // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
305         // applies to zeros and NaNs as well.
306         self.to_bits() & 0x8000_0000 != 0
307     }
308
309     /// Takes the reciprocal (inverse) of a number, `1/x`.
310     ///
311     /// ```
312     /// use std::f32;
313     ///
314     /// let x = 2.0_f32;
315     /// let abs_difference = (x.recip() - (1.0/x)).abs();
316     ///
317     /// assert!(abs_difference <= f32::EPSILON);
318     /// ```
319     #[stable(feature = "rust1", since = "1.0.0")]
320     #[inline]
321     pub fn recip(self) -> f32 {
322         1.0 / self
323     }
324
325     /// Converts radians to degrees.
326     ///
327     /// ```
328     /// use std::f32::{self, consts};
329     ///
330     /// let angle = consts::PI;
331     ///
332     /// let abs_difference = (angle.to_degrees() - 180.0).abs();
333     ///
334     /// assert!(abs_difference <= f32::EPSILON);
335     /// ```
336     #[stable(feature = "f32_deg_rad_conversions", since="1.7.0")]
337     #[inline]
338     pub fn to_degrees(self) -> f32 {
339         // Use a constant for better precision.
340         const PIS_IN_180: f32 = 57.2957795130823208767981548141051703_f32;
341         self * PIS_IN_180
342     }
343
344     /// Converts degrees to radians.
345     ///
346     /// ```
347     /// use std::f32::{self, consts};
348     ///
349     /// let angle = 180.0f32;
350     ///
351     /// let abs_difference = (angle.to_radians() - consts::PI).abs();
352     ///
353     /// assert!(abs_difference <= f32::EPSILON);
354     /// ```
355     #[stable(feature = "f32_deg_rad_conversions", since="1.7.0")]
356     #[inline]
357     pub fn to_radians(self) -> f32 {
358         let value: f32 = consts::PI;
359         self * (value / 180.0f32)
360     }
361
362     /// Returns the maximum of the two numbers.
363     ///
364     /// ```
365     /// let x = 1.0f32;
366     /// let y = 2.0f32;
367     ///
368     /// assert_eq!(x.max(y), y);
369     /// ```
370     ///
371     /// If one of the arguments is NaN, then the other argument is returned.
372     #[stable(feature = "rust1", since = "1.0.0")]
373     #[inline]
374     pub fn max(self, other: f32) -> f32 {
375         // IEEE754 says: maxNum(x, y) is the canonicalized number y if x < y, x if y < x, the
376         // canonicalized number if one operand is a number and the other a quiet NaN. Otherwise it
377         // is either x or y, canonicalized (this means results might differ among implementations).
378         // When either x or y is a signalingNaN, then the result is according to 6.2.
379         //
380         // Since we do not support sNaN in Rust yet, we do not need to handle them.
381         // FIXME(nagisa): due to https://bugs.llvm.org/show_bug.cgi?id=33303 we canonicalize by
382         // multiplying by 1.0. Should switch to the `canonicalize` when it works.
383         (if self.is_nan() || self < other { other } else { self }) * 1.0
384     }
385
386     /// Returns the minimum of the two numbers.
387     ///
388     /// ```
389     /// let x = 1.0f32;
390     /// let y = 2.0f32;
391     ///
392     /// assert_eq!(x.min(y), x);
393     /// ```
394     ///
395     /// If one of the arguments is NaN, then the other argument is returned.
396     #[stable(feature = "rust1", since = "1.0.0")]
397     #[inline]
398     pub fn min(self, other: f32) -> f32 {
399         // IEEE754 says: minNum(x, y) is the canonicalized number x if x < y, y if y < x, the
400         // canonicalized number if one operand is a number and the other a quiet NaN. Otherwise it
401         // is either x or y, canonicalized (this means results might differ among implementations).
402         // When either x or y is a signalingNaN, then the result is according to 6.2.
403         //
404         // Since we do not support sNaN in Rust yet, we do not need to handle them.
405         // FIXME(nagisa): due to https://bugs.llvm.org/show_bug.cgi?id=33303 we canonicalize by
406         // multiplying by 1.0. Should switch to the `canonicalize` when it works.
407         (if other.is_nan() || self < other { self } else { other }) * 1.0
408     }
409
410     /// Raw transmutation to `u32`.
411     ///
412     /// This is currently identical to `transmute::<f32, u32>(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_ne!((1f32).to_bits(), 1f32 as u32); // to_bits() is not casting!
424     /// assert_eq!((12.5f32).to_bits(), 0x41480000);
425     ///
426     /// ```
427     #[stable(feature = "float_bits_conv", since = "1.20.0")]
428     #[inline]
429     pub fn to_bits(self) -> u32 {
430         unsafe { mem::transmute(self) }
431     }
432
433     /// Raw transmutation from `u32`.
434     ///
435     /// This is currently identical to `transmute::<u32, f32>(v)` on all platforms.
436     /// It turns out this is incredibly portable, for two reasons:
437     ///
438     /// * Floats and Ints have the same endianness on all supported platforms.
439     /// * IEEE-754 very precisely specifies the bit layout of floats.
440     ///
441     /// However there is one caveat: prior to the 2008 version of IEEE-754, how
442     /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
443     /// (notably x86 and ARM) picked the interpretation that was ultimately
444     /// standardized in 2008, but some didn't (notably MIPS). As a result, all
445     /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
446     ///
447     /// Rather than trying to preserve signaling-ness cross-platform, this
448     /// implementation favors preserving the exact bits. This means that
449     /// any payloads encoded in NaNs will be preserved even if the result of
450     /// this method is sent over the network from an x86 machine to a MIPS one.
451     ///
452     /// If the results of this method are only manipulated by the same
453     /// architecture that produced them, then there is no portability concern.
454     ///
455     /// If the input isn't NaN, then there is no portability concern.
456     ///
457     /// If you don't care about signalingness (very likely), then there is no
458     /// portability concern.
459     ///
460     /// Note that this function is distinct from `as` casting, which attempts to
461     /// preserve the *numeric* value, and not the bitwise value.
462     ///
463     /// # Examples
464     ///
465     /// ```
466     /// use std::f32;
467     /// let v = f32::from_bits(0x41480000);
468     /// let difference = (v - 12.5).abs();
469     /// assert!(difference <= 1e-5);
470     /// ```
471     #[stable(feature = "float_bits_conv", since = "1.20.0")]
472     #[inline]
473     pub fn from_bits(v: u32) -> Self {
474         // It turns out the safety issues with sNaN were overblown! Hooray!
475         unsafe { mem::transmute(v) }
476     }
477 }