]> git.lizzy.rs Git - rust.git/blob - library/core/src/num/f32.rs
Automatic exponential formatting in Debug
[rust.git] / library / core / src / num / f32.rs
1 //! Constants specific to the `f32` single-precision floating point type.
2 //!
3 //! *[See also the `f32` primitive type][f32].*
4 //!
5 //! Mathematically significant numbers are provided in the `consts` sub-module.
6 //!
7 //! For the constants defined directly in this module
8 //! (as distinct from those defined in the `consts` sub-module),
9 //! new code should instead use the associated constants
10 //! defined directly on the `f32` type.
11
12 #![stable(feature = "rust1", since = "1.0.0")]
13
14 use crate::convert::FloatToInt;
15 #[cfg(not(test))]
16 use crate::intrinsics;
17 use crate::mem;
18 use crate::num::FpCategory;
19
20 /// The radix or base of the internal representation of `f32`.
21 /// Use [`f32::RADIX`] instead.
22 ///
23 /// # Examples
24 ///
25 /// ```rust
26 /// // deprecated way
27 /// # #[allow(deprecated, deprecated_in_future)]
28 /// let r = std::f32::RADIX;
29 ///
30 /// // intended way
31 /// let r = f32::RADIX;
32 /// ```
33 #[stable(feature = "rust1", since = "1.0.0")]
34 #[rustc_deprecated(since = "TBD", reason = "replaced by the `RADIX` associated constant on `f32`")]
35 pub const RADIX: u32 = f32::RADIX;
36
37 /// Number of significant digits in base 2.
38 /// Use [`f32::MANTISSA_DIGITS`] instead.
39 ///
40 /// # Examples
41 ///
42 /// ```rust
43 /// // deprecated way
44 /// # #[allow(deprecated, deprecated_in_future)]
45 /// let d = std::f32::MANTISSA_DIGITS;
46 ///
47 /// // intended way
48 /// let d = f32::MANTISSA_DIGITS;
49 /// ```
50 #[stable(feature = "rust1", since = "1.0.0")]
51 #[rustc_deprecated(
52     since = "TBD",
53     reason = "replaced by the `MANTISSA_DIGITS` associated constant on `f32`"
54 )]
55 pub const MANTISSA_DIGITS: u32 = f32::MANTISSA_DIGITS;
56
57 /// Approximate number of significant digits in base 10.
58 /// Use [`f32::DIGITS`] instead.
59 ///
60 /// # Examples
61 ///
62 /// ```rust
63 /// // deprecated way
64 /// # #[allow(deprecated, deprecated_in_future)]
65 /// let d = std::f32::DIGITS;
66 ///
67 /// // intended way
68 /// let d = f32::DIGITS;
69 /// ```
70 #[stable(feature = "rust1", since = "1.0.0")]
71 #[rustc_deprecated(since = "TBD", reason = "replaced by the `DIGITS` associated constant on `f32`")]
72 pub const DIGITS: u32 = f32::DIGITS;
73
74 /// [Machine epsilon] value for `f32`.
75 /// Use [`f32::EPSILON`] instead.
76 ///
77 /// This is the difference between `1.0` and the next larger representable number.
78 ///
79 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
80 ///
81 /// # Examples
82 ///
83 /// ```rust
84 /// // deprecated way
85 /// # #[allow(deprecated, deprecated_in_future)]
86 /// let e = std::f32::EPSILON;
87 ///
88 /// // intended way
89 /// let e = f32::EPSILON;
90 /// ```
91 #[stable(feature = "rust1", since = "1.0.0")]
92 #[rustc_deprecated(
93     since = "TBD",
94     reason = "replaced by the `EPSILON` associated constant on `f32`"
95 )]
96 pub const EPSILON: f32 = f32::EPSILON;
97
98 /// Smallest finite `f32` value.
99 /// Use [`f32::MIN`] instead.
100 ///
101 /// # Examples
102 ///
103 /// ```rust
104 /// // deprecated way
105 /// # #[allow(deprecated, deprecated_in_future)]
106 /// let min = std::f32::MIN;
107 ///
108 /// // intended way
109 /// let min = f32::MIN;
110 /// ```
111 #[stable(feature = "rust1", since = "1.0.0")]
112 #[rustc_deprecated(since = "TBD", reason = "replaced by the `MIN` associated constant on `f32`")]
113 pub const MIN: f32 = f32::MIN;
114
115 /// Smallest positive normal `f32` value.
116 /// Use [`f32::MIN_POSITIVE`] instead.
117 ///
118 /// # Examples
119 ///
120 /// ```rust
121 /// // deprecated way
122 /// # #[allow(deprecated, deprecated_in_future)]
123 /// let min = std::f32::MIN_POSITIVE;
124 ///
125 /// // intended way
126 /// let min = f32::MIN_POSITIVE;
127 /// ```
128 #[stable(feature = "rust1", since = "1.0.0")]
129 #[rustc_deprecated(
130     since = "TBD",
131     reason = "replaced by the `MIN_POSITIVE` associated constant on `f32`"
132 )]
133 pub const MIN_POSITIVE: f32 = f32::MIN_POSITIVE;
134
135 /// Largest finite `f32` value.
136 /// Use [`f32::MAX`] instead.
137 ///
138 /// # Examples
139 ///
140 /// ```rust
141 /// // deprecated way
142 /// # #[allow(deprecated, deprecated_in_future)]
143 /// let max = std::f32::MAX;
144 ///
145 /// // intended way
146 /// let max = f32::MAX;
147 /// ```
148 #[stable(feature = "rust1", since = "1.0.0")]
149 #[rustc_deprecated(since = "TBD", reason = "replaced by the `MAX` associated constant on `f32`")]
150 pub const MAX: f32 = f32::MAX;
151
152 /// One greater than the minimum possible normal power of 2 exponent.
153 /// Use [`f32::MIN_EXP`] instead.
154 ///
155 /// # Examples
156 ///
157 /// ```rust
158 /// // deprecated way
159 /// # #[allow(deprecated, deprecated_in_future)]
160 /// let min = std::f32::MIN_EXP;
161 ///
162 /// // intended way
163 /// let min = f32::MIN_EXP;
164 /// ```
165 #[stable(feature = "rust1", since = "1.0.0")]
166 #[rustc_deprecated(
167     since = "TBD",
168     reason = "replaced by the `MIN_EXP` associated constant on `f32`"
169 )]
170 pub const MIN_EXP: i32 = f32::MIN_EXP;
171
172 /// Maximum possible power of 2 exponent.
173 /// Use [`f32::MAX_EXP`] instead.
174 ///
175 /// # Examples
176 ///
177 /// ```rust
178 /// // deprecated way
179 /// # #[allow(deprecated, deprecated_in_future)]
180 /// let max = std::f32::MAX_EXP;
181 ///
182 /// // intended way
183 /// let max = f32::MAX_EXP;
184 /// ```
185 #[stable(feature = "rust1", since = "1.0.0")]
186 #[rustc_deprecated(
187     since = "TBD",
188     reason = "replaced by the `MAX_EXP` associated constant on `f32`"
189 )]
190 pub const MAX_EXP: i32 = f32::MAX_EXP;
191
192 /// Minimum possible normal power of 10 exponent.
193 /// Use [`f32::MIN_10_EXP`] instead.
194 ///
195 /// # Examples
196 ///
197 /// ```rust
198 /// // deprecated way
199 /// # #[allow(deprecated, deprecated_in_future)]
200 /// let min = std::f32::MIN_10_EXP;
201 ///
202 /// // intended way
203 /// let min = f32::MIN_10_EXP;
204 /// ```
205 #[stable(feature = "rust1", since = "1.0.0")]
206 #[rustc_deprecated(
207     since = "TBD",
208     reason = "replaced by the `MIN_10_EXP` associated constant on `f32`"
209 )]
210 pub const MIN_10_EXP: i32 = f32::MIN_10_EXP;
211
212 /// Maximum possible power of 10 exponent.
213 /// Use [`f32::MAX_10_EXP`] instead.
214 ///
215 /// # Examples
216 ///
217 /// ```rust
218 /// // deprecated way
219 /// # #[allow(deprecated, deprecated_in_future)]
220 /// let max = std::f32::MAX_10_EXP;
221 ///
222 /// // intended way
223 /// let max = f32::MAX_10_EXP;
224 /// ```
225 #[stable(feature = "rust1", since = "1.0.0")]
226 #[rustc_deprecated(
227     since = "TBD",
228     reason = "replaced by the `MAX_10_EXP` associated constant on `f32`"
229 )]
230 pub const MAX_10_EXP: i32 = f32::MAX_10_EXP;
231
232 /// Not a Number (NaN).
233 /// Use [`f32::NAN`] instead.
234 ///
235 /// # Examples
236 ///
237 /// ```rust
238 /// // deprecated way
239 /// # #[allow(deprecated, deprecated_in_future)]
240 /// let nan = std::f32::NAN;
241 ///
242 /// // intended way
243 /// let nan = f32::NAN;
244 /// ```
245 #[stable(feature = "rust1", since = "1.0.0")]
246 #[rustc_deprecated(since = "TBD", reason = "replaced by the `NAN` associated constant on `f32`")]
247 pub const NAN: f32 = f32::NAN;
248
249 /// Infinity (∞).
250 /// Use [`f32::INFINITY`] instead.
251 ///
252 /// # Examples
253 ///
254 /// ```rust
255 /// // deprecated way
256 /// # #[allow(deprecated, deprecated_in_future)]
257 /// let inf = std::f32::INFINITY;
258 ///
259 /// // intended way
260 /// let inf = f32::INFINITY;
261 /// ```
262 #[stable(feature = "rust1", since = "1.0.0")]
263 #[rustc_deprecated(
264     since = "TBD",
265     reason = "replaced by the `INFINITY` associated constant on `f32`"
266 )]
267 pub const INFINITY: f32 = f32::INFINITY;
268
269 /// Negative infinity (−∞).
270 /// Use [`f32::NEG_INFINITY`] instead.
271 ///
272 /// # Examples
273 ///
274 /// ```rust
275 /// // deprecated way
276 /// # #[allow(deprecated, deprecated_in_future)]
277 /// let ninf = std::f32::NEG_INFINITY;
278 ///
279 /// // intended way
280 /// let ninf = f32::NEG_INFINITY;
281 /// ```
282 #[stable(feature = "rust1", since = "1.0.0")]
283 #[rustc_deprecated(
284     since = "TBD",
285     reason = "replaced by the `NEG_INFINITY` associated constant on `f32`"
286 )]
287 pub const NEG_INFINITY: f32 = f32::NEG_INFINITY;
288
289 /// Basic mathematical constants.
290 #[stable(feature = "rust1", since = "1.0.0")]
291 pub mod consts {
292     // FIXME: replace with mathematical constants from cmath.
293
294     /// Archimedes' constant (π)
295     #[stable(feature = "rust1", since = "1.0.0")]
296     pub const PI: f32 = 3.14159265358979323846264338327950288_f32;
297
298     /// The full circle constant (τ)
299     ///
300     /// Equal to 2π.
301     #[stable(feature = "tau_constant", since = "1.47.0")]
302     pub const TAU: f32 = 6.28318530717958647692528676655900577_f32;
303
304     /// π/2
305     #[stable(feature = "rust1", since = "1.0.0")]
306     pub const FRAC_PI_2: f32 = 1.57079632679489661923132169163975144_f32;
307
308     /// π/3
309     #[stable(feature = "rust1", since = "1.0.0")]
310     pub const FRAC_PI_3: f32 = 1.04719755119659774615421446109316763_f32;
311
312     /// π/4
313     #[stable(feature = "rust1", since = "1.0.0")]
314     pub const FRAC_PI_4: f32 = 0.785398163397448309615660845819875721_f32;
315
316     /// π/6
317     #[stable(feature = "rust1", since = "1.0.0")]
318     pub const FRAC_PI_6: f32 = 0.52359877559829887307710723054658381_f32;
319
320     /// π/8
321     #[stable(feature = "rust1", since = "1.0.0")]
322     pub const FRAC_PI_8: f32 = 0.39269908169872415480783042290993786_f32;
323
324     /// 1/π
325     #[stable(feature = "rust1", since = "1.0.0")]
326     pub const FRAC_1_PI: f32 = 0.318309886183790671537767526745028724_f32;
327
328     /// 2/π
329     #[stable(feature = "rust1", since = "1.0.0")]
330     pub const FRAC_2_PI: f32 = 0.636619772367581343075535053490057448_f32;
331
332     /// 2/sqrt(π)
333     #[stable(feature = "rust1", since = "1.0.0")]
334     pub const FRAC_2_SQRT_PI: f32 = 1.12837916709551257389615890312154517_f32;
335
336     /// sqrt(2)
337     #[stable(feature = "rust1", since = "1.0.0")]
338     pub const SQRT_2: f32 = 1.41421356237309504880168872420969808_f32;
339
340     /// 1/sqrt(2)
341     #[stable(feature = "rust1", since = "1.0.0")]
342     pub const FRAC_1_SQRT_2: f32 = 0.707106781186547524400844362104849039_f32;
343
344     /// Euler's number (e)
345     #[stable(feature = "rust1", since = "1.0.0")]
346     pub const E: f32 = 2.71828182845904523536028747135266250_f32;
347
348     /// log<sub>2</sub>(e)
349     #[stable(feature = "rust1", since = "1.0.0")]
350     pub const LOG2_E: f32 = 1.44269504088896340735992468100189214_f32;
351
352     /// log<sub>2</sub>(10)
353     #[stable(feature = "extra_log_consts", since = "1.43.0")]
354     pub const LOG2_10: f32 = 3.32192809488736234787031942948939018_f32;
355
356     /// log<sub>10</sub>(e)
357     #[stable(feature = "rust1", since = "1.0.0")]
358     pub const LOG10_E: f32 = 0.434294481903251827651128918916605082_f32;
359
360     /// log<sub>10</sub>(2)
361     #[stable(feature = "extra_log_consts", since = "1.43.0")]
362     pub const LOG10_2: f32 = 0.301029995663981195213738894724493027_f32;
363
364     /// ln(2)
365     #[stable(feature = "rust1", since = "1.0.0")]
366     pub const LN_2: f32 = 0.693147180559945309417232121458176568_f32;
367
368     /// ln(10)
369     #[stable(feature = "rust1", since = "1.0.0")]
370     pub const LN_10: f32 = 2.30258509299404568401799145468436421_f32;
371 }
372
373 #[lang = "f32"]
374 #[cfg(not(test))]
375 impl f32 {
376     /// The radix or base of the internal representation of `f32`.
377     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
378     pub const RADIX: u32 = 2;
379
380     /// Number of significant digits in base 2.
381     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
382     pub const MANTISSA_DIGITS: u32 = 24;
383
384     /// Approximate number of significant digits in base 10.
385     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
386     pub const DIGITS: u32 = 6;
387
388     /// [Machine epsilon] value for `f32`.
389     ///
390     /// This is the difference between `1.0` and the next larger representable number.
391     ///
392     /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
393     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
394     pub const EPSILON: f32 = 1.19209290e-07_f32;
395
396     /// Smallest finite `f32` value.
397     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
398     pub const MIN: f32 = -3.40282347e+38_f32;
399     /// Smallest positive normal `f32` value.
400     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
401     pub const MIN_POSITIVE: f32 = 1.17549435e-38_f32;
402     /// Largest finite `f32` value.
403     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
404     pub const MAX: f32 = 3.40282347e+38_f32;
405
406     /// One greater than the minimum possible normal power of 2 exponent.
407     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
408     pub const MIN_EXP: i32 = -125;
409     /// Maximum possible power of 2 exponent.
410     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
411     pub const MAX_EXP: i32 = 128;
412
413     /// Minimum possible normal power of 10 exponent.
414     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
415     pub const MIN_10_EXP: i32 = -37;
416     /// Maximum possible power of 10 exponent.
417     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
418     pub const MAX_10_EXP: i32 = 38;
419
420     /// Not a Number (NaN).
421     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
422     pub const NAN: f32 = 0.0_f32 / 0.0_f32;
423     /// Infinity (∞).
424     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
425     pub const INFINITY: f32 = 1.0_f32 / 0.0_f32;
426     /// Negative infinity (−∞).
427     #[stable(feature = "assoc_int_consts", since = "1.43.0")]
428     pub const NEG_INFINITY: f32 = -1.0_f32 / 0.0_f32;
429
430     /// Returns `true` if this value is `NaN`.
431     ///
432     /// ```
433     /// let nan = f32::NAN;
434     /// let f = 7.0_f32;
435     ///
436     /// assert!(nan.is_nan());
437     /// assert!(!f.is_nan());
438     /// ```
439     #[stable(feature = "rust1", since = "1.0.0")]
440     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
441     #[inline]
442     pub const fn is_nan(self) -> bool {
443         self != self
444     }
445
446     // FIXME(#50145): `abs` is publicly unavailable in libcore due to
447     // concerns about portability, so this implementation is for
448     // private use internally.
449     #[inline]
450     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
451     pub(crate) const fn abs_private(self) -> f32 {
452         f32::from_bits(self.to_bits() & 0x7fff_ffff)
453     }
454
455     /// Returns `true` if this value is positive infinity or negative infinity, and
456     /// `false` otherwise.
457     ///
458     /// ```
459     /// let f = 7.0f32;
460     /// let inf = f32::INFINITY;
461     /// let neg_inf = f32::NEG_INFINITY;
462     /// let nan = f32::NAN;
463     ///
464     /// assert!(!f.is_infinite());
465     /// assert!(!nan.is_infinite());
466     ///
467     /// assert!(inf.is_infinite());
468     /// assert!(neg_inf.is_infinite());
469     /// ```
470     #[stable(feature = "rust1", since = "1.0.0")]
471     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
472     #[inline]
473     pub const fn is_infinite(self) -> bool {
474         self.abs_private() == Self::INFINITY
475     }
476
477     /// Returns `true` if this number is neither infinite nor `NaN`.
478     ///
479     /// ```
480     /// let f = 7.0f32;
481     /// let inf = f32::INFINITY;
482     /// let neg_inf = f32::NEG_INFINITY;
483     /// let nan = f32::NAN;
484     ///
485     /// assert!(f.is_finite());
486     ///
487     /// assert!(!nan.is_finite());
488     /// assert!(!inf.is_finite());
489     /// assert!(!neg_inf.is_finite());
490     /// ```
491     #[stable(feature = "rust1", since = "1.0.0")]
492     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
493     #[inline]
494     pub const fn is_finite(self) -> bool {
495         // There's no need to handle NaN separately: if self is NaN,
496         // the comparison is not true, exactly as desired.
497         self.abs_private() < Self::INFINITY
498     }
499
500     /// Returns `true` if the number is [subnormal].
501     ///
502     /// ```
503     /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
504     /// let max = f32::MAX;
505     /// let lower_than_min = 1.0e-40_f32;
506     /// let zero = 0.0_f32;
507     ///
508     /// assert!(!min.is_subnormal());
509     /// assert!(!max.is_subnormal());
510     ///
511     /// assert!(!zero.is_subnormal());
512     /// assert!(!f32::NAN.is_subnormal());
513     /// assert!(!f32::INFINITY.is_subnormal());
514     /// // Values between `0` and `min` are Subnormal.
515     /// assert!(lower_than_min.is_subnormal());
516     /// ```
517     /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
518     #[stable(feature = "is_subnormal", since = "1.53.0")]
519     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
520     #[inline]
521     pub const fn is_subnormal(self) -> bool {
522         matches!(self.classify(), FpCategory::Subnormal)
523     }
524
525     /// Returns `true` if the number is neither zero, infinite,
526     /// [subnormal], or `NaN`.
527     ///
528     /// ```
529     /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
530     /// let max = f32::MAX;
531     /// let lower_than_min = 1.0e-40_f32;
532     /// let zero = 0.0_f32;
533     ///
534     /// assert!(min.is_normal());
535     /// assert!(max.is_normal());
536     ///
537     /// assert!(!zero.is_normal());
538     /// assert!(!f32::NAN.is_normal());
539     /// assert!(!f32::INFINITY.is_normal());
540     /// // Values between `0` and `min` are Subnormal.
541     /// assert!(!lower_than_min.is_normal());
542     /// ```
543     /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
544     #[stable(feature = "rust1", since = "1.0.0")]
545     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
546     #[inline]
547     pub const fn is_normal(self) -> bool {
548         matches!(self.classify(), FpCategory::Normal)
549     }
550
551     /// Returns the floating point category of the number. If only one property
552     /// is going to be tested, it is generally faster to use the specific
553     /// predicate instead.
554     ///
555     /// ```
556     /// use std::num::FpCategory;
557     ///
558     /// let num = 12.4_f32;
559     /// let inf = f32::INFINITY;
560     ///
561     /// assert_eq!(num.classify(), FpCategory::Normal);
562     /// assert_eq!(inf.classify(), FpCategory::Infinite);
563     /// ```
564     #[stable(feature = "rust1", since = "1.0.0")]
565     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
566     pub const fn classify(self) -> FpCategory {
567         const EXP_MASK: u32 = 0x7f800000;
568         const MAN_MASK: u32 = 0x007fffff;
569
570         let bits = self.to_bits();
571         match (bits & MAN_MASK, bits & EXP_MASK) {
572             (0, 0) => FpCategory::Zero,
573             (_, 0) => FpCategory::Subnormal,
574             (0, EXP_MASK) => FpCategory::Infinite,
575             (_, EXP_MASK) => FpCategory::Nan,
576             _ => FpCategory::Normal,
577         }
578     }
579
580     /// Returns `true` if `self` has a positive sign, including `+0.0`, `NaN`s with
581     /// positive sign bit and positive infinity.
582     ///
583     /// ```
584     /// let f = 7.0_f32;
585     /// let g = -7.0_f32;
586     ///
587     /// assert!(f.is_sign_positive());
588     /// assert!(!g.is_sign_positive());
589     /// ```
590     #[stable(feature = "rust1", since = "1.0.0")]
591     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
592     #[inline]
593     pub const fn is_sign_positive(self) -> bool {
594         !self.is_sign_negative()
595     }
596
597     /// Returns `true` if `self` has a negative sign, including `-0.0`, `NaN`s with
598     /// negative sign bit and negative infinity.
599     ///
600     /// ```
601     /// let f = 7.0f32;
602     /// let g = -7.0f32;
603     ///
604     /// assert!(!f.is_sign_negative());
605     /// assert!(g.is_sign_negative());
606     /// ```
607     #[stable(feature = "rust1", since = "1.0.0")]
608     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
609     #[inline]
610     pub const fn is_sign_negative(self) -> bool {
611         // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
612         // applies to zeros and NaNs as well.
613         self.to_bits() & 0x8000_0000 != 0
614     }
615
616     /// Takes the reciprocal (inverse) of a number, `1/x`.
617     ///
618     /// ```
619     /// let x = 2.0_f32;
620     /// let abs_difference = (x.recip() - (1.0 / x)).abs();
621     ///
622     /// assert!(abs_difference <= f32::EPSILON);
623     /// ```
624     #[stable(feature = "rust1", since = "1.0.0")]
625     #[inline]
626     pub fn recip(self) -> f32 {
627         1.0 / self
628     }
629
630     /// Converts radians to degrees.
631     ///
632     /// ```
633     /// let angle = std::f32::consts::PI;
634     ///
635     /// let abs_difference = (angle.to_degrees() - 180.0).abs();
636     ///
637     /// assert!(abs_difference <= f32::EPSILON);
638     /// ```
639     #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
640     #[inline]
641     pub fn to_degrees(self) -> f32 {
642         // Use a constant for better precision.
643         const PIS_IN_180: f32 = 57.2957795130823208767981548141051703_f32;
644         self * PIS_IN_180
645     }
646
647     /// Converts degrees to radians.
648     ///
649     /// ```
650     /// let angle = 180.0f32;
651     ///
652     /// let abs_difference = (angle.to_radians() - std::f32::consts::PI).abs();
653     ///
654     /// assert!(abs_difference <= f32::EPSILON);
655     /// ```
656     #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
657     #[inline]
658     pub fn to_radians(self) -> f32 {
659         let value: f32 = consts::PI;
660         self * (value / 180.0f32)
661     }
662
663     /// Returns the maximum of the two numbers.
664     ///
665     /// ```
666     /// let x = 1.0f32;
667     /// let y = 2.0f32;
668     ///
669     /// assert_eq!(x.max(y), y);
670     /// ```
671     ///
672     /// If one of the arguments is NaN, then the other argument is returned.
673     #[stable(feature = "rust1", since = "1.0.0")]
674     #[inline]
675     pub fn max(self, other: f32) -> f32 {
676         intrinsics::maxnumf32(self, other)
677     }
678
679     /// Returns the minimum of the two numbers.
680     ///
681     /// ```
682     /// let x = 1.0f32;
683     /// let y = 2.0f32;
684     ///
685     /// assert_eq!(x.min(y), x);
686     /// ```
687     ///
688     /// If one of the arguments is NaN, then the other argument is returned.
689     #[stable(feature = "rust1", since = "1.0.0")]
690     #[inline]
691     pub fn min(self, other: f32) -> f32 {
692         intrinsics::minnumf32(self, other)
693     }
694
695     /// Rounds toward zero and converts to any primitive integer type,
696     /// assuming that the value is finite and fits in that type.
697     ///
698     /// ```
699     /// let value = 4.6_f32;
700     /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
701     /// assert_eq!(rounded, 4);
702     ///
703     /// let value = -128.9_f32;
704     /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
705     /// assert_eq!(rounded, i8::MIN);
706     /// ```
707     ///
708     /// # Safety
709     ///
710     /// The value must:
711     ///
712     /// * Not be `NaN`
713     /// * Not be infinite
714     /// * Be representable in the return type `Int`, after truncating off its fractional part
715     #[stable(feature = "float_approx_unchecked_to", since = "1.44.0")]
716     #[inline]
717     pub unsafe fn to_int_unchecked<Int>(self) -> Int
718     where
719         Self: FloatToInt<Int>,
720     {
721         // SAFETY: the caller must uphold the safety contract for
722         // `FloatToInt::to_int_unchecked`.
723         unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
724     }
725
726     /// Raw transmutation to `u32`.
727     ///
728     /// This is currently identical to `transmute::<f32, u32>(self)` on all platforms.
729     ///
730     /// See [`from_bits`](Self::from_bits) for some discussion of the
731     /// portability of this operation (there are almost no issues).
732     ///
733     /// Note that this function is distinct from `as` casting, which attempts to
734     /// preserve the *numeric* value, and not the bitwise value.
735     ///
736     /// # Examples
737     ///
738     /// ```
739     /// assert_ne!((1f32).to_bits(), 1f32 as u32); // to_bits() is not casting!
740     /// assert_eq!((12.5f32).to_bits(), 0x41480000);
741     ///
742     /// ```
743     #[stable(feature = "float_bits_conv", since = "1.20.0")]
744     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
745     #[inline]
746     pub const fn to_bits(self) -> u32 {
747         // SAFETY: `u32` is a plain old datatype so we can always transmute to it
748         unsafe { mem::transmute(self) }
749     }
750
751     /// Raw transmutation from `u32`.
752     ///
753     /// This is currently identical to `transmute::<u32, f32>(v)` on all platforms.
754     /// It turns out this is incredibly portable, for two reasons:
755     ///
756     /// * Floats and Ints have the same endianness on all supported platforms.
757     /// * IEEE-754 very precisely specifies the bit layout of floats.
758     ///
759     /// However there is one caveat: prior to the 2008 version of IEEE-754, how
760     /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
761     /// (notably x86 and ARM) picked the interpretation that was ultimately
762     /// standardized in 2008, but some didn't (notably MIPS). As a result, all
763     /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
764     ///
765     /// Rather than trying to preserve signaling-ness cross-platform, this
766     /// implementation favors preserving the exact bits. This means that
767     /// any payloads encoded in NaNs will be preserved even if the result of
768     /// this method is sent over the network from an x86 machine to a MIPS one.
769     ///
770     /// If the results of this method are only manipulated by the same
771     /// architecture that produced them, then there is no portability concern.
772     ///
773     /// If the input isn't NaN, then there is no portability concern.
774     ///
775     /// If you don't care about signalingness (very likely), then there is no
776     /// portability concern.
777     ///
778     /// Note that this function is distinct from `as` casting, which attempts to
779     /// preserve the *numeric* value, and not the bitwise value.
780     ///
781     /// # Examples
782     ///
783     /// ```
784     /// let v = f32::from_bits(0x41480000);
785     /// assert_eq!(v, 12.5);
786     /// ```
787     #[stable(feature = "float_bits_conv", since = "1.20.0")]
788     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
789     #[inline]
790     pub const fn from_bits(v: u32) -> Self {
791         // SAFETY: `u32` is a plain old datatype so we can always transmute from it
792         // It turns out the safety issues with sNaN were overblown! Hooray!
793         unsafe { mem::transmute(v) }
794     }
795
796     /// Return the memory representation of this floating point number as a byte array in
797     /// big-endian (network) byte order.
798     ///
799     /// # Examples
800     ///
801     /// ```
802     /// let bytes = 12.5f32.to_be_bytes();
803     /// assert_eq!(bytes, [0x41, 0x48, 0x00, 0x00]);
804     /// ```
805     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
806     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
807     #[inline]
808     pub const fn to_be_bytes(self) -> [u8; 4] {
809         self.to_bits().to_be_bytes()
810     }
811
812     /// Return the memory representation of this floating point number as a byte array in
813     /// little-endian byte order.
814     ///
815     /// # Examples
816     ///
817     /// ```
818     /// let bytes = 12.5f32.to_le_bytes();
819     /// assert_eq!(bytes, [0x00, 0x00, 0x48, 0x41]);
820     /// ```
821     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
822     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
823     #[inline]
824     pub const fn to_le_bytes(self) -> [u8; 4] {
825         self.to_bits().to_le_bytes()
826     }
827
828     /// Return the memory representation of this floating point number as a byte array in
829     /// native byte order.
830     ///
831     /// As the target platform's native endianness is used, portable code
832     /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
833     ///
834     /// [`to_be_bytes`]: f32::to_be_bytes
835     /// [`to_le_bytes`]: f32::to_le_bytes
836     ///
837     /// # Examples
838     ///
839     /// ```
840     /// let bytes = 12.5f32.to_ne_bytes();
841     /// assert_eq!(
842     ///     bytes,
843     ///     if cfg!(target_endian = "big") {
844     ///         [0x41, 0x48, 0x00, 0x00]
845     ///     } else {
846     ///         [0x00, 0x00, 0x48, 0x41]
847     ///     }
848     /// );
849     /// ```
850     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
851     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
852     #[inline]
853     pub const fn to_ne_bytes(self) -> [u8; 4] {
854         self.to_bits().to_ne_bytes()
855     }
856
857     /// Create a floating point value from its representation as a byte array in big endian.
858     ///
859     /// # Examples
860     ///
861     /// ```
862     /// let value = f32::from_be_bytes([0x41, 0x48, 0x00, 0x00]);
863     /// assert_eq!(value, 12.5);
864     /// ```
865     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
866     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
867     #[inline]
868     pub const fn from_be_bytes(bytes: [u8; 4]) -> Self {
869         Self::from_bits(u32::from_be_bytes(bytes))
870     }
871
872     /// Create a floating point value from its representation as a byte array in little endian.
873     ///
874     /// # Examples
875     ///
876     /// ```
877     /// let value = f32::from_le_bytes([0x00, 0x00, 0x48, 0x41]);
878     /// assert_eq!(value, 12.5);
879     /// ```
880     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
881     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
882     #[inline]
883     pub const fn from_le_bytes(bytes: [u8; 4]) -> Self {
884         Self::from_bits(u32::from_le_bytes(bytes))
885     }
886
887     /// Create a floating point value from its representation as a byte array in native endian.
888     ///
889     /// As the target platform's native endianness is used, portable code
890     /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
891     /// appropriate instead.
892     ///
893     /// [`from_be_bytes`]: f32::from_be_bytes
894     /// [`from_le_bytes`]: f32::from_le_bytes
895     ///
896     /// # Examples
897     ///
898     /// ```
899     /// let value = f32::from_ne_bytes(if cfg!(target_endian = "big") {
900     ///     [0x41, 0x48, 0x00, 0x00]
901     /// } else {
902     ///     [0x00, 0x00, 0x48, 0x41]
903     /// });
904     /// assert_eq!(value, 12.5);
905     /// ```
906     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
907     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
908     #[inline]
909     pub const fn from_ne_bytes(bytes: [u8; 4]) -> Self {
910         Self::from_bits(u32::from_ne_bytes(bytes))
911     }
912
913     /// Returns an ordering between self and other values.
914     /// Unlike the standard partial comparison between floating point numbers,
915     /// this comparison always produces an ordering in accordance to
916     /// the totalOrder predicate as defined in IEEE 754 (2008 revision)
917     /// floating point standard. The values are ordered in following order:
918     /// - Negative quiet NaN
919     /// - Negative signaling NaN
920     /// - Negative infinity
921     /// - Negative numbers
922     /// - Negative subnormal numbers
923     /// - Negative zero
924     /// - Positive zero
925     /// - Positive subnormal numbers
926     /// - Positive numbers
927     /// - Positive infinity
928     /// - Positive signaling NaN
929     /// - Positive quiet NaN
930     ///
931     /// Note that this function does not always agree with the [`PartialOrd`]
932     /// and [`PartialEq`] implementations of `f32`. In particular, they regard
933     /// negative and positive zero as equal, while `total_cmp` doesn't.
934     ///
935     /// # Example
936     /// ```
937     /// #![feature(total_cmp)]
938     /// struct GoodBoy {
939     ///     name: String,
940     ///     weight: f32,
941     /// }
942     ///
943     /// let mut bois = vec![
944     ///     GoodBoy { name: "Pucci".to_owned(), weight: 0.1 },
945     ///     GoodBoy { name: "Woofer".to_owned(), weight: 99.0 },
946     ///     GoodBoy { name: "Yapper".to_owned(), weight: 10.0 },
947     ///     GoodBoy { name: "Chonk".to_owned(), weight: f32::INFINITY },
948     ///     GoodBoy { name: "Abs. Unit".to_owned(), weight: f32::NAN },
949     ///     GoodBoy { name: "Floaty".to_owned(), weight: -5.0 },
950     /// ];
951     ///
952     /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
953     /// # assert!(bois.into_iter().map(|b| b.weight)
954     /// #     .zip([-5.0, 0.1, 10.0, 99.0, f32::INFINITY, f32::NAN].iter())
955     /// #     .all(|(a, b)| a.to_bits() == b.to_bits()))
956     /// ```
957     #[unstable(feature = "total_cmp", issue = "72599")]
958     #[inline]
959     pub fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
960         let mut left = self.to_bits() as i32;
961         let mut right = other.to_bits() as i32;
962
963         // In case of negatives, flip all the bits except the sign
964         // to achieve a similar layout as two's complement integers
965         //
966         // Why does this work? IEEE 754 floats consist of three fields:
967         // Sign bit, exponent and mantissa. The set of exponent and mantissa
968         // fields as a whole have the property that their bitwise order is
969         // equal to the numeric magnitude where the magnitude is defined.
970         // The magnitude is not normally defined on NaN values, but
971         // IEEE 754 totalOrder defines the NaN values also to follow the
972         // bitwise order. This leads to order explained in the doc comment.
973         // However, the representation of magnitude is the same for negative
974         // and positive numbers – only the sign bit is different.
975         // To easily compare the floats as signed integers, we need to
976         // flip the exponent and mantissa bits in case of negative numbers.
977         // We effectively convert the numbers to "two's complement" form.
978         //
979         // To do the flipping, we construct a mask and XOR against it.
980         // We branchlessly calculate an "all-ones except for the sign bit"
981         // mask from negative-signed values: right shifting sign-extends
982         // the integer, so we "fill" the mask with sign bits, and then
983         // convert to unsigned to push one more zero bit.
984         // On positive values, the mask is all zeros, so it's a no-op.
985         left ^= (((left >> 31) as u32) >> 1) as i32;
986         right ^= (((right >> 31) as u32) >> 1) as i32;
987
988         left.cmp(&right)
989     }
990
991     /// Restrict a value to a certain interval unless it is NaN.
992     ///
993     /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
994     /// less than `min`. Otherwise this returns `self`.
995     ///
996     /// Note that this function returns NaN if the initial value was NaN as
997     /// well.
998     ///
999     /// # Panics
1000     ///
1001     /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1002     ///
1003     /// # Examples
1004     ///
1005     /// ```
1006     /// assert!((-3.0f32).clamp(-2.0, 1.0) == -2.0);
1007     /// assert!((0.0f32).clamp(-2.0, 1.0) == 0.0);
1008     /// assert!((2.0f32).clamp(-2.0, 1.0) == 1.0);
1009     /// assert!((f32::NAN).clamp(-2.0, 1.0).is_nan());
1010     /// ```
1011     #[must_use = "method returns a new number and does not mutate the original value"]
1012     #[stable(feature = "clamp", since = "1.50.0")]
1013     #[inline]
1014     pub fn clamp(self, min: f32, max: f32) -> f32 {
1015         assert!(min <= max);
1016         let mut x = self;
1017         if x < min {
1018             x = min;
1019         }
1020         if x > max {
1021             x = max;
1022         }
1023         x
1024     }
1025 }