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