]> git.lizzy.rs Git - rust.git/blob - library/core/src/num/f32.rs
c4a232ef36c615c5010557afefa93358552a8adf
[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     #[must_use]
440     #[stable(feature = "rust1", since = "1.0.0")]
441     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
442     #[inline]
443     pub const fn is_nan(self) -> bool {
444         self != self
445     }
446
447     // FIXME(#50145): `abs` is publicly unavailable in libcore due to
448     // concerns about portability, so this implementation is for
449     // private use internally.
450     #[inline]
451     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
452     pub(crate) const fn abs_private(self) -> f32 {
453         f32::from_bits(self.to_bits() & 0x7fff_ffff)
454     }
455
456     /// Returns `true` if this value is positive infinity or negative infinity, and
457     /// `false` otherwise.
458     ///
459     /// ```
460     /// let f = 7.0f32;
461     /// let inf = f32::INFINITY;
462     /// let neg_inf = f32::NEG_INFINITY;
463     /// let nan = f32::NAN;
464     ///
465     /// assert!(!f.is_infinite());
466     /// assert!(!nan.is_infinite());
467     ///
468     /// assert!(inf.is_infinite());
469     /// assert!(neg_inf.is_infinite());
470     /// ```
471     #[must_use]
472     #[stable(feature = "rust1", since = "1.0.0")]
473     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
474     #[inline]
475     pub const fn is_infinite(self) -> bool {
476         self.abs_private() == Self::INFINITY
477     }
478
479     /// Returns `true` if this number is neither infinite nor `NaN`.
480     ///
481     /// ```
482     /// let f = 7.0f32;
483     /// let inf = f32::INFINITY;
484     /// let neg_inf = f32::NEG_INFINITY;
485     /// let nan = f32::NAN;
486     ///
487     /// assert!(f.is_finite());
488     ///
489     /// assert!(!nan.is_finite());
490     /// assert!(!inf.is_finite());
491     /// assert!(!neg_inf.is_finite());
492     /// ```
493     #[must_use]
494     #[stable(feature = "rust1", since = "1.0.0")]
495     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
496     #[inline]
497     pub const fn is_finite(self) -> bool {
498         // There's no need to handle NaN separately: if self is NaN,
499         // the comparison is not true, exactly as desired.
500         self.abs_private() < Self::INFINITY
501     }
502
503     /// Returns `true` if the number is [subnormal].
504     ///
505     /// ```
506     /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
507     /// let max = f32::MAX;
508     /// let lower_than_min = 1.0e-40_f32;
509     /// let zero = 0.0_f32;
510     ///
511     /// assert!(!min.is_subnormal());
512     /// assert!(!max.is_subnormal());
513     ///
514     /// assert!(!zero.is_subnormal());
515     /// assert!(!f32::NAN.is_subnormal());
516     /// assert!(!f32::INFINITY.is_subnormal());
517     /// // Values between `0` and `min` are Subnormal.
518     /// assert!(lower_than_min.is_subnormal());
519     /// ```
520     /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
521     #[must_use]
522     #[stable(feature = "is_subnormal", since = "1.53.0")]
523     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
524     #[inline]
525     pub const fn is_subnormal(self) -> bool {
526         matches!(self.classify(), FpCategory::Subnormal)
527     }
528
529     /// Returns `true` if the number is neither zero, infinite,
530     /// [subnormal], or `NaN`.
531     ///
532     /// ```
533     /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
534     /// let max = f32::MAX;
535     /// let lower_than_min = 1.0e-40_f32;
536     /// let zero = 0.0_f32;
537     ///
538     /// assert!(min.is_normal());
539     /// assert!(max.is_normal());
540     ///
541     /// assert!(!zero.is_normal());
542     /// assert!(!f32::NAN.is_normal());
543     /// assert!(!f32::INFINITY.is_normal());
544     /// // Values between `0` and `min` are Subnormal.
545     /// assert!(!lower_than_min.is_normal());
546     /// ```
547     /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
548     #[must_use]
549     #[stable(feature = "rust1", since = "1.0.0")]
550     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
551     #[inline]
552     pub const fn is_normal(self) -> bool {
553         matches!(self.classify(), FpCategory::Normal)
554     }
555
556     /// Returns the floating point category of the number. If only one property
557     /// is going to be tested, it is generally faster to use the specific
558     /// predicate instead.
559     ///
560     /// ```
561     /// use std::num::FpCategory;
562     ///
563     /// let num = 12.4_f32;
564     /// let inf = f32::INFINITY;
565     ///
566     /// assert_eq!(num.classify(), FpCategory::Normal);
567     /// assert_eq!(inf.classify(), FpCategory::Infinite);
568     /// ```
569     #[stable(feature = "rust1", since = "1.0.0")]
570     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
571     pub const fn classify(self) -> FpCategory {
572         const EXP_MASK: u32 = 0x7f800000;
573         const MAN_MASK: u32 = 0x007fffff;
574
575         let bits = self.to_bits();
576         match (bits & MAN_MASK, bits & EXP_MASK) {
577             (0, 0) => FpCategory::Zero,
578             (_, 0) => FpCategory::Subnormal,
579             (0, EXP_MASK) => FpCategory::Infinite,
580             (_, EXP_MASK) => FpCategory::Nan,
581             _ => FpCategory::Normal,
582         }
583     }
584
585     /// Returns `true` if `self` has a positive sign, including `+0.0`, `NaN`s with
586     /// positive sign bit and positive infinity.
587     ///
588     /// ```
589     /// let f = 7.0_f32;
590     /// let g = -7.0_f32;
591     ///
592     /// assert!(f.is_sign_positive());
593     /// assert!(!g.is_sign_positive());
594     /// ```
595     #[must_use]
596     #[stable(feature = "rust1", since = "1.0.0")]
597     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
598     #[inline]
599     pub const fn is_sign_positive(self) -> bool {
600         !self.is_sign_negative()
601     }
602
603     /// Returns `true` if `self` has a negative sign, including `-0.0`, `NaN`s with
604     /// negative sign bit and negative infinity.
605     ///
606     /// ```
607     /// let f = 7.0f32;
608     /// let g = -7.0f32;
609     ///
610     /// assert!(!f.is_sign_negative());
611     /// assert!(g.is_sign_negative());
612     /// ```
613     #[must_use]
614     #[stable(feature = "rust1", since = "1.0.0")]
615     #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
616     #[inline]
617     pub const fn is_sign_negative(self) -> bool {
618         // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
619         // applies to zeros and NaNs as well.
620         self.to_bits() & 0x8000_0000 != 0
621     }
622
623     /// Takes the reciprocal (inverse) of a number, `1/x`.
624     ///
625     /// ```
626     /// let x = 2.0_f32;
627     /// let abs_difference = (x.recip() - (1.0 / x)).abs();
628     ///
629     /// assert!(abs_difference <= f32::EPSILON);
630     /// ```
631     #[stable(feature = "rust1", since = "1.0.0")]
632     #[inline]
633     pub fn recip(self) -> f32 {
634         1.0 / self
635     }
636
637     /// Converts radians to degrees.
638     ///
639     /// ```
640     /// let angle = std::f32::consts::PI;
641     ///
642     /// let abs_difference = (angle.to_degrees() - 180.0).abs();
643     ///
644     /// assert!(abs_difference <= f32::EPSILON);
645     /// ```
646     #[must_use = "this returns the result of the operation, \
647                   without modifying the original"]
648     #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
649     #[inline]
650     pub fn to_degrees(self) -> f32 {
651         // Use a constant for better precision.
652         const PIS_IN_180: f32 = 57.2957795130823208767981548141051703_f32;
653         self * PIS_IN_180
654     }
655
656     /// Converts degrees to radians.
657     ///
658     /// ```
659     /// let angle = 180.0f32;
660     ///
661     /// let abs_difference = (angle.to_radians() - std::f32::consts::PI).abs();
662     ///
663     /// assert!(abs_difference <= f32::EPSILON);
664     /// ```
665     #[must_use = "this returns the result of the operation, \
666                   without modifying the original"]
667     #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
668     #[inline]
669     pub fn to_radians(self) -> f32 {
670         let value: f32 = consts::PI;
671         self * (value / 180.0f32)
672     }
673
674     /// Returns the maximum of the two numbers.
675     ///
676     /// Follows the IEEE-754 2008 semantics for maxNum, except for handling of signaling NaNs.
677     /// This matches the behavior of libm’s fmin.
678     ///
679     /// ```
680     /// let x = 1.0f32;
681     /// let y = 2.0f32;
682     ///
683     /// assert_eq!(x.max(y), y);
684     /// ```
685     ///
686     /// If one of the arguments is NaN, then the other argument is returned.
687     #[stable(feature = "rust1", since = "1.0.0")]
688     #[inline]
689     pub fn max(self, other: f32) -> f32 {
690         intrinsics::maxnumf32(self, other)
691     }
692
693     /// Returns the minimum of the two numbers.
694     ///
695     /// Follows the IEEE-754 2008 semantics for minNum, except for handling of signaling NaNs.
696     /// This matches the behavior of libm’s fmin.
697     ///
698     /// ```
699     /// let x = 1.0f32;
700     /// let y = 2.0f32;
701     ///
702     /// assert_eq!(x.min(y), x);
703     /// ```
704     ///
705     /// If one of the arguments is NaN, then the other argument is returned.
706     #[stable(feature = "rust1", since = "1.0.0")]
707     #[inline]
708     pub fn min(self, other: f32) -> f32 {
709         intrinsics::minnumf32(self, other)
710     }
711
712     /// Returns the maximum of the two numbers, propagating NaNs.
713     ///
714     /// This returns NaN when *either* argument is NaN, as opposed to
715     /// [`f32::max`] which only returns NaN when *both* arguments are NaN.
716     ///
717     /// ```
718     /// #![feature(float_minimum_maximum)]
719     /// let x = 1.0f32;
720     /// let y = 2.0f32;
721     ///
722     /// assert_eq!(x.maximum(y), y);
723     /// assert!(x.maximum(f32::NAN).is_nan());
724     /// ```
725     ///
726     /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the greater
727     /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
728     /// Note that this follows the semantics specified in IEEE 754-2019.
729     #[unstable(feature = "float_minimum_maximum", issue = "91079")]
730     #[inline]
731     pub fn maximum(self, other: f32) -> f32 {
732         if self > other {
733             self
734         } else if other > self {
735             other
736         } else if self == other {
737             if self.is_sign_positive() && other.is_sign_negative() { self } else { other }
738         } else {
739             self + other
740         }
741     }
742
743     /// Returns the minimum of the two numbers, propagating NaNs.
744     ///
745     /// This returns NaN when *either* argument is NaN, as opposed to
746     /// [`f32::min`] which only returns NaN when *both* arguments are NaN.
747     ///
748     /// ```
749     /// #![feature(float_minimum_maximum)]
750     /// let x = 1.0f32;
751     /// let y = 2.0f32;
752     ///
753     /// assert_eq!(x.minimum(y), x);
754     /// assert!(x.minimum(f32::NAN).is_nan());
755     /// ```
756     ///
757     /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the lesser
758     /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
759     /// Note that this follows the semantics specified in IEEE 754-2019.
760     #[unstable(feature = "float_minimum_maximum", issue = "91079")]
761     #[inline]
762     pub fn minimum(self, other: f32) -> f32 {
763         if self < other {
764             self
765         } else if other < self {
766             other
767         } else if self == other {
768             if self.is_sign_negative() && other.is_sign_positive() { self } else { other }
769         } else {
770             self + other
771         }
772     }
773
774     /// Rounds toward zero and converts to any primitive integer type,
775     /// assuming that the value is finite and fits in that type.
776     ///
777     /// ```
778     /// let value = 4.6_f32;
779     /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
780     /// assert_eq!(rounded, 4);
781     ///
782     /// let value = -128.9_f32;
783     /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
784     /// assert_eq!(rounded, i8::MIN);
785     /// ```
786     ///
787     /// # Safety
788     ///
789     /// The value must:
790     ///
791     /// * Not be `NaN`
792     /// * Not be infinite
793     /// * Be representable in the return type `Int`, after truncating off its fractional part
794     #[must_use = "this returns the result of the operation, \
795                   without modifying the original"]
796     #[stable(feature = "float_approx_unchecked_to", since = "1.44.0")]
797     #[inline]
798     pub unsafe fn to_int_unchecked<Int>(self) -> Int
799     where
800         Self: FloatToInt<Int>,
801     {
802         // SAFETY: the caller must uphold the safety contract for
803         // `FloatToInt::to_int_unchecked`.
804         unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
805     }
806
807     /// Raw transmutation to `u32`.
808     ///
809     /// This is currently identical to `transmute::<f32, u32>(self)` on all platforms.
810     ///
811     /// See [`from_bits`](Self::from_bits) for some discussion of the
812     /// portability of this operation (there are almost no issues).
813     ///
814     /// Note that this function is distinct from `as` casting, which attempts to
815     /// preserve the *numeric* value, and not the bitwise value.
816     ///
817     /// # Examples
818     ///
819     /// ```
820     /// assert_ne!((1f32).to_bits(), 1f32 as u32); // to_bits() is not casting!
821     /// assert_eq!((12.5f32).to_bits(), 0x41480000);
822     ///
823     /// ```
824     #[must_use = "this returns the result of the operation, \
825                   without modifying the original"]
826     #[stable(feature = "float_bits_conv", since = "1.20.0")]
827     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
828     #[inline]
829     pub const fn to_bits(self) -> u32 {
830         // SAFETY: `u32` is a plain old datatype so we can always transmute to it
831         unsafe { mem::transmute(self) }
832     }
833
834     /// Raw transmutation from `u32`.
835     ///
836     /// This is currently identical to `transmute::<u32, f32>(v)` on all platforms.
837     /// It turns out this is incredibly portable, for two reasons:
838     ///
839     /// * Floats and Ints have the same endianness on all supported platforms.
840     /// * IEEE-754 very precisely specifies the bit layout of floats.
841     ///
842     /// However there is one caveat: prior to the 2008 version of IEEE-754, how
843     /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
844     /// (notably x86 and ARM) picked the interpretation that was ultimately
845     /// standardized in 2008, but some didn't (notably MIPS). As a result, all
846     /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
847     ///
848     /// Rather than trying to preserve signaling-ness cross-platform, this
849     /// implementation favors preserving the exact bits. This means that
850     /// any payloads encoded in NaNs will be preserved even if the result of
851     /// this method is sent over the network from an x86 machine to a MIPS one.
852     ///
853     /// If the results of this method are only manipulated by the same
854     /// architecture that produced them, then there is no portability concern.
855     ///
856     /// If the input isn't NaN, then there is no portability concern.
857     ///
858     /// If you don't care about signalingness (very likely), then there is no
859     /// portability concern.
860     ///
861     /// Note that this function is distinct from `as` casting, which attempts to
862     /// preserve the *numeric* value, and not the bitwise value.
863     ///
864     /// # Examples
865     ///
866     /// ```
867     /// let v = f32::from_bits(0x41480000);
868     /// assert_eq!(v, 12.5);
869     /// ```
870     #[stable(feature = "float_bits_conv", since = "1.20.0")]
871     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
872     #[must_use]
873     #[inline]
874     pub const fn from_bits(v: u32) -> Self {
875         // SAFETY: `u32` is a plain old datatype so we can always transmute from it
876         // It turns out the safety issues with sNaN were overblown! Hooray!
877         unsafe { mem::transmute(v) }
878     }
879
880     /// Return the memory representation of this floating point number as a byte array in
881     /// big-endian (network) byte order.
882     ///
883     /// # Examples
884     ///
885     /// ```
886     /// let bytes = 12.5f32.to_be_bytes();
887     /// assert_eq!(bytes, [0x41, 0x48, 0x00, 0x00]);
888     /// ```
889     #[must_use = "this returns the result of the operation, \
890                   without modifying the original"]
891     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
892     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
893     #[inline]
894     pub const fn to_be_bytes(self) -> [u8; 4] {
895         self.to_bits().to_be_bytes()
896     }
897
898     /// Return the memory representation of this floating point number as a byte array in
899     /// little-endian byte order.
900     ///
901     /// # Examples
902     ///
903     /// ```
904     /// let bytes = 12.5f32.to_le_bytes();
905     /// assert_eq!(bytes, [0x00, 0x00, 0x48, 0x41]);
906     /// ```
907     #[must_use = "this returns the result of the operation, \
908                   without modifying the original"]
909     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
910     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
911     #[inline]
912     pub const fn to_le_bytes(self) -> [u8; 4] {
913         self.to_bits().to_le_bytes()
914     }
915
916     /// Return the memory representation of this floating point number as a byte array in
917     /// native byte order.
918     ///
919     /// As the target platform's native endianness is used, portable code
920     /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
921     ///
922     /// [`to_be_bytes`]: f32::to_be_bytes
923     /// [`to_le_bytes`]: f32::to_le_bytes
924     ///
925     /// # Examples
926     ///
927     /// ```
928     /// let bytes = 12.5f32.to_ne_bytes();
929     /// assert_eq!(
930     ///     bytes,
931     ///     if cfg!(target_endian = "big") {
932     ///         [0x41, 0x48, 0x00, 0x00]
933     ///     } else {
934     ///         [0x00, 0x00, 0x48, 0x41]
935     ///     }
936     /// );
937     /// ```
938     #[must_use = "this returns the result of the operation, \
939                   without modifying the original"]
940     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
941     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
942     #[inline]
943     pub const fn to_ne_bytes(self) -> [u8; 4] {
944         self.to_bits().to_ne_bytes()
945     }
946
947     /// Create a floating point value from its representation as a byte array in big endian.
948     ///
949     /// # Examples
950     ///
951     /// ```
952     /// let value = f32::from_be_bytes([0x41, 0x48, 0x00, 0x00]);
953     /// assert_eq!(value, 12.5);
954     /// ```
955     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
956     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
957     #[must_use]
958     #[inline]
959     pub const fn from_be_bytes(bytes: [u8; 4]) -> Self {
960         Self::from_bits(u32::from_be_bytes(bytes))
961     }
962
963     /// Create a floating point value from its representation as a byte array in little endian.
964     ///
965     /// # Examples
966     ///
967     /// ```
968     /// let value = f32::from_le_bytes([0x00, 0x00, 0x48, 0x41]);
969     /// assert_eq!(value, 12.5);
970     /// ```
971     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
972     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
973     #[must_use]
974     #[inline]
975     pub const fn from_le_bytes(bytes: [u8; 4]) -> Self {
976         Self::from_bits(u32::from_le_bytes(bytes))
977     }
978
979     /// Create a floating point value from its representation as a byte array in native endian.
980     ///
981     /// As the target platform's native endianness is used, portable code
982     /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
983     /// appropriate instead.
984     ///
985     /// [`from_be_bytes`]: f32::from_be_bytes
986     /// [`from_le_bytes`]: f32::from_le_bytes
987     ///
988     /// # Examples
989     ///
990     /// ```
991     /// let value = f32::from_ne_bytes(if cfg!(target_endian = "big") {
992     ///     [0x41, 0x48, 0x00, 0x00]
993     /// } else {
994     ///     [0x00, 0x00, 0x48, 0x41]
995     /// });
996     /// assert_eq!(value, 12.5);
997     /// ```
998     #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
999     #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1000     #[must_use]
1001     #[inline]
1002     pub const fn from_ne_bytes(bytes: [u8; 4]) -> Self {
1003         Self::from_bits(u32::from_ne_bytes(bytes))
1004     }
1005
1006     /// Returns an ordering between self and other values.
1007     /// Unlike the standard partial comparison between floating point numbers,
1008     /// this comparison always produces an ordering in accordance to
1009     /// the totalOrder predicate as defined in IEEE 754 (2008 revision)
1010     /// floating point standard. The values are ordered in following order:
1011     /// - Negative quiet NaN
1012     /// - Negative signaling NaN
1013     /// - Negative infinity
1014     /// - Negative numbers
1015     /// - Negative subnormal numbers
1016     /// - Negative zero
1017     /// - Positive zero
1018     /// - Positive subnormal numbers
1019     /// - Positive numbers
1020     /// - Positive infinity
1021     /// - Positive signaling NaN
1022     /// - Positive quiet NaN
1023     ///
1024     /// Note that this function does not always agree with the [`PartialOrd`]
1025     /// and [`PartialEq`] implementations of `f32`. In particular, they regard
1026     /// negative and positive zero as equal, while `total_cmp` doesn't.
1027     ///
1028     /// # Example
1029     /// ```
1030     /// #![feature(total_cmp)]
1031     /// struct GoodBoy {
1032     ///     name: String,
1033     ///     weight: f32,
1034     /// }
1035     ///
1036     /// let mut bois = vec![
1037     ///     GoodBoy { name: "Pucci".to_owned(), weight: 0.1 },
1038     ///     GoodBoy { name: "Woofer".to_owned(), weight: 99.0 },
1039     ///     GoodBoy { name: "Yapper".to_owned(), weight: 10.0 },
1040     ///     GoodBoy { name: "Chonk".to_owned(), weight: f32::INFINITY },
1041     ///     GoodBoy { name: "Abs. Unit".to_owned(), weight: f32::NAN },
1042     ///     GoodBoy { name: "Floaty".to_owned(), weight: -5.0 },
1043     /// ];
1044     ///
1045     /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1046     /// # assert!(bois.into_iter().map(|b| b.weight)
1047     /// #     .zip([-5.0, 0.1, 10.0, 99.0, f32::INFINITY, f32::NAN].iter())
1048     /// #     .all(|(a, b)| a.to_bits() == b.to_bits()))
1049     /// ```
1050     #[unstable(feature = "total_cmp", issue = "72599")]
1051     #[must_use]
1052     #[inline]
1053     pub fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1054         let mut left = self.to_bits() as i32;
1055         let mut right = other.to_bits() as i32;
1056
1057         // In case of negatives, flip all the bits except the sign
1058         // to achieve a similar layout as two's complement integers
1059         //
1060         // Why does this work? IEEE 754 floats consist of three fields:
1061         // Sign bit, exponent and mantissa. The set of exponent and mantissa
1062         // fields as a whole have the property that their bitwise order is
1063         // equal to the numeric magnitude where the magnitude is defined.
1064         // The magnitude is not normally defined on NaN values, but
1065         // IEEE 754 totalOrder defines the NaN values also to follow the
1066         // bitwise order. This leads to order explained in the doc comment.
1067         // However, the representation of magnitude is the same for negative
1068         // and positive numbers – only the sign bit is different.
1069         // To easily compare the floats as signed integers, we need to
1070         // flip the exponent and mantissa bits in case of negative numbers.
1071         // We effectively convert the numbers to "two's complement" form.
1072         //
1073         // To do the flipping, we construct a mask and XOR against it.
1074         // We branchlessly calculate an "all-ones except for the sign bit"
1075         // mask from negative-signed values: right shifting sign-extends
1076         // the integer, so we "fill" the mask with sign bits, and then
1077         // convert to unsigned to push one more zero bit.
1078         // On positive values, the mask is all zeros, so it's a no-op.
1079         left ^= (((left >> 31) as u32) >> 1) as i32;
1080         right ^= (((right >> 31) as u32) >> 1) as i32;
1081
1082         left.cmp(&right)
1083     }
1084
1085     /// Restrict a value to a certain interval unless it is NaN.
1086     ///
1087     /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1088     /// less than `min`. Otherwise this returns `self`.
1089     ///
1090     /// Note that this function returns NaN if the initial value was NaN as
1091     /// well.
1092     ///
1093     /// # Panics
1094     ///
1095     /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1096     ///
1097     /// # Examples
1098     ///
1099     /// ```
1100     /// assert!((-3.0f32).clamp(-2.0, 1.0) == -2.0);
1101     /// assert!((0.0f32).clamp(-2.0, 1.0) == 0.0);
1102     /// assert!((2.0f32).clamp(-2.0, 1.0) == 1.0);
1103     /// assert!((f32::NAN).clamp(-2.0, 1.0).is_nan());
1104     /// ```
1105     #[must_use = "method returns a new number and does not mutate the original value"]
1106     #[stable(feature = "clamp", since = "1.50.0")]
1107     #[inline]
1108     pub fn clamp(self, min: f32, max: f32) -> f32 {
1109         assert!(min <= max);
1110         let mut x = self;
1111         if x < min {
1112             x = min;
1113         }
1114         if x > max {
1115             x = max;
1116         }
1117         x
1118     }
1119 }