core/num/f32.rs
1//! Constants for 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
14use crate::convert::FloatToInt;
15use crate::num::FpCategory;
16use crate::panic::const_assert;
17use crate::{intrinsics, mem};
18
19/// The radix or base of the internal representation of `f32`.
20/// Use [`f32::RADIX`] instead.
21///
22/// # Examples
23///
24/// ```rust
25/// // deprecated way
26/// # #[allow(deprecated, deprecated_in_future)]
27/// let r = std::f32::RADIX;
28///
29/// // intended way
30/// let r = f32::RADIX;
31/// ```
32#[stable(feature = "rust1", since = "1.0.0")]
33#[deprecated(since = "TBD", note = "replaced by the `RADIX` associated constant on `f32`")]
34#[rustc_diagnostic_item = "f32_legacy_const_radix"]
35pub 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#[deprecated(
52 since = "TBD",
53 note = "replaced by the `MANTISSA_DIGITS` associated constant on `f32`"
54)]
55#[rustc_diagnostic_item = "f32_legacy_const_mantissa_dig"]
56pub const MANTISSA_DIGITS: u32 = f32::MANTISSA_DIGITS;
57
58/// Approximate number of significant digits in base 10.
59/// Use [`f32::DIGITS`] instead.
60///
61/// # Examples
62///
63/// ```rust
64/// // deprecated way
65/// # #[allow(deprecated, deprecated_in_future)]
66/// let d = std::f32::DIGITS;
67///
68/// // intended way
69/// let d = f32::DIGITS;
70/// ```
71#[stable(feature = "rust1", since = "1.0.0")]
72#[deprecated(since = "TBD", note = "replaced by the `DIGITS` associated constant on `f32`")]
73#[rustc_diagnostic_item = "f32_legacy_const_digits"]
74pub const DIGITS: u32 = f32::DIGITS;
75
76/// [Machine epsilon] value for `f32`.
77/// Use [`f32::EPSILON`] instead.
78///
79/// This is the difference between `1.0` and the next larger representable number.
80///
81/// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
82///
83/// # Examples
84///
85/// ```rust
86/// // deprecated way
87/// # #[allow(deprecated, deprecated_in_future)]
88/// let e = std::f32::EPSILON;
89///
90/// // intended way
91/// let e = f32::EPSILON;
92/// ```
93#[stable(feature = "rust1", since = "1.0.0")]
94#[deprecated(since = "TBD", note = "replaced by the `EPSILON` associated constant on `f32`")]
95#[rustc_diagnostic_item = "f32_legacy_const_epsilon"]
96pub 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#[deprecated(since = "TBD", note = "replaced by the `MIN` associated constant on `f32`")]
113#[rustc_diagnostic_item = "f32_legacy_const_min"]
114pub const MIN: f32 = f32::MIN;
115
116/// Smallest positive normal `f32` value.
117/// Use [`f32::MIN_POSITIVE`] instead.
118///
119/// # Examples
120///
121/// ```rust
122/// // deprecated way
123/// # #[allow(deprecated, deprecated_in_future)]
124/// let min = std::f32::MIN_POSITIVE;
125///
126/// // intended way
127/// let min = f32::MIN_POSITIVE;
128/// ```
129#[stable(feature = "rust1", since = "1.0.0")]
130#[deprecated(since = "TBD", note = "replaced by the `MIN_POSITIVE` associated constant on `f32`")]
131#[rustc_diagnostic_item = "f32_legacy_const_min_positive"]
132pub const MIN_POSITIVE: f32 = f32::MIN_POSITIVE;
133
134/// Largest finite `f32` value.
135/// Use [`f32::MAX`] instead.
136///
137/// # Examples
138///
139/// ```rust
140/// // deprecated way
141/// # #[allow(deprecated, deprecated_in_future)]
142/// let max = std::f32::MAX;
143///
144/// // intended way
145/// let max = f32::MAX;
146/// ```
147#[stable(feature = "rust1", since = "1.0.0")]
148#[deprecated(since = "TBD", note = "replaced by the `MAX` associated constant on `f32`")]
149#[rustc_diagnostic_item = "f32_legacy_const_max"]
150pub 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#[deprecated(since = "TBD", note = "replaced by the `MIN_EXP` associated constant on `f32`")]
167#[rustc_diagnostic_item = "f32_legacy_const_min_exp"]
168pub const MIN_EXP: i32 = f32::MIN_EXP;
169
170/// Maximum possible power of 2 exponent.
171/// Use [`f32::MAX_EXP`] instead.
172///
173/// # Examples
174///
175/// ```rust
176/// // deprecated way
177/// # #[allow(deprecated, deprecated_in_future)]
178/// let max = std::f32::MAX_EXP;
179///
180/// // intended way
181/// let max = f32::MAX_EXP;
182/// ```
183#[stable(feature = "rust1", since = "1.0.0")]
184#[deprecated(since = "TBD", note = "replaced by the `MAX_EXP` associated constant on `f32`")]
185#[rustc_diagnostic_item = "f32_legacy_const_max_exp"]
186pub const MAX_EXP: i32 = f32::MAX_EXP;
187
188/// Minimum possible normal power of 10 exponent.
189/// Use [`f32::MIN_10_EXP`] instead.
190///
191/// # Examples
192///
193/// ```rust
194/// // deprecated way
195/// # #[allow(deprecated, deprecated_in_future)]
196/// let min = std::f32::MIN_10_EXP;
197///
198/// // intended way
199/// let min = f32::MIN_10_EXP;
200/// ```
201#[stable(feature = "rust1", since = "1.0.0")]
202#[deprecated(since = "TBD", note = "replaced by the `MIN_10_EXP` associated constant on `f32`")]
203#[rustc_diagnostic_item = "f32_legacy_const_min_10_exp"]
204pub const MIN_10_EXP: i32 = f32::MIN_10_EXP;
205
206/// Maximum possible power of 10 exponent.
207/// Use [`f32::MAX_10_EXP`] instead.
208///
209/// # Examples
210///
211/// ```rust
212/// // deprecated way
213/// # #[allow(deprecated, deprecated_in_future)]
214/// let max = std::f32::MAX_10_EXP;
215///
216/// // intended way
217/// let max = f32::MAX_10_EXP;
218/// ```
219#[stable(feature = "rust1", since = "1.0.0")]
220#[deprecated(since = "TBD", note = "replaced by the `MAX_10_EXP` associated constant on `f32`")]
221#[rustc_diagnostic_item = "f32_legacy_const_max_10_exp"]
222pub const MAX_10_EXP: i32 = f32::MAX_10_EXP;
223
224/// Not a Number (NaN).
225/// Use [`f32::NAN`] instead.
226///
227/// # Examples
228///
229/// ```rust
230/// // deprecated way
231/// # #[allow(deprecated, deprecated_in_future)]
232/// let nan = std::f32::NAN;
233///
234/// // intended way
235/// let nan = f32::NAN;
236/// ```
237#[stable(feature = "rust1", since = "1.0.0")]
238#[deprecated(since = "TBD", note = "replaced by the `NAN` associated constant on `f32`")]
239#[rustc_diagnostic_item = "f32_legacy_const_nan"]
240pub const NAN: f32 = f32::NAN;
241
242/// Infinity (∞).
243/// Use [`f32::INFINITY`] instead.
244///
245/// # Examples
246///
247/// ```rust
248/// // deprecated way
249/// # #[allow(deprecated, deprecated_in_future)]
250/// let inf = std::f32::INFINITY;
251///
252/// // intended way
253/// let inf = f32::INFINITY;
254/// ```
255#[stable(feature = "rust1", since = "1.0.0")]
256#[deprecated(since = "TBD", note = "replaced by the `INFINITY` associated constant on `f32`")]
257#[rustc_diagnostic_item = "f32_legacy_const_infinity"]
258pub const INFINITY: f32 = f32::INFINITY;
259
260/// Negative infinity (−∞).
261/// Use [`f32::NEG_INFINITY`] instead.
262///
263/// # Examples
264///
265/// ```rust
266/// // deprecated way
267/// # #[allow(deprecated, deprecated_in_future)]
268/// let ninf = std::f32::NEG_INFINITY;
269///
270/// // intended way
271/// let ninf = f32::NEG_INFINITY;
272/// ```
273#[stable(feature = "rust1", since = "1.0.0")]
274#[deprecated(since = "TBD", note = "replaced by the `NEG_INFINITY` associated constant on `f32`")]
275#[rustc_diagnostic_item = "f32_legacy_const_neg_infinity"]
276pub const NEG_INFINITY: f32 = f32::NEG_INFINITY;
277
278/// Basic mathematical constants.
279#[stable(feature = "rust1", since = "1.0.0")]
280pub mod consts {
281 // FIXME: replace with mathematical constants from cmath.
282
283 /// Archimedes' constant (π)
284 #[stable(feature = "rust1", since = "1.0.0")]
285 pub const PI: f32 = 3.14159265358979323846264338327950288_f32;
286
287 /// The full circle constant (τ)
288 ///
289 /// Equal to 2π.
290 #[stable(feature = "tau_constant", since = "1.47.0")]
291 pub const TAU: f32 = 6.28318530717958647692528676655900577_f32;
292
293 /// The golden ratio (φ)
294 #[unstable(feature = "more_float_constants", issue = "103883")]
295 pub const PHI: f32 = 1.618033988749894848204586834365638118_f32;
296
297 /// The Euler-Mascheroni constant (γ)
298 #[unstable(feature = "more_float_constants", issue = "103883")]
299 pub const EGAMMA: f32 = 0.577215664901532860606512090082402431_f32;
300
301 /// π/2
302 #[stable(feature = "rust1", since = "1.0.0")]
303 pub const FRAC_PI_2: f32 = 1.57079632679489661923132169163975144_f32;
304
305 /// π/3
306 #[stable(feature = "rust1", since = "1.0.0")]
307 pub const FRAC_PI_3: f32 = 1.04719755119659774615421446109316763_f32;
308
309 /// π/4
310 #[stable(feature = "rust1", since = "1.0.0")]
311 pub const FRAC_PI_4: f32 = 0.785398163397448309615660845819875721_f32;
312
313 /// π/6
314 #[stable(feature = "rust1", since = "1.0.0")]
315 pub const FRAC_PI_6: f32 = 0.52359877559829887307710723054658381_f32;
316
317 /// π/8
318 #[stable(feature = "rust1", since = "1.0.0")]
319 pub const FRAC_PI_8: f32 = 0.39269908169872415480783042290993786_f32;
320
321 /// 1/π
322 #[stable(feature = "rust1", since = "1.0.0")]
323 pub const FRAC_1_PI: f32 = 0.318309886183790671537767526745028724_f32;
324
325 /// 1/sqrt(π)
326 #[unstable(feature = "more_float_constants", issue = "103883")]
327 pub const FRAC_1_SQRT_PI: f32 = 0.564189583547756286948079451560772586_f32;
328
329 /// 1/sqrt(2π)
330 #[doc(alias = "FRAC_1_SQRT_TAU")]
331 #[unstable(feature = "more_float_constants", issue = "103883")]
332 pub const FRAC_1_SQRT_2PI: f32 = 0.398942280401432677939946059934381868_f32;
333
334 /// 2/π
335 #[stable(feature = "rust1", since = "1.0.0")]
336 pub const FRAC_2_PI: f32 = 0.636619772367581343075535053490057448_f32;
337
338 /// 2/sqrt(π)
339 #[stable(feature = "rust1", since = "1.0.0")]
340 pub const FRAC_2_SQRT_PI: f32 = 1.12837916709551257389615890312154517_f32;
341
342 /// sqrt(2)
343 #[stable(feature = "rust1", since = "1.0.0")]
344 pub const SQRT_2: f32 = 1.41421356237309504880168872420969808_f32;
345
346 /// 1/sqrt(2)
347 #[stable(feature = "rust1", since = "1.0.0")]
348 pub const FRAC_1_SQRT_2: f32 = 0.707106781186547524400844362104849039_f32;
349
350 /// sqrt(3)
351 #[unstable(feature = "more_float_constants", issue = "103883")]
352 pub const SQRT_3: f32 = 1.732050807568877293527446341505872367_f32;
353
354 /// 1/sqrt(3)
355 #[unstable(feature = "more_float_constants", issue = "103883")]
356 pub const FRAC_1_SQRT_3: f32 = 0.577350269189625764509148780501957456_f32;
357
358 /// Euler's number (e)
359 #[stable(feature = "rust1", since = "1.0.0")]
360 pub const E: f32 = 2.71828182845904523536028747135266250_f32;
361
362 /// log<sub>2</sub>(e)
363 #[stable(feature = "rust1", since = "1.0.0")]
364 pub const LOG2_E: f32 = 1.44269504088896340735992468100189214_f32;
365
366 /// log<sub>2</sub>(10)
367 #[stable(feature = "extra_log_consts", since = "1.43.0")]
368 pub const LOG2_10: f32 = 3.32192809488736234787031942948939018_f32;
369
370 /// log<sub>10</sub>(e)
371 #[stable(feature = "rust1", since = "1.0.0")]
372 pub const LOG10_E: f32 = 0.434294481903251827651128918916605082_f32;
373
374 /// log<sub>10</sub>(2)
375 #[stable(feature = "extra_log_consts", since = "1.43.0")]
376 pub const LOG10_2: f32 = 0.301029995663981195213738894724493027_f32;
377
378 /// ln(2)
379 #[stable(feature = "rust1", since = "1.0.0")]
380 pub const LN_2: f32 = 0.693147180559945309417232121458176568_f32;
381
382 /// ln(10)
383 #[stable(feature = "rust1", since = "1.0.0")]
384 pub const LN_10: f32 = 2.30258509299404568401799145468436421_f32;
385}
386
387impl f32 {
388 /// The radix or base of the internal representation of `f32`.
389 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
390 pub const RADIX: u32 = 2;
391
392 /// Number of significant digits in base 2.
393 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
394 pub const MANTISSA_DIGITS: u32 = 24;
395
396 /// Approximate number of significant digits in base 10.
397 ///
398 /// This is the maximum <i>x</i> such that any decimal number with <i>x</i>
399 /// significant digits can be converted to `f32` and back without loss.
400 ///
401 /// Equal to floor(log<sub>10</sub> 2<sup>[`MANTISSA_DIGITS`] − 1</sup>).
402 ///
403 /// [`MANTISSA_DIGITS`]: f32::MANTISSA_DIGITS
404 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
405 pub const DIGITS: u32 = 6;
406
407 /// [Machine epsilon] value for `f32`.
408 ///
409 /// This is the difference between `1.0` and the next larger representable number.
410 ///
411 /// Equal to 2<sup>1 − [`MANTISSA_DIGITS`]</sup>.
412 ///
413 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
414 /// [`MANTISSA_DIGITS`]: f32::MANTISSA_DIGITS
415 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
416 #[rustc_diagnostic_item = "f32_epsilon"]
417 pub const EPSILON: f32 = 1.19209290e-07_f32;
418
419 /// Smallest finite `f32` value.
420 ///
421 /// Equal to −[`MAX`].
422 ///
423 /// [`MAX`]: f32::MAX
424 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
425 pub const MIN: f32 = -3.40282347e+38_f32;
426 /// Smallest positive normal `f32` value.
427 ///
428 /// Equal to 2<sup>[`MIN_EXP`] − 1</sup>.
429 ///
430 /// [`MIN_EXP`]: f32::MIN_EXP
431 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
432 pub const MIN_POSITIVE: f32 = 1.17549435e-38_f32;
433 /// Largest finite `f32` value.
434 ///
435 /// Equal to
436 /// (1 − 2<sup>−[`MANTISSA_DIGITS`]</sup>) 2<sup>[`MAX_EXP`]</sup>.
437 ///
438 /// [`MANTISSA_DIGITS`]: f32::MANTISSA_DIGITS
439 /// [`MAX_EXP`]: f32::MAX_EXP
440 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
441 pub const MAX: f32 = 3.40282347e+38_f32;
442
443 /// One greater than the minimum possible normal power of 2 exponent.
444 ///
445 /// If <i>x</i> = `MIN_EXP`, then normal numbers
446 /// ≥ 0.5 × 2<sup><i>x</i></sup>.
447 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
448 pub const MIN_EXP: i32 = -125;
449 /// Maximum possible power of 2 exponent.
450 ///
451 /// If <i>x</i> = `MAX_EXP`, then normal numbers
452 /// < 1 × 2<sup><i>x</i></sup>.
453 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
454 pub const MAX_EXP: i32 = 128;
455
456 /// Minimum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
457 ///
458 /// Equal to ceil(log<sub>10</sub> [`MIN_POSITIVE`]).
459 ///
460 /// [`MIN_POSITIVE`]: f32::MIN_POSITIVE
461 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
462 pub const MIN_10_EXP: i32 = -37;
463 /// Maximum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
464 ///
465 /// Equal to floor(log<sub>10</sub> [`MAX`]).
466 ///
467 /// [`MAX`]: f32::MAX
468 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
469 pub const MAX_10_EXP: i32 = 38;
470
471 /// Not a Number (NaN).
472 ///
473 /// Note that IEEE 754 doesn't define just a single NaN value;
474 /// a plethora of bit patterns are considered to be NaN.
475 /// Furthermore, the standard makes a difference
476 /// between a "signaling" and a "quiet" NaN,
477 /// and allows inspecting its "payload" (the unspecified bits in the bit pattern).
478 /// This constant isn't guaranteed to equal to any specific NaN bitpattern,
479 /// and the stability of its representation over Rust versions
480 /// and target platforms isn't guaranteed.
481 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
482 #[rustc_diagnostic_item = "f32_nan"]
483 #[allow(clippy::eq_op)]
484 pub const NAN: f32 = 0.0_f32 / 0.0_f32;
485 /// Infinity (∞).
486 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
487 pub const INFINITY: f32 = 1.0_f32 / 0.0_f32;
488 /// Negative infinity (−∞).
489 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
490 pub const NEG_INFINITY: f32 = -1.0_f32 / 0.0_f32;
491
492 /// Sign bit
493 pub(crate) const SIGN_MASK: u32 = 0x8000_0000;
494
495 /// Exponent mask
496 pub(crate) const EXP_MASK: u32 = 0x7f80_0000;
497
498 /// Mantissa mask
499 pub(crate) const MAN_MASK: u32 = 0x007f_ffff;
500
501 /// Minimum representable positive value (min subnormal)
502 const TINY_BITS: u32 = 0x1;
503
504 /// Minimum representable negative value (min negative subnormal)
505 const NEG_TINY_BITS: u32 = Self::TINY_BITS | Self::SIGN_MASK;
506
507 /// Returns `true` if this value is NaN.
508 ///
509 /// ```
510 /// let nan = f32::NAN;
511 /// let f = 7.0_f32;
512 ///
513 /// assert!(nan.is_nan());
514 /// assert!(!f.is_nan());
515 /// ```
516 #[must_use]
517 #[stable(feature = "rust1", since = "1.0.0")]
518 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
519 #[inline]
520 #[allow(clippy::eq_op)] // > if you intended to check if the operand is NaN, use `.is_nan()` instead :)
521 pub const fn is_nan(self) -> bool {
522 self != self
523 }
524
525 /// Returns `true` if this value is positive infinity or negative infinity, and
526 /// `false` otherwise.
527 ///
528 /// ```
529 /// let f = 7.0f32;
530 /// let inf = f32::INFINITY;
531 /// let neg_inf = f32::NEG_INFINITY;
532 /// let nan = f32::NAN;
533 ///
534 /// assert!(!f.is_infinite());
535 /// assert!(!nan.is_infinite());
536 ///
537 /// assert!(inf.is_infinite());
538 /// assert!(neg_inf.is_infinite());
539 /// ```
540 #[must_use]
541 #[stable(feature = "rust1", since = "1.0.0")]
542 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
543 #[inline]
544 pub const fn is_infinite(self) -> bool {
545 // Getting clever with transmutation can result in incorrect answers on some FPUs
546 // FIXME: alter the Rust <-> Rust calling convention to prevent this problem.
547 // See https://github.com/rust-lang/rust/issues/72327
548 (self == f32::INFINITY) | (self == f32::NEG_INFINITY)
549 }
550
551 /// Returns `true` if this number is neither infinite nor NaN.
552 ///
553 /// ```
554 /// let f = 7.0f32;
555 /// let inf = f32::INFINITY;
556 /// let neg_inf = f32::NEG_INFINITY;
557 /// let nan = f32::NAN;
558 ///
559 /// assert!(f.is_finite());
560 ///
561 /// assert!(!nan.is_finite());
562 /// assert!(!inf.is_finite());
563 /// assert!(!neg_inf.is_finite());
564 /// ```
565 #[must_use]
566 #[stable(feature = "rust1", since = "1.0.0")]
567 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
568 #[inline]
569 pub const fn is_finite(self) -> bool {
570 // There's no need to handle NaN separately: if self is NaN,
571 // the comparison is not true, exactly as desired.
572 self.abs() < Self::INFINITY
573 }
574
575 /// Returns `true` if the number is [subnormal].
576 ///
577 /// ```
578 /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
579 /// let max = f32::MAX;
580 /// let lower_than_min = 1.0e-40_f32;
581 /// let zero = 0.0_f32;
582 ///
583 /// assert!(!min.is_subnormal());
584 /// assert!(!max.is_subnormal());
585 ///
586 /// assert!(!zero.is_subnormal());
587 /// assert!(!f32::NAN.is_subnormal());
588 /// assert!(!f32::INFINITY.is_subnormal());
589 /// // Values between `0` and `min` are Subnormal.
590 /// assert!(lower_than_min.is_subnormal());
591 /// ```
592 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
593 #[must_use]
594 #[stable(feature = "is_subnormal", since = "1.53.0")]
595 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
596 #[inline]
597 pub const fn is_subnormal(self) -> bool {
598 matches!(self.classify(), FpCategory::Subnormal)
599 }
600
601 /// Returns `true` if the number is neither zero, infinite,
602 /// [subnormal], or NaN.
603 ///
604 /// ```
605 /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
606 /// let max = f32::MAX;
607 /// let lower_than_min = 1.0e-40_f32;
608 /// let zero = 0.0_f32;
609 ///
610 /// assert!(min.is_normal());
611 /// assert!(max.is_normal());
612 ///
613 /// assert!(!zero.is_normal());
614 /// assert!(!f32::NAN.is_normal());
615 /// assert!(!f32::INFINITY.is_normal());
616 /// // Values between `0` and `min` are Subnormal.
617 /// assert!(!lower_than_min.is_normal());
618 /// ```
619 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
620 #[must_use]
621 #[stable(feature = "rust1", since = "1.0.0")]
622 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
623 #[inline]
624 pub const fn is_normal(self) -> bool {
625 matches!(self.classify(), FpCategory::Normal)
626 }
627
628 /// Returns the floating point category of the number. If only one property
629 /// is going to be tested, it is generally faster to use the specific
630 /// predicate instead.
631 ///
632 /// ```
633 /// use std::num::FpCategory;
634 ///
635 /// let num = 12.4_f32;
636 /// let inf = f32::INFINITY;
637 ///
638 /// assert_eq!(num.classify(), FpCategory::Normal);
639 /// assert_eq!(inf.classify(), FpCategory::Infinite);
640 /// ```
641 #[stable(feature = "rust1", since = "1.0.0")]
642 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
643 pub const fn classify(self) -> FpCategory {
644 // We used to have complicated logic here that avoids the simple bit-based tests to work
645 // around buggy codegen for x87 targets (see
646 // https://github.com/rust-lang/rust/issues/114479). However, some LLVM versions later, none
647 // of our tests is able to find any difference between the complicated and the naive
648 // version, so now we are back to the naive version.
649 let b = self.to_bits();
650 match (b & Self::MAN_MASK, b & Self::EXP_MASK) {
651 (0, Self::EXP_MASK) => FpCategory::Infinite,
652 (_, Self::EXP_MASK) => FpCategory::Nan,
653 (0, 0) => FpCategory::Zero,
654 (_, 0) => FpCategory::Subnormal,
655 _ => FpCategory::Normal,
656 }
657 }
658
659 /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with
660 /// positive sign bit and positive infinity.
661 ///
662 /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
663 /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
664 /// conserved over arithmetic operations, the result of `is_sign_positive` on
665 /// a NaN might produce an unexpected or non-portable result. See the [specification
666 /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == 1.0`
667 /// if you need fully portable behavior (will return `false` for all NaNs).
668 ///
669 /// ```
670 /// let f = 7.0_f32;
671 /// let g = -7.0_f32;
672 ///
673 /// assert!(f.is_sign_positive());
674 /// assert!(!g.is_sign_positive());
675 /// ```
676 #[must_use]
677 #[stable(feature = "rust1", since = "1.0.0")]
678 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
679 #[inline]
680 pub const fn is_sign_positive(self) -> bool {
681 !self.is_sign_negative()
682 }
683
684 /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with
685 /// negative sign bit and negative infinity.
686 ///
687 /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
688 /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
689 /// conserved over arithmetic operations, the result of `is_sign_negative` on
690 /// a NaN might produce an unexpected or non-portable result. See the [specification
691 /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == -1.0`
692 /// if you need fully portable behavior (will return `false` for all NaNs).
693 ///
694 /// ```
695 /// let f = 7.0f32;
696 /// let g = -7.0f32;
697 ///
698 /// assert!(!f.is_sign_negative());
699 /// assert!(g.is_sign_negative());
700 /// ```
701 #[must_use]
702 #[stable(feature = "rust1", since = "1.0.0")]
703 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
704 #[inline]
705 pub const fn is_sign_negative(self) -> bool {
706 // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
707 // applies to zeros and NaNs as well.
708 // SAFETY: This is just transmuting to get the sign bit, it's fine.
709 unsafe { mem::transmute::<f32, u32>(self) & 0x8000_0000 != 0 }
710 }
711
712 /// Returns the least number greater than `self`.
713 ///
714 /// Let `TINY` be the smallest representable positive `f32`. Then,
715 /// - if `self.is_nan()`, this returns `self`;
716 /// - if `self` is [`NEG_INFINITY`], this returns [`MIN`];
717 /// - if `self` is `-TINY`, this returns -0.0;
718 /// - if `self` is -0.0 or +0.0, this returns `TINY`;
719 /// - if `self` is [`MAX`] or [`INFINITY`], this returns [`INFINITY`];
720 /// - otherwise the unique least value greater than `self` is returned.
721 ///
722 /// The identity `x.next_up() == -(-x).next_down()` holds for all non-NaN `x`. When `x`
723 /// is finite `x == x.next_up().next_down()` also holds.
724 ///
725 /// ```rust
726 /// // f32::EPSILON is the difference between 1.0 and the next number up.
727 /// assert_eq!(1.0f32.next_up(), 1.0 + f32::EPSILON);
728 /// // But not for most numbers.
729 /// assert!(0.1f32.next_up() < 0.1 + f32::EPSILON);
730 /// assert_eq!(16777216f32.next_up(), 16777218.0);
731 /// ```
732 ///
733 /// This operation corresponds to IEEE-754 `nextUp`.
734 ///
735 /// [`NEG_INFINITY`]: Self::NEG_INFINITY
736 /// [`INFINITY`]: Self::INFINITY
737 /// [`MIN`]: Self::MIN
738 /// [`MAX`]: Self::MAX
739 #[inline]
740 #[doc(alias = "nextUp")]
741 #[stable(feature = "float_next_up_down", since = "1.86.0")]
742 #[rustc_const_stable(feature = "float_next_up_down", since = "1.86.0")]
743 pub const fn next_up(self) -> Self {
744 // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
745 // denormals to zero. This is in general unsound and unsupported, but here
746 // we do our best to still produce the correct result on such targets.
747 let bits = self.to_bits();
748 if self.is_nan() || bits == Self::INFINITY.to_bits() {
749 return self;
750 }
751
752 let abs = bits & !Self::SIGN_MASK;
753 let next_bits = if abs == 0 {
754 Self::TINY_BITS
755 } else if bits == abs {
756 bits + 1
757 } else {
758 bits - 1
759 };
760 Self::from_bits(next_bits)
761 }
762
763 /// Returns the greatest number less than `self`.
764 ///
765 /// Let `TINY` be the smallest representable positive `f32`. Then,
766 /// - if `self.is_nan()`, this returns `self`;
767 /// - if `self` is [`INFINITY`], this returns [`MAX`];
768 /// - if `self` is `TINY`, this returns 0.0;
769 /// - if `self` is -0.0 or +0.0, this returns `-TINY`;
770 /// - if `self` is [`MIN`] or [`NEG_INFINITY`], this returns [`NEG_INFINITY`];
771 /// - otherwise the unique greatest value less than `self` is returned.
772 ///
773 /// The identity `x.next_down() == -(-x).next_up()` holds for all non-NaN `x`. When `x`
774 /// is finite `x == x.next_down().next_up()` also holds.
775 ///
776 /// ```rust
777 /// let x = 1.0f32;
778 /// // Clamp value into range [0, 1).
779 /// let clamped = x.clamp(0.0, 1.0f32.next_down());
780 /// assert!(clamped < 1.0);
781 /// assert_eq!(clamped.next_up(), 1.0);
782 /// ```
783 ///
784 /// This operation corresponds to IEEE-754 `nextDown`.
785 ///
786 /// [`NEG_INFINITY`]: Self::NEG_INFINITY
787 /// [`INFINITY`]: Self::INFINITY
788 /// [`MIN`]: Self::MIN
789 /// [`MAX`]: Self::MAX
790 #[inline]
791 #[doc(alias = "nextDown")]
792 #[stable(feature = "float_next_up_down", since = "1.86.0")]
793 #[rustc_const_stable(feature = "float_next_up_down", since = "1.86.0")]
794 pub const fn next_down(self) -> Self {
795 // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
796 // denormals to zero. This is in general unsound and unsupported, but here
797 // we do our best to still produce the correct result on such targets.
798 let bits = self.to_bits();
799 if self.is_nan() || bits == Self::NEG_INFINITY.to_bits() {
800 return self;
801 }
802
803 let abs = bits & !Self::SIGN_MASK;
804 let next_bits = if abs == 0 {
805 Self::NEG_TINY_BITS
806 } else if bits == abs {
807 bits - 1
808 } else {
809 bits + 1
810 };
811 Self::from_bits(next_bits)
812 }
813
814 /// Takes the reciprocal (inverse) of a number, `1/x`.
815 ///
816 /// ```
817 /// let x = 2.0_f32;
818 /// let abs_difference = (x.recip() - (1.0 / x)).abs();
819 ///
820 /// assert!(abs_difference <= f32::EPSILON);
821 /// ```
822 #[must_use = "this returns the result of the operation, without modifying the original"]
823 #[stable(feature = "rust1", since = "1.0.0")]
824 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
825 #[inline]
826 pub const fn recip(self) -> f32 {
827 1.0 / self
828 }
829
830 /// Converts radians to degrees.
831 ///
832 /// ```
833 /// let angle = std::f32::consts::PI;
834 ///
835 /// let abs_difference = (angle.to_degrees() - 180.0).abs();
836 /// # #[cfg(any(not(target_arch = "x86"), target_feature = "sse2"))]
837 /// assert!(abs_difference <= f32::EPSILON);
838 /// ```
839 #[must_use = "this returns the result of the operation, \
840 without modifying the original"]
841 #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
842 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
843 #[inline]
844 pub const fn to_degrees(self) -> f32 {
845 // Use a constant for better precision.
846 const PIS_IN_180: f32 = 57.2957795130823208767981548141051703_f32;
847 self * PIS_IN_180
848 }
849
850 /// Converts degrees to radians.
851 ///
852 /// ```
853 /// let angle = 180.0f32;
854 ///
855 /// let abs_difference = (angle.to_radians() - std::f32::consts::PI).abs();
856 ///
857 /// assert!(abs_difference <= f32::EPSILON);
858 /// ```
859 #[must_use = "this returns the result of the operation, \
860 without modifying the original"]
861 #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
862 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
863 #[inline]
864 pub const fn to_radians(self) -> f32 {
865 const RADS_PER_DEG: f32 = consts::PI / 180.0;
866 self * RADS_PER_DEG
867 }
868
869 /// Returns the maximum of the two numbers, ignoring NaN.
870 ///
871 /// If one of the arguments is NaN, then the other argument is returned.
872 /// This follows the IEEE 754-2008 semantics for maxNum, except for handling of signaling NaNs;
873 /// this function handles all NaNs the same way and avoids maxNum's problems with associativity.
874 /// This also matches the behavior of libm’s fmax. In particular, if the inputs compare equal
875 /// (such as for the case of `+0.0` and `-0.0`), either input may be returned non-deterministically.
876 ///
877 /// ```
878 /// let x = 1.0f32;
879 /// let y = 2.0f32;
880 ///
881 /// assert_eq!(x.max(y), y);
882 /// ```
883 #[must_use = "this returns the result of the comparison, without modifying either input"]
884 #[stable(feature = "rust1", since = "1.0.0")]
885 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
886 #[inline]
887 pub const fn max(self, other: f32) -> f32 {
888 intrinsics::maxnumf32(self, other)
889 }
890
891 /// Returns the minimum of the two numbers, ignoring NaN.
892 ///
893 /// If one of the arguments is NaN, then the other argument is returned.
894 /// This follows the IEEE 754-2008 semantics for minNum, except for handling of signaling NaNs;
895 /// this function handles all NaNs the same way and avoids minNum's problems with associativity.
896 /// This also matches the behavior of libm’s fmin. In particular, if the inputs compare equal
897 /// (such as for the case of `+0.0` and `-0.0`), either input may be returned non-deterministically.
898 ///
899 /// ```
900 /// let x = 1.0f32;
901 /// let y = 2.0f32;
902 ///
903 /// assert_eq!(x.min(y), x);
904 /// ```
905 #[must_use = "this returns the result of the comparison, without modifying either input"]
906 #[stable(feature = "rust1", since = "1.0.0")]
907 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
908 #[inline]
909 pub const fn min(self, other: f32) -> f32 {
910 intrinsics::minnumf32(self, other)
911 }
912
913 /// Returns the maximum of the two numbers, propagating NaN.
914 ///
915 /// This returns NaN when *either* argument is NaN, as opposed to
916 /// [`f32::max`] which only returns NaN when *both* arguments are NaN.
917 ///
918 /// ```
919 /// #![feature(float_minimum_maximum)]
920 /// let x = 1.0f32;
921 /// let y = 2.0f32;
922 ///
923 /// assert_eq!(x.maximum(y), y);
924 /// assert!(x.maximum(f32::NAN).is_nan());
925 /// ```
926 ///
927 /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the greater
928 /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
929 /// Note that this follows the semantics specified in IEEE 754-2019.
930 ///
931 /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
932 /// operand is conserved; see the [specification of NaN bit patterns](f32#nan-bit-patterns) for more info.
933 #[must_use = "this returns the result of the comparison, without modifying either input"]
934 #[unstable(feature = "float_minimum_maximum", issue = "91079")]
935 #[inline]
936 pub const fn maximum(self, other: f32) -> f32 {
937 if self > other {
938 self
939 } else if other > self {
940 other
941 } else if self == other {
942 if self.is_sign_positive() && other.is_sign_negative() { self } else { other }
943 } else {
944 self + other
945 }
946 }
947
948 /// Returns the minimum of the two numbers, propagating NaN.
949 ///
950 /// This returns NaN when *either* argument is NaN, as opposed to
951 /// [`f32::min`] which only returns NaN when *both* arguments are NaN.
952 ///
953 /// ```
954 /// #![feature(float_minimum_maximum)]
955 /// let x = 1.0f32;
956 /// let y = 2.0f32;
957 ///
958 /// assert_eq!(x.minimum(y), x);
959 /// assert!(x.minimum(f32::NAN).is_nan());
960 /// ```
961 ///
962 /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the lesser
963 /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
964 /// Note that this follows the semantics specified in IEEE 754-2019.
965 ///
966 /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
967 /// operand is conserved; see the [specification of NaN bit patterns](f32#nan-bit-patterns) for more info.
968 #[must_use = "this returns the result of the comparison, without modifying either input"]
969 #[unstable(feature = "float_minimum_maximum", issue = "91079")]
970 #[inline]
971 pub const fn minimum(self, other: f32) -> f32 {
972 if self < other {
973 self
974 } else if other < self {
975 other
976 } else if self == other {
977 if self.is_sign_negative() && other.is_sign_positive() { self } else { other }
978 } else {
979 // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
980 self + other
981 }
982 }
983
984 /// Calculates the middle point of `self` and `rhs`.
985 ///
986 /// This returns NaN when *either* argument is NaN or if a combination of
987 /// +inf and -inf is provided as arguments.
988 ///
989 /// # Examples
990 ///
991 /// ```
992 /// assert_eq!(1f32.midpoint(4.0), 2.5);
993 /// assert_eq!((-5.5f32).midpoint(8.0), 1.25);
994 /// ```
995 #[inline]
996 #[stable(feature = "num_midpoint", since = "1.85.0")]
997 #[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
998 pub const fn midpoint(self, other: f32) -> f32 {
999 cfg_if! {
1000 // Allow faster implementation that have known good 64-bit float
1001 // implementations. Falling back to the branchy code on targets that don't
1002 // have 64-bit hardware floats or buggy implementations.
1003 // https://github.com/rust-lang/rust/pull/121062#issuecomment-2123408114
1004 if #[cfg(any(
1005 target_arch = "x86_64",
1006 target_arch = "aarch64",
1007 all(any(target_arch = "riscv32", target_arch = "riscv64"), target_feature = "d"),
1008 all(target_arch = "arm", target_feature = "vfp2"),
1009 target_arch = "wasm32",
1010 target_arch = "wasm64",
1011 ))] {
1012 ((self as f64 + other as f64) / 2.0) as f32
1013 } else {
1014 const LO: f32 = f32::MIN_POSITIVE * 2.;
1015 const HI: f32 = f32::MAX / 2.;
1016
1017 let (a, b) = (self, other);
1018 let abs_a = a.abs();
1019 let abs_b = b.abs();
1020
1021 if abs_a <= HI && abs_b <= HI {
1022 // Overflow is impossible
1023 (a + b) / 2.
1024 } else if abs_a < LO {
1025 // Not safe to halve `a` (would underflow)
1026 a + (b / 2.)
1027 } else if abs_b < LO {
1028 // Not safe to halve `b` (would underflow)
1029 (a / 2.) + b
1030 } else {
1031 // Safe to halve `a` and `b`
1032 (a / 2.) + (b / 2.)
1033 }
1034 }
1035 }
1036 }
1037
1038 /// Rounds toward zero and converts to any primitive integer type,
1039 /// assuming that the value is finite and fits in that type.
1040 ///
1041 /// ```
1042 /// let value = 4.6_f32;
1043 /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
1044 /// assert_eq!(rounded, 4);
1045 ///
1046 /// let value = -128.9_f32;
1047 /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
1048 /// assert_eq!(rounded, i8::MIN);
1049 /// ```
1050 ///
1051 /// # Safety
1052 ///
1053 /// The value must:
1054 ///
1055 /// * Not be `NaN`
1056 /// * Not be infinite
1057 /// * Be representable in the return type `Int`, after truncating off its fractional part
1058 #[must_use = "this returns the result of the operation, \
1059 without modifying the original"]
1060 #[stable(feature = "float_approx_unchecked_to", since = "1.44.0")]
1061 #[inline]
1062 pub unsafe fn to_int_unchecked<Int>(self) -> Int
1063 where
1064 Self: FloatToInt<Int>,
1065 {
1066 // SAFETY: the caller must uphold the safety contract for
1067 // `FloatToInt::to_int_unchecked`.
1068 unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
1069 }
1070
1071 /// Raw transmutation to `u32`.
1072 ///
1073 /// This is currently identical to `transmute::<f32, u32>(self)` on all platforms.
1074 ///
1075 /// See [`from_bits`](Self::from_bits) for some discussion of the
1076 /// portability of this operation (there are almost no issues).
1077 ///
1078 /// Note that this function is distinct from `as` casting, which attempts to
1079 /// preserve the *numeric* value, and not the bitwise value.
1080 ///
1081 /// # Examples
1082 ///
1083 /// ```
1084 /// assert_ne!((1f32).to_bits(), 1f32 as u32); // to_bits() is not casting!
1085 /// assert_eq!((12.5f32).to_bits(), 0x41480000);
1086 ///
1087 /// ```
1088 #[must_use = "this returns the result of the operation, \
1089 without modifying the original"]
1090 #[stable(feature = "float_bits_conv", since = "1.20.0")]
1091 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1092 #[inline]
1093 pub const fn to_bits(self) -> u32 {
1094 // SAFETY: `u32` is a plain old datatype so we can always transmute to it.
1095 unsafe { mem::transmute(self) }
1096 }
1097
1098 /// Raw transmutation from `u32`.
1099 ///
1100 /// This is currently identical to `transmute::<u32, f32>(v)` on all platforms.
1101 /// It turns out this is incredibly portable, for two reasons:
1102 ///
1103 /// * Floats and Ints have the same endianness on all supported platforms.
1104 /// * IEEE 754 very precisely specifies the bit layout of floats.
1105 ///
1106 /// However there is one caveat: prior to the 2008 version of IEEE 754, how
1107 /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
1108 /// (notably x86 and ARM) picked the interpretation that was ultimately
1109 /// standardized in 2008, but some didn't (notably MIPS). As a result, all
1110 /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
1111 ///
1112 /// Rather than trying to preserve signaling-ness cross-platform, this
1113 /// implementation favors preserving the exact bits. This means that
1114 /// any payloads encoded in NaNs will be preserved even if the result of
1115 /// this method is sent over the network from an x86 machine to a MIPS one.
1116 ///
1117 /// If the results of this method are only manipulated by the same
1118 /// architecture that produced them, then there is no portability concern.
1119 ///
1120 /// If the input isn't NaN, then there is no portability concern.
1121 ///
1122 /// If you don't care about signalingness (very likely), then there is no
1123 /// portability concern.
1124 ///
1125 /// Note that this function is distinct from `as` casting, which attempts to
1126 /// preserve the *numeric* value, and not the bitwise value.
1127 ///
1128 /// # Examples
1129 ///
1130 /// ```
1131 /// let v = f32::from_bits(0x41480000);
1132 /// assert_eq!(v, 12.5);
1133 /// ```
1134 #[stable(feature = "float_bits_conv", since = "1.20.0")]
1135 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1136 #[must_use]
1137 #[inline]
1138 pub const fn from_bits(v: u32) -> Self {
1139 // It turns out the safety issues with sNaN were overblown! Hooray!
1140 // SAFETY: `u32` is a plain old datatype so we can always transmute from it.
1141 unsafe { mem::transmute(v) }
1142 }
1143
1144 /// Returns the memory representation of this floating point number as a byte array in
1145 /// big-endian (network) byte order.
1146 ///
1147 /// See [`from_bits`](Self::from_bits) for some discussion of the
1148 /// portability of this operation (there are almost no issues).
1149 ///
1150 /// # Examples
1151 ///
1152 /// ```
1153 /// let bytes = 12.5f32.to_be_bytes();
1154 /// assert_eq!(bytes, [0x41, 0x48, 0x00, 0x00]);
1155 /// ```
1156 #[must_use = "this returns the result of the operation, \
1157 without modifying the original"]
1158 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1159 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1160 #[inline]
1161 pub const fn to_be_bytes(self) -> [u8; 4] {
1162 self.to_bits().to_be_bytes()
1163 }
1164
1165 /// Returns the memory representation of this floating point number as a byte array in
1166 /// little-endian byte order.
1167 ///
1168 /// See [`from_bits`](Self::from_bits) for some discussion of the
1169 /// portability of this operation (there are almost no issues).
1170 ///
1171 /// # Examples
1172 ///
1173 /// ```
1174 /// let bytes = 12.5f32.to_le_bytes();
1175 /// assert_eq!(bytes, [0x00, 0x00, 0x48, 0x41]);
1176 /// ```
1177 #[must_use = "this returns the result of the operation, \
1178 without modifying the original"]
1179 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1180 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1181 #[inline]
1182 pub const fn to_le_bytes(self) -> [u8; 4] {
1183 self.to_bits().to_le_bytes()
1184 }
1185
1186 /// Returns the memory representation of this floating point number as a byte array in
1187 /// native byte order.
1188 ///
1189 /// As the target platform's native endianness is used, portable code
1190 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1191 ///
1192 /// [`to_be_bytes`]: f32::to_be_bytes
1193 /// [`to_le_bytes`]: f32::to_le_bytes
1194 ///
1195 /// See [`from_bits`](Self::from_bits) for some discussion of the
1196 /// portability of this operation (there are almost no issues).
1197 ///
1198 /// # Examples
1199 ///
1200 /// ```
1201 /// let bytes = 12.5f32.to_ne_bytes();
1202 /// assert_eq!(
1203 /// bytes,
1204 /// if cfg!(target_endian = "big") {
1205 /// [0x41, 0x48, 0x00, 0x00]
1206 /// } else {
1207 /// [0x00, 0x00, 0x48, 0x41]
1208 /// }
1209 /// );
1210 /// ```
1211 #[must_use = "this returns the result of the operation, \
1212 without modifying the original"]
1213 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1214 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1215 #[inline]
1216 pub const fn to_ne_bytes(self) -> [u8; 4] {
1217 self.to_bits().to_ne_bytes()
1218 }
1219
1220 /// Creates a floating point value from its representation as a byte array in big endian.
1221 ///
1222 /// See [`from_bits`](Self::from_bits) for some discussion of the
1223 /// portability of this operation (there are almost no issues).
1224 ///
1225 /// # Examples
1226 ///
1227 /// ```
1228 /// let value = f32::from_be_bytes([0x41, 0x48, 0x00, 0x00]);
1229 /// assert_eq!(value, 12.5);
1230 /// ```
1231 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1232 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1233 #[must_use]
1234 #[inline]
1235 pub const fn from_be_bytes(bytes: [u8; 4]) -> Self {
1236 Self::from_bits(u32::from_be_bytes(bytes))
1237 }
1238
1239 /// Creates a floating point value from its representation as a byte array in little endian.
1240 ///
1241 /// See [`from_bits`](Self::from_bits) for some discussion of the
1242 /// portability of this operation (there are almost no issues).
1243 ///
1244 /// # Examples
1245 ///
1246 /// ```
1247 /// let value = f32::from_le_bytes([0x00, 0x00, 0x48, 0x41]);
1248 /// assert_eq!(value, 12.5);
1249 /// ```
1250 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1251 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1252 #[must_use]
1253 #[inline]
1254 pub const fn from_le_bytes(bytes: [u8; 4]) -> Self {
1255 Self::from_bits(u32::from_le_bytes(bytes))
1256 }
1257
1258 /// Creates a floating point value from its representation as a byte array in native endian.
1259 ///
1260 /// As the target platform's native endianness is used, portable code
1261 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1262 /// appropriate instead.
1263 ///
1264 /// [`from_be_bytes`]: f32::from_be_bytes
1265 /// [`from_le_bytes`]: f32::from_le_bytes
1266 ///
1267 /// See [`from_bits`](Self::from_bits) for some discussion of the
1268 /// portability of this operation (there are almost no issues).
1269 ///
1270 /// # Examples
1271 ///
1272 /// ```
1273 /// let value = f32::from_ne_bytes(if cfg!(target_endian = "big") {
1274 /// [0x41, 0x48, 0x00, 0x00]
1275 /// } else {
1276 /// [0x00, 0x00, 0x48, 0x41]
1277 /// });
1278 /// assert_eq!(value, 12.5);
1279 /// ```
1280 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1281 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1282 #[must_use]
1283 #[inline]
1284 pub const fn from_ne_bytes(bytes: [u8; 4]) -> Self {
1285 Self::from_bits(u32::from_ne_bytes(bytes))
1286 }
1287
1288 /// Returns the ordering between `self` and `other`.
1289 ///
1290 /// Unlike the standard partial comparison between floating point numbers,
1291 /// this comparison always produces an ordering in accordance to
1292 /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1293 /// floating point standard. The values are ordered in the following sequence:
1294 ///
1295 /// - negative quiet NaN
1296 /// - negative signaling NaN
1297 /// - negative infinity
1298 /// - negative numbers
1299 /// - negative subnormal numbers
1300 /// - negative zero
1301 /// - positive zero
1302 /// - positive subnormal numbers
1303 /// - positive numbers
1304 /// - positive infinity
1305 /// - positive signaling NaN
1306 /// - positive quiet NaN.
1307 ///
1308 /// The ordering established by this function does not always agree with the
1309 /// [`PartialOrd`] and [`PartialEq`] implementations of `f32`. For example,
1310 /// they consider negative and positive zero equal, while `total_cmp`
1311 /// doesn't.
1312 ///
1313 /// The interpretation of the signaling NaN bit follows the definition in
1314 /// the IEEE 754 standard, which may not match the interpretation by some of
1315 /// the older, non-conformant (e.g. MIPS) hardware implementations.
1316 ///
1317 /// # Example
1318 ///
1319 /// ```
1320 /// struct GoodBoy {
1321 /// name: String,
1322 /// weight: f32,
1323 /// }
1324 ///
1325 /// let mut bois = vec![
1326 /// GoodBoy { name: "Pucci".to_owned(), weight: 0.1 },
1327 /// GoodBoy { name: "Woofer".to_owned(), weight: 99.0 },
1328 /// GoodBoy { name: "Yapper".to_owned(), weight: 10.0 },
1329 /// GoodBoy { name: "Chonk".to_owned(), weight: f32::INFINITY },
1330 /// GoodBoy { name: "Abs. Unit".to_owned(), weight: f32::NAN },
1331 /// GoodBoy { name: "Floaty".to_owned(), weight: -5.0 },
1332 /// ];
1333 ///
1334 /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1335 ///
1336 /// // `f32::NAN` could be positive or negative, which will affect the sort order.
1337 /// if f32::NAN.is_sign_negative() {
1338 /// assert!(bois.into_iter().map(|b| b.weight)
1339 /// .zip([f32::NAN, -5.0, 0.1, 10.0, 99.0, f32::INFINITY].iter())
1340 /// .all(|(a, b)| a.to_bits() == b.to_bits()))
1341 /// } else {
1342 /// assert!(bois.into_iter().map(|b| b.weight)
1343 /// .zip([-5.0, 0.1, 10.0, 99.0, f32::INFINITY, f32::NAN].iter())
1344 /// .all(|(a, b)| a.to_bits() == b.to_bits()))
1345 /// }
1346 /// ```
1347 #[stable(feature = "total_cmp", since = "1.62.0")]
1348 #[must_use]
1349 #[inline]
1350 pub fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1351 let mut left = self.to_bits() as i32;
1352 let mut right = other.to_bits() as i32;
1353
1354 // In case of negatives, flip all the bits except the sign
1355 // to achieve a similar layout as two's complement integers
1356 //
1357 // Why does this work? IEEE 754 floats consist of three fields:
1358 // Sign bit, exponent and mantissa. The set of exponent and mantissa
1359 // fields as a whole have the property that their bitwise order is
1360 // equal to the numeric magnitude where the magnitude is defined.
1361 // The magnitude is not normally defined on NaN values, but
1362 // IEEE 754 totalOrder defines the NaN values also to follow the
1363 // bitwise order. This leads to order explained in the doc comment.
1364 // However, the representation of magnitude is the same for negative
1365 // and positive numbers – only the sign bit is different.
1366 // To easily compare the floats as signed integers, we need to
1367 // flip the exponent and mantissa bits in case of negative numbers.
1368 // We effectively convert the numbers to "two's complement" form.
1369 //
1370 // To do the flipping, we construct a mask and XOR against it.
1371 // We branchlessly calculate an "all-ones except for the sign bit"
1372 // mask from negative-signed values: right shifting sign-extends
1373 // the integer, so we "fill" the mask with sign bits, and then
1374 // convert to unsigned to push one more zero bit.
1375 // On positive values, the mask is all zeros, so it's a no-op.
1376 left ^= (((left >> 31) as u32) >> 1) as i32;
1377 right ^= (((right >> 31) as u32) >> 1) as i32;
1378
1379 left.cmp(&right)
1380 }
1381
1382 /// Restrict a value to a certain interval unless it is NaN.
1383 ///
1384 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1385 /// less than `min`. Otherwise this returns `self`.
1386 ///
1387 /// Note that this function returns NaN if the initial value was NaN as
1388 /// well.
1389 ///
1390 /// # Panics
1391 ///
1392 /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1393 ///
1394 /// # Examples
1395 ///
1396 /// ```
1397 /// assert!((-3.0f32).clamp(-2.0, 1.0) == -2.0);
1398 /// assert!((0.0f32).clamp(-2.0, 1.0) == 0.0);
1399 /// assert!((2.0f32).clamp(-2.0, 1.0) == 1.0);
1400 /// assert!((f32::NAN).clamp(-2.0, 1.0).is_nan());
1401 /// ```
1402 #[must_use = "method returns a new number and does not mutate the original value"]
1403 #[stable(feature = "clamp", since = "1.50.0")]
1404 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1405 #[inline]
1406 pub const fn clamp(mut self, min: f32, max: f32) -> f32 {
1407 const_assert!(
1408 min <= max,
1409 "min > max, or either was NaN",
1410 "min > max, or either was NaN. min = {min:?}, max = {max:?}",
1411 min: f32,
1412 max: f32,
1413 );
1414
1415 if self < min {
1416 self = min;
1417 }
1418 if self > max {
1419 self = max;
1420 }
1421 self
1422 }
1423
1424 /// Computes the absolute value of `self`.
1425 ///
1426 /// This function always returns the precise result.
1427 ///
1428 /// # Examples
1429 ///
1430 /// ```
1431 /// let x = 3.5_f32;
1432 /// let y = -3.5_f32;
1433 ///
1434 /// assert_eq!(x.abs(), x);
1435 /// assert_eq!(y.abs(), -y);
1436 ///
1437 /// assert!(f32::NAN.abs().is_nan());
1438 /// ```
1439 #[must_use = "method returns a new number and does not mutate the original value"]
1440 #[stable(feature = "rust1", since = "1.0.0")]
1441 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1442 #[inline]
1443 pub const fn abs(self) -> f32 {
1444 // SAFETY: this is actually a safe intrinsic
1445 unsafe { intrinsics::fabsf32(self) }
1446 }
1447
1448 /// Returns a number that represents the sign of `self`.
1449 ///
1450 /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
1451 /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
1452 /// - NaN if the number is NaN
1453 ///
1454 /// # Examples
1455 ///
1456 /// ```
1457 /// let f = 3.5_f32;
1458 ///
1459 /// assert_eq!(f.signum(), 1.0);
1460 /// assert_eq!(f32::NEG_INFINITY.signum(), -1.0);
1461 ///
1462 /// assert!(f32::NAN.signum().is_nan());
1463 /// ```
1464 #[must_use = "method returns a new number and does not mutate the original value"]
1465 #[stable(feature = "rust1", since = "1.0.0")]
1466 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1467 #[inline]
1468 pub const fn signum(self) -> f32 {
1469 if self.is_nan() { Self::NAN } else { 1.0_f32.copysign(self) }
1470 }
1471
1472 /// Returns a number composed of the magnitude of `self` and the sign of
1473 /// `sign`.
1474 ///
1475 /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`.
1476 /// If `self` is a NaN, then a NaN with the same payload as `self` and the sign bit of `sign` is
1477 /// returned.
1478 ///
1479 /// If `sign` is a NaN, then this operation will still carry over its sign into the result. Note
1480 /// that IEEE 754 doesn't assign any meaning to the sign bit in case of a NaN, and as Rust
1481 /// doesn't guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the
1482 /// result of `copysign` with `sign` being a NaN might produce an unexpected or non-portable
1483 /// result. See the [specification of NaN bit patterns](primitive@f32#nan-bit-patterns) for more
1484 /// info.
1485 ///
1486 /// # Examples
1487 ///
1488 /// ```
1489 /// let f = 3.5_f32;
1490 ///
1491 /// assert_eq!(f.copysign(0.42), 3.5_f32);
1492 /// assert_eq!(f.copysign(-0.42), -3.5_f32);
1493 /// assert_eq!((-f).copysign(0.42), 3.5_f32);
1494 /// assert_eq!((-f).copysign(-0.42), -3.5_f32);
1495 ///
1496 /// assert!(f32::NAN.copysign(1.0).is_nan());
1497 /// ```
1498 #[must_use = "method returns a new number and does not mutate the original value"]
1499 #[inline]
1500 #[stable(feature = "copysign", since = "1.35.0")]
1501 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1502 pub const fn copysign(self, sign: f32) -> f32 {
1503 // SAFETY: this is actually a safe intrinsic
1504 unsafe { intrinsics::copysignf32(self, sign) }
1505 }
1506}