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