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