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
14#[cfg(not(feature = "ferrocene_certified"))]
15use crate::convert::FloatToInt;
16#[cfg(not(feature = "ferrocene_certified"))]
17use crate::num::FpCategory;
18#[cfg(not(feature = "ferrocene_certified"))]
19use crate::panic::const_assert;
20#[cfg(not(feature = "ferrocene_certified"))]
21use crate::{cfg_select, intrinsics, mem};
22
23// Ferrocene addition: imports for certified subset
24#[cfg(feature = "ferrocene_certified")]
25#[rustfmt::skip]
26use crate::mem;
27
28/// The radix or base of the internal representation of `f32`.
29/// Use [`f32::RADIX`] instead.
30///
31/// # Examples
32///
33/// ```rust
34/// // deprecated way
35/// # #[allow(deprecated, deprecated_in_future)]
36/// let r = std::f32::RADIX;
37///
38/// // intended way
39/// let r = f32::RADIX;
40/// ```
41#[stable(feature = "rust1", since = "1.0.0")]
42#[deprecated(since = "TBD", note = "replaced by the `RADIX` associated constant on `f32`")]
43#[rustc_diagnostic_item = "f32_legacy_const_radix"]
44pub const RADIX: u32 = f32::RADIX;
45
46/// Number of significant digits in base 2.
47/// Use [`f32::MANTISSA_DIGITS`] instead.
48///
49/// # Examples
50///
51/// ```rust
52/// // deprecated way
53/// # #[allow(deprecated, deprecated_in_future)]
54/// let d = std::f32::MANTISSA_DIGITS;
55///
56/// // intended way
57/// let d = f32::MANTISSA_DIGITS;
58/// ```
59#[stable(feature = "rust1", since = "1.0.0")]
60#[deprecated(
61 since = "TBD",
62 note = "replaced by the `MANTISSA_DIGITS` associated constant on `f32`"
63)]
64#[rustc_diagnostic_item = "f32_legacy_const_mantissa_dig"]
65pub const MANTISSA_DIGITS: u32 = f32::MANTISSA_DIGITS;
66
67/// Approximate number of significant digits in base 10.
68/// Use [`f32::DIGITS`] instead.
69///
70/// # Examples
71///
72/// ```rust
73/// // deprecated way
74/// # #[allow(deprecated, deprecated_in_future)]
75/// let d = std::f32::DIGITS;
76///
77/// // intended way
78/// let d = f32::DIGITS;
79/// ```
80#[stable(feature = "rust1", since = "1.0.0")]
81#[deprecated(since = "TBD", note = "replaced by the `DIGITS` associated constant on `f32`")]
82#[rustc_diagnostic_item = "f32_legacy_const_digits"]
83pub const DIGITS: u32 = f32::DIGITS;
84
85/// [Machine epsilon] value for `f32`.
86/// Use [`f32::EPSILON`] instead.
87///
88/// This is the difference between `1.0` and the next larger representable number.
89///
90/// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
91///
92/// # Examples
93///
94/// ```rust
95/// // deprecated way
96/// # #[allow(deprecated, deprecated_in_future)]
97/// let e = std::f32::EPSILON;
98///
99/// // intended way
100/// let e = f32::EPSILON;
101/// ```
102#[stable(feature = "rust1", since = "1.0.0")]
103#[deprecated(since = "TBD", note = "replaced by the `EPSILON` associated constant on `f32`")]
104#[rustc_diagnostic_item = "f32_legacy_const_epsilon"]
105pub const EPSILON: f32 = f32::EPSILON;
106
107/// Smallest finite `f32` value.
108/// Use [`f32::MIN`] instead.
109///
110/// # Examples
111///
112/// ```rust
113/// // deprecated way
114/// # #[allow(deprecated, deprecated_in_future)]
115/// let min = std::f32::MIN;
116///
117/// // intended way
118/// let min = f32::MIN;
119/// ```
120#[stable(feature = "rust1", since = "1.0.0")]
121#[deprecated(since = "TBD", note = "replaced by the `MIN` associated constant on `f32`")]
122#[rustc_diagnostic_item = "f32_legacy_const_min"]
123pub const MIN: f32 = f32::MIN;
124
125/// Smallest positive normal `f32` value.
126/// Use [`f32::MIN_POSITIVE`] instead.
127///
128/// # Examples
129///
130/// ```rust
131/// // deprecated way
132/// # #[allow(deprecated, deprecated_in_future)]
133/// let min = std::f32::MIN_POSITIVE;
134///
135/// // intended way
136/// let min = f32::MIN_POSITIVE;
137/// ```
138#[stable(feature = "rust1", since = "1.0.0")]
139#[deprecated(since = "TBD", note = "replaced by the `MIN_POSITIVE` associated constant on `f32`")]
140#[rustc_diagnostic_item = "f32_legacy_const_min_positive"]
141pub const MIN_POSITIVE: f32 = f32::MIN_POSITIVE;
142
143/// Largest finite `f32` value.
144/// Use [`f32::MAX`] instead.
145///
146/// # Examples
147///
148/// ```rust
149/// // deprecated way
150/// # #[allow(deprecated, deprecated_in_future)]
151/// let max = std::f32::MAX;
152///
153/// // intended way
154/// let max = f32::MAX;
155/// ```
156#[stable(feature = "rust1", since = "1.0.0")]
157#[deprecated(since = "TBD", note = "replaced by the `MAX` associated constant on `f32`")]
158#[rustc_diagnostic_item = "f32_legacy_const_max"]
159pub const MAX: f32 = f32::MAX;
160
161/// One greater than the minimum possible normal power of 2 exponent.
162/// Use [`f32::MIN_EXP`] instead.
163///
164/// # Examples
165///
166/// ```rust
167/// // deprecated way
168/// # #[allow(deprecated, deprecated_in_future)]
169/// let min = std::f32::MIN_EXP;
170///
171/// // intended way
172/// let min = f32::MIN_EXP;
173/// ```
174#[stable(feature = "rust1", since = "1.0.0")]
175#[deprecated(since = "TBD", note = "replaced by the `MIN_EXP` associated constant on `f32`")]
176#[rustc_diagnostic_item = "f32_legacy_const_min_exp"]
177pub const MIN_EXP: i32 = f32::MIN_EXP;
178
179/// Maximum possible power of 2 exponent.
180/// Use [`f32::MAX_EXP`] instead.
181///
182/// # Examples
183///
184/// ```rust
185/// // deprecated way
186/// # #[allow(deprecated, deprecated_in_future)]
187/// let max = std::f32::MAX_EXP;
188///
189/// // intended way
190/// let max = f32::MAX_EXP;
191/// ```
192#[stable(feature = "rust1", since = "1.0.0")]
193#[deprecated(since = "TBD", note = "replaced by the `MAX_EXP` associated constant on `f32`")]
194#[rustc_diagnostic_item = "f32_legacy_const_max_exp"]
195pub const MAX_EXP: i32 = f32::MAX_EXP;
196
197/// Minimum possible normal power of 10 exponent.
198/// Use [`f32::MIN_10_EXP`] instead.
199///
200/// # Examples
201///
202/// ```rust
203/// // deprecated way
204/// # #[allow(deprecated, deprecated_in_future)]
205/// let min = std::f32::MIN_10_EXP;
206///
207/// // intended way
208/// let min = f32::MIN_10_EXP;
209/// ```
210#[stable(feature = "rust1", since = "1.0.0")]
211#[deprecated(since = "TBD", note = "replaced by the `MIN_10_EXP` associated constant on `f32`")]
212#[rustc_diagnostic_item = "f32_legacy_const_min_10_exp"]
213pub const MIN_10_EXP: i32 = f32::MIN_10_EXP;
214
215/// Maximum possible power of 10 exponent.
216/// Use [`f32::MAX_10_EXP`] instead.
217///
218/// # Examples
219///
220/// ```rust
221/// // deprecated way
222/// # #[allow(deprecated, deprecated_in_future)]
223/// let max = std::f32::MAX_10_EXP;
224///
225/// // intended way
226/// let max = f32::MAX_10_EXP;
227/// ```
228#[stable(feature = "rust1", since = "1.0.0")]
229#[deprecated(since = "TBD", note = "replaced by the `MAX_10_EXP` associated constant on `f32`")]
230#[rustc_diagnostic_item = "f32_legacy_const_max_10_exp"]
231pub const MAX_10_EXP: i32 = f32::MAX_10_EXP;
232
233/// Not a Number (NaN).
234/// Use [`f32::NAN`] instead.
235///
236/// # Examples
237///
238/// ```rust
239/// // deprecated way
240/// # #[allow(deprecated, deprecated_in_future)]
241/// let nan = std::f32::NAN;
242///
243/// // intended way
244/// let nan = f32::NAN;
245/// ```
246#[stable(feature = "rust1", since = "1.0.0")]
247#[deprecated(since = "TBD", note = "replaced by the `NAN` associated constant on `f32`")]
248#[rustc_diagnostic_item = "f32_legacy_const_nan"]
249pub const NAN: f32 = f32::NAN;
250
251/// Infinity (∞).
252/// Use [`f32::INFINITY`] instead.
253///
254/// # Examples
255///
256/// ```rust
257/// // deprecated way
258/// # #[allow(deprecated, deprecated_in_future)]
259/// let inf = std::f32::INFINITY;
260///
261/// // intended way
262/// let inf = f32::INFINITY;
263/// ```
264#[stable(feature = "rust1", since = "1.0.0")]
265#[deprecated(since = "TBD", note = "replaced by the `INFINITY` associated constant on `f32`")]
266#[rustc_diagnostic_item = "f32_legacy_const_infinity"]
267pub const INFINITY: f32 = f32::INFINITY;
268
269/// Negative infinity (−∞).
270/// Use [`f32::NEG_INFINITY`] instead.
271///
272/// # Examples
273///
274/// ```rust
275/// // deprecated way
276/// # #[allow(deprecated, deprecated_in_future)]
277/// let ninf = std::f32::NEG_INFINITY;
278///
279/// // intended way
280/// let ninf = f32::NEG_INFINITY;
281/// ```
282#[stable(feature = "rust1", since = "1.0.0")]
283#[deprecated(since = "TBD", note = "replaced by the `NEG_INFINITY` associated constant on `f32`")]
284#[rustc_diagnostic_item = "f32_legacy_const_neg_infinity"]
285pub const NEG_INFINITY: f32 = f32::NEG_INFINITY;
286
287/// Basic mathematical constants.
288#[stable(feature = "rust1", since = "1.0.0")]
289#[rustc_diagnostic_item = "f32_consts_mod"]
290pub mod consts {
291 // FIXME: replace with mathematical constants from cmath.
292
293 /// Archimedes' constant (π)
294 #[stable(feature = "rust1", since = "1.0.0")]
295 pub const PI: f32 = 3.14159265358979323846264338327950288_f32;
296
297 /// The full circle constant (τ)
298 ///
299 /// Equal to 2π.
300 #[stable(feature = "tau_constant", since = "1.47.0")]
301 pub const TAU: f32 = 6.28318530717958647692528676655900577_f32;
302
303 /// The golden ratio (φ)
304 #[unstable(feature = "more_float_constants", issue = "146939")]
305 pub const PHI: f32 = 1.618033988749894848204586834365638118_f32;
306
307 /// The Euler-Mascheroni constant (γ)
308 #[unstable(feature = "more_float_constants", issue = "146939")]
309 pub const EGAMMA: f32 = 0.577215664901532860606512090082402431_f32;
310
311 /// π/2
312 #[stable(feature = "rust1", since = "1.0.0")]
313 pub const FRAC_PI_2: f32 = 1.57079632679489661923132169163975144_f32;
314
315 /// π/3
316 #[stable(feature = "rust1", since = "1.0.0")]
317 pub const FRAC_PI_3: f32 = 1.04719755119659774615421446109316763_f32;
318
319 /// π/4
320 #[stable(feature = "rust1", since = "1.0.0")]
321 pub const FRAC_PI_4: f32 = 0.785398163397448309615660845819875721_f32;
322
323 /// π/6
324 #[stable(feature = "rust1", since = "1.0.0")]
325 pub const FRAC_PI_6: f32 = 0.52359877559829887307710723054658381_f32;
326
327 /// π/8
328 #[stable(feature = "rust1", since = "1.0.0")]
329 pub const FRAC_PI_8: f32 = 0.39269908169872415480783042290993786_f32;
330
331 /// 1/π
332 #[stable(feature = "rust1", since = "1.0.0")]
333 pub const FRAC_1_PI: f32 = 0.318309886183790671537767526745028724_f32;
334
335 /// 1/sqrt(π)
336 #[unstable(feature = "more_float_constants", issue = "146939")]
337 pub const FRAC_1_SQRT_PI: f32 = 0.564189583547756286948079451560772586_f32;
338
339 /// 1/sqrt(2π)
340 #[doc(alias = "FRAC_1_SQRT_TAU")]
341 #[unstable(feature = "more_float_constants", issue = "146939")]
342 pub const FRAC_1_SQRT_2PI: f32 = 0.398942280401432677939946059934381868_f32;
343
344 /// 2/π
345 #[stable(feature = "rust1", since = "1.0.0")]
346 pub const FRAC_2_PI: f32 = 0.636619772367581343075535053490057448_f32;
347
348 /// 2/sqrt(π)
349 #[stable(feature = "rust1", since = "1.0.0")]
350 pub const FRAC_2_SQRT_PI: f32 = 1.12837916709551257389615890312154517_f32;
351
352 /// sqrt(2)
353 #[stable(feature = "rust1", since = "1.0.0")]
354 pub const SQRT_2: f32 = 1.41421356237309504880168872420969808_f32;
355
356 /// 1/sqrt(2)
357 #[stable(feature = "rust1", since = "1.0.0")]
358 pub const FRAC_1_SQRT_2: f32 = 0.707106781186547524400844362104849039_f32;
359
360 /// sqrt(3)
361 #[unstable(feature = "more_float_constants", issue = "146939")]
362 pub const SQRT_3: f32 = 1.732050807568877293527446341505872367_f32;
363
364 /// 1/sqrt(3)
365 #[unstable(feature = "more_float_constants", issue = "146939")]
366 pub const FRAC_1_SQRT_3: f32 = 0.577350269189625764509148780501957456_f32;
367
368 /// Euler's number (e)
369 #[stable(feature = "rust1", since = "1.0.0")]
370 pub const E: f32 = 2.71828182845904523536028747135266250_f32;
371
372 /// log<sub>2</sub>(e)
373 #[stable(feature = "rust1", since = "1.0.0")]
374 pub const LOG2_E: f32 = 1.44269504088896340735992468100189214_f32;
375
376 /// log<sub>2</sub>(10)
377 #[stable(feature = "extra_log_consts", since = "1.43.0")]
378 pub const LOG2_10: f32 = 3.32192809488736234787031942948939018_f32;
379
380 /// log<sub>10</sub>(e)
381 #[stable(feature = "rust1", since = "1.0.0")]
382 pub const LOG10_E: f32 = 0.434294481903251827651128918916605082_f32;
383
384 /// log<sub>10</sub>(2)
385 #[stable(feature = "extra_log_consts", since = "1.43.0")]
386 pub const LOG10_2: f32 = 0.301029995663981195213738894724493027_f32;
387
388 /// ln(2)
389 #[stable(feature = "rust1", since = "1.0.0")]
390 pub const LN_2: f32 = 0.693147180559945309417232121458176568_f32;
391
392 /// ln(10)
393 #[stable(feature = "rust1", since = "1.0.0")]
394 pub const LN_10: f32 = 2.30258509299404568401799145468436421_f32;
395}
396
397impl f32 {
398 /// The radix or base of the internal representation of `f32`.
399 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
400 pub const RADIX: u32 = 2;
401
402 /// Number of significant digits in base 2.
403 ///
404 /// Note that the size of the mantissa in the bitwise representation is one
405 /// smaller than this since the leading 1 is not stored explicitly.
406 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
407 pub const MANTISSA_DIGITS: u32 = 24;
408
409 /// Approximate number of significant digits in base 10.
410 ///
411 /// This is the maximum <i>x</i> such that any decimal number with <i>x</i>
412 /// significant digits can be converted to `f32` and back without loss.
413 ///
414 /// Equal to floor(log<sub>10</sub> 2<sup>[`MANTISSA_DIGITS`] − 1</sup>).
415 ///
416 /// [`MANTISSA_DIGITS`]: f32::MANTISSA_DIGITS
417 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
418 pub const DIGITS: u32 = 6;
419
420 /// [Machine epsilon] value for `f32`.
421 ///
422 /// This is the difference between `1.0` and the next larger representable number.
423 ///
424 /// Equal to 2<sup>1 − [`MANTISSA_DIGITS`]</sup>.
425 ///
426 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
427 /// [`MANTISSA_DIGITS`]: f32::MANTISSA_DIGITS
428 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
429 #[rustc_diagnostic_item = "f32_epsilon"]
430 pub const EPSILON: f32 = 1.19209290e-07_f32;
431
432 /// Smallest finite `f32` value.
433 ///
434 /// Equal to −[`MAX`].
435 ///
436 /// [`MAX`]: f32::MAX
437 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
438 pub const MIN: f32 = -3.40282347e+38_f32;
439 /// Smallest positive normal `f32` value.
440 ///
441 /// Equal to 2<sup>[`MIN_EXP`] − 1</sup>.
442 ///
443 /// [`MIN_EXP`]: f32::MIN_EXP
444 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
445 pub const MIN_POSITIVE: f32 = 1.17549435e-38_f32;
446 /// Largest finite `f32` value.
447 ///
448 /// Equal to
449 /// (1 − 2<sup>−[`MANTISSA_DIGITS`]</sup>) 2<sup>[`MAX_EXP`]</sup>.
450 ///
451 /// [`MANTISSA_DIGITS`]: f32::MANTISSA_DIGITS
452 /// [`MAX_EXP`]: f32::MAX_EXP
453 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
454 pub const MAX: f32 = 3.40282347e+38_f32;
455
456 /// One greater than the minimum possible *normal* power of 2 exponent
457 /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).
458 ///
459 /// This corresponds to the exact minimum possible *normal* power of 2 exponent
460 /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).
461 /// In other words, all normal numbers representable by this type are
462 /// greater than or equal to 0.5 × 2<sup><i>MIN_EXP</i></sup>.
463 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
464 pub const MIN_EXP: i32 = -125;
465 /// One greater than the maximum possible power of 2 exponent
466 /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).
467 ///
468 /// This corresponds to the exact maximum possible power of 2 exponent
469 /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).
470 /// In other words, all numbers representable by this type are
471 /// strictly less than 2<sup><i>MAX_EXP</i></sup>.
472 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
473 pub const MAX_EXP: i32 = 128;
474
475 /// Minimum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
476 ///
477 /// Equal to ceil(log<sub>10</sub> [`MIN_POSITIVE`]).
478 ///
479 /// [`MIN_POSITIVE`]: f32::MIN_POSITIVE
480 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
481 pub const MIN_10_EXP: i32 = -37;
482 /// Maximum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
483 ///
484 /// Equal to floor(log<sub>10</sub> [`MAX`]).
485 ///
486 /// [`MAX`]: f32::MAX
487 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
488 pub const MAX_10_EXP: i32 = 38;
489
490 /// Not a Number (NaN).
491 ///
492 /// Note that IEEE 754 doesn't define just a single NaN value; a plethora of bit patterns are
493 /// considered to be NaN. Furthermore, the standard makes a difference between a "signaling" and
494 /// a "quiet" NaN, and allows inspecting its "payload" (the unspecified bits in the bit pattern)
495 /// and its sign. See the [specification of NaN bit patterns](f32#nan-bit-patterns) for more
496 /// info.
497 ///
498 /// This constant is guaranteed to be a quiet NaN (on targets that follow the Rust assumptions
499 /// that the quiet/signaling bit being set to 1 indicates a quiet NaN). Beyond that, nothing is
500 /// guaranteed about the specific bit pattern chosen here: both payload and sign are arbitrary.
501 /// The concrete bit pattern may change across Rust versions and target platforms.
502 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
503 #[rustc_diagnostic_item = "f32_nan"]
504 #[allow(clippy::eq_op)]
505 pub const NAN: f32 = 0.0_f32 / 0.0_f32;
506 /// Infinity (∞).
507 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
508 pub const INFINITY: f32 = 1.0_f32 / 0.0_f32;
509 /// Negative infinity (−∞).
510 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
511 pub const NEG_INFINITY: f32 = -1.0_f32 / 0.0_f32;
512
513 /// Sign bit
514 #[cfg(not(feature = "ferrocene_certified"))]
515 pub(crate) const SIGN_MASK: u32 = 0x8000_0000;
516
517 /// Exponent mask
518 #[cfg(not(feature = "ferrocene_certified"))]
519 pub(crate) const EXP_MASK: u32 = 0x7f80_0000;
520
521 /// Mantissa mask
522 #[cfg(not(feature = "ferrocene_certified"))]
523 pub(crate) const MAN_MASK: u32 = 0x007f_ffff;
524
525 /// Minimum representable positive value (min subnormal)
526 #[cfg(not(feature = "ferrocene_certified"))]
527 const TINY_BITS: u32 = 0x1;
528
529 /// Minimum representable negative value (min negative subnormal)
530 #[cfg(not(feature = "ferrocene_certified"))]
531 const NEG_TINY_BITS: u32 = Self::TINY_BITS | Self::SIGN_MASK;
532
533 /// Returns `true` if this value is NaN.
534 ///
535 /// ```
536 /// let nan = f32::NAN;
537 /// let f = 7.0_f32;
538 ///
539 /// assert!(nan.is_nan());
540 /// assert!(!f.is_nan());
541 /// ```
542 #[must_use]
543 #[stable(feature = "rust1", since = "1.0.0")]
544 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
545 #[inline]
546 #[allow(clippy::eq_op)] // > if you intended to check if the operand is NaN, use `.is_nan()` instead :)
547 #[cfg(not(feature = "ferrocene_certified"))]
548 pub const fn is_nan(self) -> bool {
549 self != self
550 }
551
552 /// Returns `true` if this value is positive infinity or negative infinity, and
553 /// `false` otherwise.
554 ///
555 /// ```
556 /// let f = 7.0f32;
557 /// let inf = f32::INFINITY;
558 /// let neg_inf = f32::NEG_INFINITY;
559 /// let nan = f32::NAN;
560 ///
561 /// assert!(!f.is_infinite());
562 /// assert!(!nan.is_infinite());
563 ///
564 /// assert!(inf.is_infinite());
565 /// assert!(neg_inf.is_infinite());
566 /// ```
567 #[must_use]
568 #[stable(feature = "rust1", since = "1.0.0")]
569 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
570 #[inline]
571 #[cfg(not(feature = "ferrocene_certified"))]
572 pub const fn is_infinite(self) -> bool {
573 // Getting clever with transmutation can result in incorrect answers on some FPUs
574 // FIXME: alter the Rust <-> Rust calling convention to prevent this problem.
575 // See https://github.com/rust-lang/rust/issues/72327
576 (self == f32::INFINITY) | (self == f32::NEG_INFINITY)
577 }
578
579 /// Returns `true` if this number is neither infinite nor NaN.
580 ///
581 /// ```
582 /// let f = 7.0f32;
583 /// let inf = f32::INFINITY;
584 /// let neg_inf = f32::NEG_INFINITY;
585 /// let nan = f32::NAN;
586 ///
587 /// assert!(f.is_finite());
588 ///
589 /// assert!(!nan.is_finite());
590 /// assert!(!inf.is_finite());
591 /// assert!(!neg_inf.is_finite());
592 /// ```
593 #[must_use]
594 #[stable(feature = "rust1", since = "1.0.0")]
595 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
596 #[inline]
597 #[cfg(not(feature = "ferrocene_certified"))]
598 pub const fn is_finite(self) -> bool {
599 // There's no need to handle NaN separately: if self is NaN,
600 // the comparison is not true, exactly as desired.
601 self.abs() < Self::INFINITY
602 }
603
604 /// Returns `true` if the number is [subnormal].
605 ///
606 /// ```
607 /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
608 /// let max = f32::MAX;
609 /// let lower_than_min = 1.0e-40_f32;
610 /// let zero = 0.0_f32;
611 ///
612 /// assert!(!min.is_subnormal());
613 /// assert!(!max.is_subnormal());
614 ///
615 /// assert!(!zero.is_subnormal());
616 /// assert!(!f32::NAN.is_subnormal());
617 /// assert!(!f32::INFINITY.is_subnormal());
618 /// // Values between `0` and `min` are Subnormal.
619 /// assert!(lower_than_min.is_subnormal());
620 /// ```
621 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
622 #[must_use]
623 #[stable(feature = "is_subnormal", since = "1.53.0")]
624 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
625 #[inline]
626 #[cfg(not(feature = "ferrocene_certified"))]
627 pub const fn is_subnormal(self) -> bool {
628 matches!(self.classify(), FpCategory::Subnormal)
629 }
630
631 /// Returns `true` if the number is neither zero, infinite,
632 /// [subnormal], or NaN.
633 ///
634 /// ```
635 /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
636 /// let max = f32::MAX;
637 /// let lower_than_min = 1.0e-40_f32;
638 /// let zero = 0.0_f32;
639 ///
640 /// assert!(min.is_normal());
641 /// assert!(max.is_normal());
642 ///
643 /// assert!(!zero.is_normal());
644 /// assert!(!f32::NAN.is_normal());
645 /// assert!(!f32::INFINITY.is_normal());
646 /// // Values between `0` and `min` are Subnormal.
647 /// assert!(!lower_than_min.is_normal());
648 /// ```
649 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
650 #[must_use]
651 #[stable(feature = "rust1", since = "1.0.0")]
652 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
653 #[inline]
654 #[cfg(not(feature = "ferrocene_certified"))]
655 pub const fn is_normal(self) -> bool {
656 matches!(self.classify(), FpCategory::Normal)
657 }
658
659 /// Returns the floating point category of the number. If only one property
660 /// is going to be tested, it is generally faster to use the specific
661 /// predicate instead.
662 ///
663 /// ```
664 /// use std::num::FpCategory;
665 ///
666 /// let num = 12.4_f32;
667 /// let inf = f32::INFINITY;
668 ///
669 /// assert_eq!(num.classify(), FpCategory::Normal);
670 /// assert_eq!(inf.classify(), FpCategory::Infinite);
671 /// ```
672 #[stable(feature = "rust1", since = "1.0.0")]
673 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
674 #[cfg(not(feature = "ferrocene_certified"))]
675 pub const fn classify(self) -> FpCategory {
676 // We used to have complicated logic here that avoids the simple bit-based tests to work
677 // around buggy codegen for x87 targets (see
678 // https://github.com/rust-lang/rust/issues/114479). However, some LLVM versions later, none
679 // of our tests is able to find any difference between the complicated and the naive
680 // version, so now we are back to the naive version.
681 let b = self.to_bits();
682 match (b & Self::MAN_MASK, b & Self::EXP_MASK) {
683 (0, Self::EXP_MASK) => FpCategory::Infinite,
684 (_, Self::EXP_MASK) => FpCategory::Nan,
685 (0, 0) => FpCategory::Zero,
686 (_, 0) => FpCategory::Subnormal,
687 _ => FpCategory::Normal,
688 }
689 }
690
691 /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with
692 /// positive sign bit and positive infinity.
693 ///
694 /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
695 /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
696 /// conserved over arithmetic operations, the result of `is_sign_positive` on
697 /// a NaN might produce an unexpected or non-portable result. See the [specification
698 /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == 1.0`
699 /// if you need fully portable behavior (will return `false` for all NaNs).
700 ///
701 /// ```
702 /// let f = 7.0_f32;
703 /// let g = -7.0_f32;
704 ///
705 /// assert!(f.is_sign_positive());
706 /// assert!(!g.is_sign_positive());
707 /// ```
708 #[must_use]
709 #[stable(feature = "rust1", since = "1.0.0")]
710 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
711 #[inline]
712 #[cfg(not(feature = "ferrocene_certified"))]
713 pub const fn is_sign_positive(self) -> bool {
714 !self.is_sign_negative()
715 }
716
717 /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with
718 /// negative sign bit and negative infinity.
719 ///
720 /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
721 /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
722 /// conserved over arithmetic operations, the result of `is_sign_negative` on
723 /// a NaN might produce an unexpected or non-portable result. See the [specification
724 /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == -1.0`
725 /// if you need fully portable behavior (will return `false` for all NaNs).
726 ///
727 /// ```
728 /// let f = 7.0f32;
729 /// let g = -7.0f32;
730 ///
731 /// assert!(!f.is_sign_negative());
732 /// assert!(g.is_sign_negative());
733 /// ```
734 #[must_use]
735 #[stable(feature = "rust1", since = "1.0.0")]
736 #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
737 #[inline]
738 #[cfg(not(feature = "ferrocene_certified"))]
739 pub const fn is_sign_negative(self) -> bool {
740 // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
741 // applies to zeros and NaNs as well.
742 self.to_bits() & 0x8000_0000 != 0
743 }
744
745 /// Returns the least number greater than `self`.
746 ///
747 /// Let `TINY` be the smallest representable positive `f32`. Then,
748 /// - if `self.is_nan()`, this returns `self`;
749 /// - if `self` is [`NEG_INFINITY`], this returns [`MIN`];
750 /// - if `self` is `-TINY`, this returns -0.0;
751 /// - if `self` is -0.0 or +0.0, this returns `TINY`;
752 /// - if `self` is [`MAX`] or [`INFINITY`], this returns [`INFINITY`];
753 /// - otherwise the unique least value greater than `self` is returned.
754 ///
755 /// The identity `x.next_up() == -(-x).next_down()` holds for all non-NaN `x`. When `x`
756 /// is finite `x == x.next_up().next_down()` also holds.
757 ///
758 /// ```rust
759 /// // f32::EPSILON is the difference between 1.0 and the next number up.
760 /// assert_eq!(1.0f32.next_up(), 1.0 + f32::EPSILON);
761 /// // But not for most numbers.
762 /// assert!(0.1f32.next_up() < 0.1 + f32::EPSILON);
763 /// assert_eq!(16777216f32.next_up(), 16777218.0);
764 /// ```
765 ///
766 /// This operation corresponds to IEEE-754 `nextUp`.
767 ///
768 /// [`NEG_INFINITY`]: Self::NEG_INFINITY
769 /// [`INFINITY`]: Self::INFINITY
770 /// [`MIN`]: Self::MIN
771 /// [`MAX`]: Self::MAX
772 #[inline]
773 #[doc(alias = "nextUp")]
774 #[stable(feature = "float_next_up_down", since = "1.86.0")]
775 #[rustc_const_stable(feature = "float_next_up_down", since = "1.86.0")]
776 #[cfg(not(feature = "ferrocene_certified"))]
777 pub const fn next_up(self) -> Self {
778 // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
779 // denormals to zero. This is in general unsound and unsupported, but here
780 // we do our best to still produce the correct result on such targets.
781 let bits = self.to_bits();
782 if self.is_nan() || bits == Self::INFINITY.to_bits() {
783 return self;
784 }
785
786 let abs = bits & !Self::SIGN_MASK;
787 let next_bits = if abs == 0 {
788 Self::TINY_BITS
789 } else if bits == abs {
790 bits + 1
791 } else {
792 bits - 1
793 };
794 Self::from_bits(next_bits)
795 }
796
797 /// Returns the greatest number less than `self`.
798 ///
799 /// Let `TINY` be the smallest representable positive `f32`. Then,
800 /// - if `self.is_nan()`, this returns `self`;
801 /// - if `self` is [`INFINITY`], this returns [`MAX`];
802 /// - if `self` is `TINY`, this returns 0.0;
803 /// - if `self` is -0.0 or +0.0, this returns `-TINY`;
804 /// - if `self` is [`MIN`] or [`NEG_INFINITY`], this returns [`NEG_INFINITY`];
805 /// - otherwise the unique greatest value less than `self` is returned.
806 ///
807 /// The identity `x.next_down() == -(-x).next_up()` holds for all non-NaN `x`. When `x`
808 /// is finite `x == x.next_down().next_up()` also holds.
809 ///
810 /// ```rust
811 /// let x = 1.0f32;
812 /// // Clamp value into range [0, 1).
813 /// let clamped = x.clamp(0.0, 1.0f32.next_down());
814 /// assert!(clamped < 1.0);
815 /// assert_eq!(clamped.next_up(), 1.0);
816 /// ```
817 ///
818 /// This operation corresponds to IEEE-754 `nextDown`.
819 ///
820 /// [`NEG_INFINITY`]: Self::NEG_INFINITY
821 /// [`INFINITY`]: Self::INFINITY
822 /// [`MIN`]: Self::MIN
823 /// [`MAX`]: Self::MAX
824 #[inline]
825 #[doc(alias = "nextDown")]
826 #[stable(feature = "float_next_up_down", since = "1.86.0")]
827 #[rustc_const_stable(feature = "float_next_up_down", since = "1.86.0")]
828 #[cfg(not(feature = "ferrocene_certified"))]
829 pub const fn next_down(self) -> Self {
830 // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
831 // denormals to zero. This is in general unsound and unsupported, but here
832 // we do our best to still produce the correct result on such targets.
833 let bits = self.to_bits();
834 if self.is_nan() || bits == Self::NEG_INFINITY.to_bits() {
835 return self;
836 }
837
838 let abs = bits & !Self::SIGN_MASK;
839 let next_bits = if abs == 0 {
840 Self::NEG_TINY_BITS
841 } else if bits == abs {
842 bits - 1
843 } else {
844 bits + 1
845 };
846 Self::from_bits(next_bits)
847 }
848
849 /// Takes the reciprocal (inverse) of a number, `1/x`.
850 ///
851 /// ```
852 /// let x = 2.0_f32;
853 /// let abs_difference = (x.recip() - (1.0 / x)).abs();
854 ///
855 /// assert!(abs_difference <= f32::EPSILON);
856 /// ```
857 #[must_use = "this returns the result of the operation, without modifying the original"]
858 #[stable(feature = "rust1", since = "1.0.0")]
859 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
860 #[inline]
861 #[cfg(not(feature = "ferrocene_certified"))]
862 pub const fn recip(self) -> f32 {
863 1.0 / self
864 }
865
866 /// Converts radians to degrees.
867 ///
868 /// # Unspecified precision
869 ///
870 /// The precision of this function is non-deterministic. This means it varies by platform,
871 /// Rust version, and can even differ within the same execution from one invocation to the next.
872 ///
873 /// # Examples
874 ///
875 /// ```
876 /// let angle = std::f32::consts::PI;
877 ///
878 /// let abs_difference = (angle.to_degrees() - 180.0).abs();
879 /// # #[cfg(any(not(target_arch = "x86"), target_feature = "sse2"))]
880 /// assert!(abs_difference <= f32::EPSILON);
881 /// ```
882 #[must_use = "this returns the result of the operation, \
883 without modifying the original"]
884 #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
885 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
886 #[inline]
887 #[cfg(not(feature = "ferrocene_certified"))]
888 pub const fn to_degrees(self) -> f32 {
889 // Use a literal to avoid double rounding, consts::PI is already rounded,
890 // and dividing would round again.
891 const PIS_IN_180: f32 = 57.2957795130823208767981548141051703_f32;
892 self * PIS_IN_180
893 }
894
895 /// Converts degrees to radians.
896 ///
897 /// # Unspecified precision
898 ///
899 /// The precision of this function is non-deterministic. This means it varies by platform,
900 /// Rust version, and can even differ within the same execution from one invocation to the next.
901 ///
902 /// # Examples
903 ///
904 /// ```
905 /// let angle = 180.0f32;
906 ///
907 /// let abs_difference = (angle.to_radians() - std::f32::consts::PI).abs();
908 ///
909 /// assert!(abs_difference <= f32::EPSILON);
910 /// ```
911 #[must_use = "this returns the result of the operation, \
912 without modifying the original"]
913 #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
914 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
915 #[inline]
916 #[cfg(not(feature = "ferrocene_certified"))]
917 pub const fn to_radians(self) -> f32 {
918 // The division here is correctly rounded with respect to the true value of π/180.
919 // Although π is irrational and already rounded, the double rounding happens
920 // to produce correct result for f32.
921 const RADS_PER_DEG: f32 = consts::PI / 180.0;
922 self * RADS_PER_DEG
923 }
924
925 /// Returns the maximum of the two numbers, ignoring NaN.
926 ///
927 /// If one of the arguments is NaN, then the other argument is returned.
928 /// This follows the IEEE 754-2008 semantics for maxNum, except for handling of signaling NaNs;
929 /// this function handles all NaNs the same way and avoids maxNum's problems with associativity.
930 /// This also matches the behavior of libm’s fmax. In particular, if the inputs compare equal
931 /// (such as for the case of `+0.0` and `-0.0`), either input may be returned non-deterministically.
932 ///
933 /// ```
934 /// let x = 1.0f32;
935 /// let y = 2.0f32;
936 ///
937 /// assert_eq!(x.max(y), y);
938 /// ```
939 #[must_use = "this returns the result of the comparison, without modifying either input"]
940 #[stable(feature = "rust1", since = "1.0.0")]
941 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
942 #[inline]
943 #[cfg(not(feature = "ferrocene_certified"))]
944 pub const fn max(self, other: f32) -> f32 {
945 intrinsics::maxnumf32(self, other)
946 }
947
948 /// Returns the minimum of the two numbers, ignoring NaN.
949 ///
950 /// If one of the arguments is NaN, then the other argument is returned.
951 /// This follows the IEEE 754-2008 semantics for minNum, except for handling of signaling NaNs;
952 /// this function handles all NaNs the same way and avoids minNum's problems with associativity.
953 /// This also matches the behavior of libm’s fmin. In particular, if the inputs compare equal
954 /// (such as for the case of `+0.0` and `-0.0`), either input may be returned non-deterministically.
955 ///
956 /// ```
957 /// let x = 1.0f32;
958 /// let y = 2.0f32;
959 ///
960 /// assert_eq!(x.min(y), x);
961 /// ```
962 #[must_use = "this returns the result of the comparison, without modifying either input"]
963 #[stable(feature = "rust1", since = "1.0.0")]
964 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
965 #[inline]
966 #[cfg(not(feature = "ferrocene_certified"))]
967 pub const fn min(self, other: f32) -> f32 {
968 intrinsics::minnumf32(self, other)
969 }
970
971 /// Returns the maximum of the two numbers, propagating NaN.
972 ///
973 /// This returns NaN when *either* argument is NaN, as opposed to
974 /// [`f32::max`] which only returns NaN when *both* arguments are NaN.
975 ///
976 /// ```
977 /// #![feature(float_minimum_maximum)]
978 /// let x = 1.0f32;
979 /// let y = 2.0f32;
980 ///
981 /// assert_eq!(x.maximum(y), y);
982 /// assert!(x.maximum(f32::NAN).is_nan());
983 /// ```
984 ///
985 /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the greater
986 /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
987 /// Note that this follows the semantics specified in IEEE 754-2019.
988 ///
989 /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
990 /// operand is conserved; see the [specification of NaN bit patterns](f32#nan-bit-patterns) for more info.
991 #[must_use = "this returns the result of the comparison, without modifying either input"]
992 #[unstable(feature = "float_minimum_maximum", issue = "91079")]
993 #[inline]
994 #[cfg(not(feature = "ferrocene_certified"))]
995 pub const fn maximum(self, other: f32) -> f32 {
996 intrinsics::maximumf32(self, other)
997 }
998
999 /// Returns the minimum of the two numbers, propagating NaN.
1000 ///
1001 /// This returns NaN when *either* argument is NaN, as opposed to
1002 /// [`f32::min`] which only returns NaN when *both* arguments are NaN.
1003 ///
1004 /// ```
1005 /// #![feature(float_minimum_maximum)]
1006 /// let x = 1.0f32;
1007 /// let y = 2.0f32;
1008 ///
1009 /// assert_eq!(x.minimum(y), x);
1010 /// assert!(x.minimum(f32::NAN).is_nan());
1011 /// ```
1012 ///
1013 /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the lesser
1014 /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
1015 /// Note that this follows the semantics specified in IEEE 754-2019.
1016 ///
1017 /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
1018 /// operand is conserved; see the [specification of NaN bit patterns](f32#nan-bit-patterns) for more info.
1019 #[must_use = "this returns the result of the comparison, without modifying either input"]
1020 #[unstable(feature = "float_minimum_maximum", issue = "91079")]
1021 #[inline]
1022 #[cfg(not(feature = "ferrocene_certified"))]
1023 pub const fn minimum(self, other: f32) -> f32 {
1024 intrinsics::minimumf32(self, other)
1025 }
1026
1027 /// Calculates the midpoint (average) between `self` and `rhs`.
1028 ///
1029 /// This returns NaN when *either* argument is NaN or if a combination of
1030 /// +inf and -inf is provided as arguments.
1031 ///
1032 /// # Examples
1033 ///
1034 /// ```
1035 /// assert_eq!(1f32.midpoint(4.0), 2.5);
1036 /// assert_eq!((-5.5f32).midpoint(8.0), 1.25);
1037 /// ```
1038 #[inline]
1039 #[doc(alias = "average")]
1040 #[stable(feature = "num_midpoint", since = "1.85.0")]
1041 #[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
1042 #[cfg(not(feature = "ferrocene_certified"))]
1043 pub const fn midpoint(self, other: f32) -> f32 {
1044 cfg_select! {
1045 // Allow faster implementation that have known good 64-bit float
1046 // implementations. Falling back to the branchy code on targets that don't
1047 // have 64-bit hardware floats or buggy implementations.
1048 // https://github.com/rust-lang/rust/pull/121062#issuecomment-2123408114
1049 any(
1050 target_arch = "x86_64",
1051 target_arch = "aarch64",
1052 all(any(target_arch = "riscv32", target_arch = "riscv64"), target_feature = "d"),
1053 all(target_arch = "loongarch64", target_feature = "d"),
1054 all(target_arch = "arm", target_feature = "vfp2"),
1055 target_arch = "wasm32",
1056 target_arch = "wasm64",
1057 ) => {
1058 ((self as f64 + other as f64) / 2.0) as f32
1059 }
1060 _ => {
1061 const HI: f32 = f32::MAX / 2.;
1062
1063 let (a, b) = (self, other);
1064 let abs_a = a.abs();
1065 let abs_b = b.abs();
1066
1067 if abs_a <= HI && abs_b <= HI {
1068 // Overflow is impossible
1069 (a + b) / 2.
1070 } else {
1071 (a / 2.) + (b / 2.)
1072 }
1073 }
1074 }
1075 }
1076
1077 /// Rounds toward zero and converts to any primitive integer type,
1078 /// assuming that the value is finite and fits in that type.
1079 ///
1080 /// ```
1081 /// let value = 4.6_f32;
1082 /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
1083 /// assert_eq!(rounded, 4);
1084 ///
1085 /// let value = -128.9_f32;
1086 /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
1087 /// assert_eq!(rounded, i8::MIN);
1088 /// ```
1089 ///
1090 /// # Safety
1091 ///
1092 /// The value must:
1093 ///
1094 /// * Not be `NaN`
1095 /// * Not be infinite
1096 /// * Be representable in the return type `Int`, after truncating off its fractional part
1097 #[must_use = "this returns the result of the operation, \
1098 without modifying the original"]
1099 #[stable(feature = "float_approx_unchecked_to", since = "1.44.0")]
1100 #[inline]
1101 #[cfg(not(feature = "ferrocene_certified"))]
1102 pub unsafe fn to_int_unchecked<Int>(self) -> Int
1103 where
1104 Self: FloatToInt<Int>,
1105 {
1106 // SAFETY: the caller must uphold the safety contract for
1107 // `FloatToInt::to_int_unchecked`.
1108 unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
1109 }
1110
1111 /// Raw transmutation to `u32`.
1112 ///
1113 /// This is currently identical to `transmute::<f32, u32>(self)` on all platforms.
1114 ///
1115 /// See [`from_bits`](Self::from_bits) for some discussion of the
1116 /// portability of this operation (there are almost no issues).
1117 ///
1118 /// Note that this function is distinct from `as` casting, which attempts to
1119 /// preserve the *numeric* value, and not the bitwise value.
1120 ///
1121 /// # Examples
1122 ///
1123 /// ```
1124 /// assert_ne!((1f32).to_bits(), 1f32 as u32); // to_bits() is not casting!
1125 /// assert_eq!((12.5f32).to_bits(), 0x41480000);
1126 ///
1127 /// ```
1128 #[must_use = "this returns the result of the operation, \
1129 without modifying the original"]
1130 #[stable(feature = "float_bits_conv", since = "1.20.0")]
1131 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1132 #[inline]
1133 #[allow(unnecessary_transmutes)]
1134 pub const fn to_bits(self) -> u32 {
1135 // SAFETY: `u32` is a plain old datatype so we can always transmute to it.
1136 unsafe { mem::transmute(self) }
1137 }
1138
1139 /// Raw transmutation from `u32`.
1140 ///
1141 /// This is currently identical to `transmute::<u32, f32>(v)` on all platforms.
1142 /// It turns out this is incredibly portable, for two reasons:
1143 ///
1144 /// * Floats and Ints have the same endianness on all supported platforms.
1145 /// * IEEE 754 very precisely specifies the bit layout of floats.
1146 ///
1147 /// However there is one caveat: prior to the 2008 version of IEEE 754, how
1148 /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
1149 /// (notably x86 and ARM) picked the interpretation that was ultimately
1150 /// standardized in 2008, but some didn't (notably MIPS). As a result, all
1151 /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
1152 ///
1153 /// Rather than trying to preserve signaling-ness cross-platform, this
1154 /// implementation favors preserving the exact bits. This means that
1155 /// any payloads encoded in NaNs will be preserved even if the result of
1156 /// this method is sent over the network from an x86 machine to a MIPS one.
1157 ///
1158 /// If the results of this method are only manipulated by the same
1159 /// architecture that produced them, then there is no portability concern.
1160 ///
1161 /// If the input isn't NaN, then there is no portability concern.
1162 ///
1163 /// If you don't care about signalingness (very likely), then there is no
1164 /// portability concern.
1165 ///
1166 /// Note that this function is distinct from `as` casting, which attempts to
1167 /// preserve the *numeric* value, and not the bitwise value.
1168 ///
1169 /// # Examples
1170 ///
1171 /// ```
1172 /// let v = f32::from_bits(0x41480000);
1173 /// assert_eq!(v, 12.5);
1174 /// ```
1175 #[stable(feature = "float_bits_conv", since = "1.20.0")]
1176 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1177 #[must_use]
1178 #[inline]
1179 #[allow(unnecessary_transmutes)]
1180 pub const fn from_bits(v: u32) -> Self {
1181 // It turns out the safety issues with sNaN were overblown! Hooray!
1182 // SAFETY: `u32` is a plain old datatype so we can always transmute from it.
1183 unsafe { mem::transmute(v) }
1184 }
1185
1186 /// Returns the memory representation of this floating point number as a byte array in
1187 /// big-endian (network) byte order.
1188 ///
1189 /// See [`from_bits`](Self::from_bits) for some discussion of the
1190 /// portability of this operation (there are almost no issues).
1191 ///
1192 /// # Examples
1193 ///
1194 /// ```
1195 /// let bytes = 12.5f32.to_be_bytes();
1196 /// assert_eq!(bytes, [0x41, 0x48, 0x00, 0x00]);
1197 /// ```
1198 #[must_use = "this returns the result of the operation, \
1199 without modifying the original"]
1200 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1201 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1202 #[inline]
1203 #[cfg(not(feature = "ferrocene_certified"))]
1204 pub const fn to_be_bytes(self) -> [u8; 4] {
1205 self.to_bits().to_be_bytes()
1206 }
1207
1208 /// Returns the memory representation of this floating point number as a byte array in
1209 /// little-endian byte order.
1210 ///
1211 /// See [`from_bits`](Self::from_bits) for some discussion of the
1212 /// portability of this operation (there are almost no issues).
1213 ///
1214 /// # Examples
1215 ///
1216 /// ```
1217 /// let bytes = 12.5f32.to_le_bytes();
1218 /// assert_eq!(bytes, [0x00, 0x00, 0x48, 0x41]);
1219 /// ```
1220 #[must_use = "this returns the result of the operation, \
1221 without modifying the original"]
1222 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1223 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1224 #[inline]
1225 pub const fn to_le_bytes(self) -> [u8; 4] {
1226 self.to_bits().to_le_bytes()
1227 }
1228
1229 /// Returns the memory representation of this floating point number as a byte array in
1230 /// native byte order.
1231 ///
1232 /// As the target platform's native endianness is used, portable code
1233 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1234 ///
1235 /// [`to_be_bytes`]: f32::to_be_bytes
1236 /// [`to_le_bytes`]: f32::to_le_bytes
1237 ///
1238 /// See [`from_bits`](Self::from_bits) for some discussion of the
1239 /// portability of this operation (there are almost no issues).
1240 ///
1241 /// # Examples
1242 ///
1243 /// ```
1244 /// let bytes = 12.5f32.to_ne_bytes();
1245 /// assert_eq!(
1246 /// bytes,
1247 /// if cfg!(target_endian = "big") {
1248 /// [0x41, 0x48, 0x00, 0x00]
1249 /// } else {
1250 /// [0x00, 0x00, 0x48, 0x41]
1251 /// }
1252 /// );
1253 /// ```
1254 #[must_use = "this returns the result of the operation, \
1255 without modifying the original"]
1256 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1257 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1258 #[inline]
1259 #[cfg(not(feature = "ferrocene_certified"))]
1260 pub const fn to_ne_bytes(self) -> [u8; 4] {
1261 self.to_bits().to_ne_bytes()
1262 }
1263
1264 /// Creates a floating point value from its representation as a byte array in big endian.
1265 ///
1266 /// See [`from_bits`](Self::from_bits) for some discussion of the
1267 /// portability of this operation (there are almost no issues).
1268 ///
1269 /// # Examples
1270 ///
1271 /// ```
1272 /// let value = f32::from_be_bytes([0x41, 0x48, 0x00, 0x00]);
1273 /// assert_eq!(value, 12.5);
1274 /// ```
1275 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1276 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1277 #[must_use]
1278 #[inline]
1279 #[cfg(not(feature = "ferrocene_certified"))]
1280 pub const fn from_be_bytes(bytes: [u8; 4]) -> Self {
1281 Self::from_bits(u32::from_be_bytes(bytes))
1282 }
1283
1284 /// Creates a floating point value from its representation as a byte array in little endian.
1285 ///
1286 /// See [`from_bits`](Self::from_bits) for some discussion of the
1287 /// portability of this operation (there are almost no issues).
1288 ///
1289 /// # Examples
1290 ///
1291 /// ```
1292 /// let value = f32::from_le_bytes([0x00, 0x00, 0x48, 0x41]);
1293 /// assert_eq!(value, 12.5);
1294 /// ```
1295 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1296 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1297 #[must_use]
1298 #[inline]
1299 pub const fn from_le_bytes(bytes: [u8; 4]) -> Self {
1300 Self::from_bits(u32::from_le_bytes(bytes))
1301 }
1302
1303 /// Creates a floating point value from its representation as a byte array in native endian.
1304 ///
1305 /// As the target platform's native endianness is used, portable code
1306 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1307 /// appropriate instead.
1308 ///
1309 /// [`from_be_bytes`]: f32::from_be_bytes
1310 /// [`from_le_bytes`]: f32::from_le_bytes
1311 ///
1312 /// See [`from_bits`](Self::from_bits) for some discussion of the
1313 /// portability of this operation (there are almost no issues).
1314 ///
1315 /// # Examples
1316 ///
1317 /// ```
1318 /// let value = f32::from_ne_bytes(if cfg!(target_endian = "big") {
1319 /// [0x41, 0x48, 0x00, 0x00]
1320 /// } else {
1321 /// [0x00, 0x00, 0x48, 0x41]
1322 /// });
1323 /// assert_eq!(value, 12.5);
1324 /// ```
1325 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1326 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1327 #[must_use]
1328 #[inline]
1329 #[cfg(not(feature = "ferrocene_certified"))]
1330 pub const fn from_ne_bytes(bytes: [u8; 4]) -> Self {
1331 Self::from_bits(u32::from_ne_bytes(bytes))
1332 }
1333
1334 /// Returns the ordering between `self` and `other`.
1335 ///
1336 /// Unlike the standard partial comparison between floating point numbers,
1337 /// this comparison always produces an ordering in accordance to
1338 /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1339 /// floating point standard. The values are ordered in the following sequence:
1340 ///
1341 /// - negative quiet NaN
1342 /// - negative signaling NaN
1343 /// - negative infinity
1344 /// - negative numbers
1345 /// - negative subnormal numbers
1346 /// - negative zero
1347 /// - positive zero
1348 /// - positive subnormal numbers
1349 /// - positive numbers
1350 /// - positive infinity
1351 /// - positive signaling NaN
1352 /// - positive quiet NaN.
1353 ///
1354 /// The ordering established by this function does not always agree with the
1355 /// [`PartialOrd`] and [`PartialEq`] implementations of `f32`. For example,
1356 /// they consider negative and positive zero equal, while `total_cmp`
1357 /// doesn't.
1358 ///
1359 /// The interpretation of the signaling NaN bit follows the definition in
1360 /// the IEEE 754 standard, which may not match the interpretation by some of
1361 /// the older, non-conformant (e.g. MIPS) hardware implementations.
1362 ///
1363 /// # Example
1364 ///
1365 /// ```
1366 /// struct GoodBoy {
1367 /// name: String,
1368 /// weight: f32,
1369 /// }
1370 ///
1371 /// let mut bois = vec![
1372 /// GoodBoy { name: "Pucci".to_owned(), weight: 0.1 },
1373 /// GoodBoy { name: "Woofer".to_owned(), weight: 99.0 },
1374 /// GoodBoy { name: "Yapper".to_owned(), weight: 10.0 },
1375 /// GoodBoy { name: "Chonk".to_owned(), weight: f32::INFINITY },
1376 /// GoodBoy { name: "Abs. Unit".to_owned(), weight: f32::NAN },
1377 /// GoodBoy { name: "Floaty".to_owned(), weight: -5.0 },
1378 /// ];
1379 ///
1380 /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1381 ///
1382 /// // `f32::NAN` could be positive or negative, which will affect the sort order.
1383 /// if f32::NAN.is_sign_negative() {
1384 /// assert!(bois.into_iter().map(|b| b.weight)
1385 /// .zip([f32::NAN, -5.0, 0.1, 10.0, 99.0, f32::INFINITY].iter())
1386 /// .all(|(a, b)| a.to_bits() == b.to_bits()))
1387 /// } else {
1388 /// assert!(bois.into_iter().map(|b| b.weight)
1389 /// .zip([-5.0, 0.1, 10.0, 99.0, f32::INFINITY, f32::NAN].iter())
1390 /// .all(|(a, b)| a.to_bits() == b.to_bits()))
1391 /// }
1392 /// ```
1393 #[stable(feature = "total_cmp", since = "1.62.0")]
1394 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1395 #[must_use]
1396 #[inline]
1397 #[cfg(not(feature = "ferrocene_certified"))]
1398 pub const fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1399 let mut left = self.to_bits() as i32;
1400 let mut right = other.to_bits() as i32;
1401
1402 // In case of negatives, flip all the bits except the sign
1403 // to achieve a similar layout as two's complement integers
1404 //
1405 // Why does this work? IEEE 754 floats consist of three fields:
1406 // Sign bit, exponent and mantissa. The set of exponent and mantissa
1407 // fields as a whole have the property that their bitwise order is
1408 // equal to the numeric magnitude where the magnitude is defined.
1409 // The magnitude is not normally defined on NaN values, but
1410 // IEEE 754 totalOrder defines the NaN values also to follow the
1411 // bitwise order. This leads to order explained in the doc comment.
1412 // However, the representation of magnitude is the same for negative
1413 // and positive numbers – only the sign bit is different.
1414 // To easily compare the floats as signed integers, we need to
1415 // flip the exponent and mantissa bits in case of negative numbers.
1416 // We effectively convert the numbers to "two's complement" form.
1417 //
1418 // To do the flipping, we construct a mask and XOR against it.
1419 // We branchlessly calculate an "all-ones except for the sign bit"
1420 // mask from negative-signed values: right shifting sign-extends
1421 // the integer, so we "fill" the mask with sign bits, and then
1422 // convert to unsigned to push one more zero bit.
1423 // On positive values, the mask is all zeros, so it's a no-op.
1424 left ^= (((left >> 31) as u32) >> 1) as i32;
1425 right ^= (((right >> 31) as u32) >> 1) as i32;
1426
1427 left.cmp(&right)
1428 }
1429
1430 /// Restrict a value to a certain interval unless it is NaN.
1431 ///
1432 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1433 /// less than `min`. Otherwise this returns `self`.
1434 ///
1435 /// Note that this function returns NaN if the initial value was NaN as
1436 /// well.
1437 ///
1438 /// # Panics
1439 ///
1440 /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1441 ///
1442 /// # Examples
1443 ///
1444 /// ```
1445 /// assert!((-3.0f32).clamp(-2.0, 1.0) == -2.0);
1446 /// assert!((0.0f32).clamp(-2.0, 1.0) == 0.0);
1447 /// assert!((2.0f32).clamp(-2.0, 1.0) == 1.0);
1448 /// assert!((f32::NAN).clamp(-2.0, 1.0).is_nan());
1449 /// ```
1450 #[must_use = "method returns a new number and does not mutate the original value"]
1451 #[stable(feature = "clamp", since = "1.50.0")]
1452 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1453 #[inline]
1454 #[cfg(not(feature = "ferrocene_certified"))]
1455 pub const fn clamp(mut self, min: f32, max: f32) -> f32 {
1456 const_assert!(
1457 min <= max,
1458 "min > max, or either was NaN",
1459 "min > max, or either was NaN. min = {min:?}, max = {max:?}",
1460 min: f32,
1461 max: f32,
1462 );
1463
1464 if self < min {
1465 self = min;
1466 }
1467 if self > max {
1468 self = max;
1469 }
1470 self
1471 }
1472
1473 /// Computes the absolute value of `self`.
1474 ///
1475 /// This function always returns the precise result.
1476 ///
1477 /// # Examples
1478 ///
1479 /// ```
1480 /// let x = 3.5_f32;
1481 /// let y = -3.5_f32;
1482 ///
1483 /// assert_eq!(x.abs(), x);
1484 /// assert_eq!(y.abs(), -y);
1485 ///
1486 /// assert!(f32::NAN.abs().is_nan());
1487 /// ```
1488 #[must_use = "method returns a new number and does not mutate the original value"]
1489 #[stable(feature = "rust1", since = "1.0.0")]
1490 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1491 #[inline]
1492 #[cfg(not(feature = "ferrocene_certified"))]
1493 pub const fn abs(self) -> f32 {
1494 intrinsics::fabsf32(self)
1495 }
1496
1497 /// Returns a number that represents the sign of `self`.
1498 ///
1499 /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
1500 /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
1501 /// - NaN if the number is NaN
1502 ///
1503 /// # Examples
1504 ///
1505 /// ```
1506 /// let f = 3.5_f32;
1507 ///
1508 /// assert_eq!(f.signum(), 1.0);
1509 /// assert_eq!(f32::NEG_INFINITY.signum(), -1.0);
1510 ///
1511 /// assert!(f32::NAN.signum().is_nan());
1512 /// ```
1513 #[must_use = "method returns a new number and does not mutate the original value"]
1514 #[stable(feature = "rust1", since = "1.0.0")]
1515 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1516 #[inline]
1517 #[cfg(not(feature = "ferrocene_certified"))]
1518 pub const fn signum(self) -> f32 {
1519 if self.is_nan() { Self::NAN } else { 1.0_f32.copysign(self) }
1520 }
1521
1522 /// Returns a number composed of the magnitude of `self` and the sign of
1523 /// `sign`.
1524 ///
1525 /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`.
1526 /// If `self` is a NaN, then a NaN with the same payload as `self` and the sign bit of `sign` is
1527 /// returned.
1528 ///
1529 /// If `sign` is a NaN, then this operation will still carry over its sign into the result. Note
1530 /// that IEEE 754 doesn't assign any meaning to the sign bit in case of a NaN, and as Rust
1531 /// doesn't guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the
1532 /// result of `copysign` with `sign` being a NaN might produce an unexpected or non-portable
1533 /// result. See the [specification of NaN bit patterns](primitive@f32#nan-bit-patterns) for more
1534 /// info.
1535 ///
1536 /// # Examples
1537 ///
1538 /// ```
1539 /// let f = 3.5_f32;
1540 ///
1541 /// assert_eq!(f.copysign(0.42), 3.5_f32);
1542 /// assert_eq!(f.copysign(-0.42), -3.5_f32);
1543 /// assert_eq!((-f).copysign(0.42), 3.5_f32);
1544 /// assert_eq!((-f).copysign(-0.42), -3.5_f32);
1545 ///
1546 /// assert!(f32::NAN.copysign(1.0).is_nan());
1547 /// ```
1548 #[must_use = "method returns a new number and does not mutate the original value"]
1549 #[inline]
1550 #[stable(feature = "copysign", since = "1.35.0")]
1551 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1552 #[cfg(not(feature = "ferrocene_certified"))]
1553 pub const fn copysign(self, sign: f32) -> f32 {
1554 intrinsics::copysignf32(self, sign)
1555 }
1556
1557 /// Float addition that allows optimizations based on algebraic rules.
1558 ///
1559 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1560 #[must_use = "method returns a new number and does not mutate the original value"]
1561 #[unstable(feature = "float_algebraic", issue = "136469")]
1562 #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1563 #[inline]
1564 #[cfg(not(feature = "ferrocene_certified"))]
1565 pub const fn algebraic_add(self, rhs: f32) -> f32 {
1566 intrinsics::fadd_algebraic(self, rhs)
1567 }
1568
1569 /// Float subtraction that allows optimizations based on algebraic rules.
1570 ///
1571 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1572 #[must_use = "method returns a new number and does not mutate the original value"]
1573 #[unstable(feature = "float_algebraic", issue = "136469")]
1574 #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1575 #[inline]
1576 #[cfg(not(feature = "ferrocene_certified"))]
1577 pub const fn algebraic_sub(self, rhs: f32) -> f32 {
1578 intrinsics::fsub_algebraic(self, rhs)
1579 }
1580
1581 /// Float multiplication that allows optimizations based on algebraic rules.
1582 ///
1583 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1584 #[must_use = "method returns a new number and does not mutate the original value"]
1585 #[unstable(feature = "float_algebraic", issue = "136469")]
1586 #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1587 #[inline]
1588 #[cfg(not(feature = "ferrocene_certified"))]
1589 pub const fn algebraic_mul(self, rhs: f32) -> f32 {
1590 intrinsics::fmul_algebraic(self, rhs)
1591 }
1592
1593 /// Float division that allows optimizations based on algebraic rules.
1594 ///
1595 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1596 #[must_use = "method returns a new number and does not mutate the original value"]
1597 #[unstable(feature = "float_algebraic", issue = "136469")]
1598 #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1599 #[inline]
1600 #[cfg(not(feature = "ferrocene_certified"))]
1601 pub const fn algebraic_div(self, rhs: f32) -> f32 {
1602 intrinsics::fdiv_algebraic(self, rhs)
1603 }
1604
1605 /// Float remainder that allows optimizations based on algebraic rules.
1606 ///
1607 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1608 #[must_use = "method returns a new number and does not mutate the original value"]
1609 #[unstable(feature = "float_algebraic", issue = "136469")]
1610 #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1611 #[inline]
1612 #[cfg(not(feature = "ferrocene_certified"))]
1613 pub const fn algebraic_rem(self, rhs: f32) -> f32 {
1614 intrinsics::frem_algebraic(self, rhs)
1615 }
1616}
1617
1618/// Experimental implementations of floating point functions in `core`.
1619///
1620/// _The standalone functions in this module are for testing only.
1621/// They will be stabilized as inherent methods._
1622#[unstable(feature = "core_float_math", issue = "137578")]
1623#[cfg(not(feature = "ferrocene_certified"))]
1624pub mod math {
1625 use crate::intrinsics;
1626 use crate::num::libm;
1627
1628 /// Experimental version of `floor` in `core`. See [`f32::floor`] for details.
1629 ///
1630 /// # Examples
1631 ///
1632 /// ```
1633 /// #![feature(core_float_math)]
1634 ///
1635 /// use core::f32;
1636 ///
1637 /// let f = 3.7_f32;
1638 /// let g = 3.0_f32;
1639 /// let h = -3.7_f32;
1640 ///
1641 /// assert_eq!(f32::math::floor(f), 3.0);
1642 /// assert_eq!(f32::math::floor(g), 3.0);
1643 /// assert_eq!(f32::math::floor(h), -4.0);
1644 /// ```
1645 ///
1646 /// _This standalone function is for testing only.
1647 /// It will be stabilized as an inherent method._
1648 ///
1649 /// [`f32::floor`]: ../../../std/primitive.f32.html#method.floor
1650 #[inline]
1651 #[unstable(feature = "core_float_math", issue = "137578")]
1652 #[must_use = "method returns a new number and does not mutate the original value"]
1653 pub const fn floor(x: f32) -> f32 {
1654 intrinsics::floorf32(x)
1655 }
1656
1657 /// Experimental version of `ceil` in `core`. See [`f32::ceil`] for details.
1658 ///
1659 /// # Examples
1660 ///
1661 /// ```
1662 /// #![feature(core_float_math)]
1663 ///
1664 /// use core::f32;
1665 ///
1666 /// let f = 3.01_f32;
1667 /// let g = 4.0_f32;
1668 ///
1669 /// assert_eq!(f32::math::ceil(f), 4.0);
1670 /// assert_eq!(f32::math::ceil(g), 4.0);
1671 /// ```
1672 ///
1673 /// _This standalone function is for testing only.
1674 /// It will be stabilized as an inherent method._
1675 ///
1676 /// [`f32::ceil`]: ../../../std/primitive.f32.html#method.ceil
1677 #[inline]
1678 #[doc(alias = "ceiling")]
1679 #[must_use = "method returns a new number and does not mutate the original value"]
1680 #[unstable(feature = "core_float_math", issue = "137578")]
1681 pub const fn ceil(x: f32) -> f32 {
1682 intrinsics::ceilf32(x)
1683 }
1684
1685 /// Experimental version of `round` in `core`. See [`f32::round`] for details.
1686 ///
1687 /// # Examples
1688 ///
1689 /// ```
1690 /// #![feature(core_float_math)]
1691 ///
1692 /// use core::f32;
1693 ///
1694 /// let f = 3.3_f32;
1695 /// let g = -3.3_f32;
1696 /// let h = -3.7_f32;
1697 /// let i = 3.5_f32;
1698 /// let j = 4.5_f32;
1699 ///
1700 /// assert_eq!(f32::math::round(f), 3.0);
1701 /// assert_eq!(f32::math::round(g), -3.0);
1702 /// assert_eq!(f32::math::round(h), -4.0);
1703 /// assert_eq!(f32::math::round(i), 4.0);
1704 /// assert_eq!(f32::math::round(j), 5.0);
1705 /// ```
1706 ///
1707 /// _This standalone function is for testing only.
1708 /// It will be stabilized as an inherent method._
1709 ///
1710 /// [`f32::round`]: ../../../std/primitive.f32.html#method.round
1711 #[inline]
1712 #[unstable(feature = "core_float_math", issue = "137578")]
1713 #[must_use = "method returns a new number and does not mutate the original value"]
1714 pub const fn round(x: f32) -> f32 {
1715 intrinsics::roundf32(x)
1716 }
1717
1718 /// Experimental version of `round_ties_even` in `core`. See [`f32::round_ties_even`] for
1719 /// details.
1720 ///
1721 /// # Examples
1722 ///
1723 /// ```
1724 /// #![feature(core_float_math)]
1725 ///
1726 /// use core::f32;
1727 ///
1728 /// let f = 3.3_f32;
1729 /// let g = -3.3_f32;
1730 /// let h = 3.5_f32;
1731 /// let i = 4.5_f32;
1732 ///
1733 /// assert_eq!(f32::math::round_ties_even(f), 3.0);
1734 /// assert_eq!(f32::math::round_ties_even(g), -3.0);
1735 /// assert_eq!(f32::math::round_ties_even(h), 4.0);
1736 /// assert_eq!(f32::math::round_ties_even(i), 4.0);
1737 /// ```
1738 ///
1739 /// _This standalone function is for testing only.
1740 /// It will be stabilized as an inherent method._
1741 ///
1742 /// [`f32::round_ties_even`]: ../../../std/primitive.f32.html#method.round_ties_even
1743 #[inline]
1744 #[unstable(feature = "core_float_math", issue = "137578")]
1745 #[must_use = "method returns a new number and does not mutate the original value"]
1746 pub const fn round_ties_even(x: f32) -> f32 {
1747 intrinsics::round_ties_even_f32(x)
1748 }
1749
1750 /// Experimental version of `trunc` in `core`. See [`f32::trunc`] for details.
1751 ///
1752 /// # Examples
1753 ///
1754 /// ```
1755 /// #![feature(core_float_math)]
1756 ///
1757 /// use core::f32;
1758 ///
1759 /// let f = 3.7_f32;
1760 /// let g = 3.0_f32;
1761 /// let h = -3.7_f32;
1762 ///
1763 /// assert_eq!(f32::math::trunc(f), 3.0);
1764 /// assert_eq!(f32::math::trunc(g), 3.0);
1765 /// assert_eq!(f32::math::trunc(h), -3.0);
1766 /// ```
1767 ///
1768 /// _This standalone function is for testing only.
1769 /// It will be stabilized as an inherent method._
1770 ///
1771 /// [`f32::trunc`]: ../../../std/primitive.f32.html#method.trunc
1772 #[inline]
1773 #[doc(alias = "truncate")]
1774 #[must_use = "method returns a new number and does not mutate the original value"]
1775 #[unstable(feature = "core_float_math", issue = "137578")]
1776 pub const fn trunc(x: f32) -> f32 {
1777 intrinsics::truncf32(x)
1778 }
1779
1780 /// Experimental version of `fract` in `core`. See [`f32::fract`] for details.
1781 ///
1782 /// # Examples
1783 ///
1784 /// ```
1785 /// #![feature(core_float_math)]
1786 ///
1787 /// use core::f32;
1788 ///
1789 /// let x = 3.6_f32;
1790 /// let y = -3.6_f32;
1791 /// let abs_difference_x = (f32::math::fract(x) - 0.6).abs();
1792 /// let abs_difference_y = (f32::math::fract(y) - (-0.6)).abs();
1793 ///
1794 /// assert!(abs_difference_x <= f32::EPSILON);
1795 /// assert!(abs_difference_y <= f32::EPSILON);
1796 /// ```
1797 ///
1798 /// _This standalone function is for testing only.
1799 /// It will be stabilized as an inherent method._
1800 ///
1801 /// [`f32::fract`]: ../../../std/primitive.f32.html#method.fract
1802 #[inline]
1803 #[unstable(feature = "core_float_math", issue = "137578")]
1804 #[must_use = "method returns a new number and does not mutate the original value"]
1805 pub const fn fract(x: f32) -> f32 {
1806 x - trunc(x)
1807 }
1808
1809 /// Experimental version of `mul_add` in `core`. See [`f32::mul_add`] for details.
1810 ///
1811 /// # Examples
1812 ///
1813 /// ```
1814 /// #![feature(core_float_math)]
1815 ///
1816 /// # // FIXME(#140515): mingw has an incorrect fma
1817 /// # // https://sourceforge.net/p/mingw-w64/bugs/848/
1818 /// # #[cfg(all(target_os = "windows", target_env = "gnu", not(target_abi = "llvm")))] {
1819 /// use core::f32;
1820 ///
1821 /// let m = 10.0_f32;
1822 /// let x = 4.0_f32;
1823 /// let b = 60.0_f32;
1824 ///
1825 /// assert_eq!(f32::math::mul_add(m, x, b), 100.0);
1826 /// assert_eq!(m * x + b, 100.0);
1827 ///
1828 /// let one_plus_eps = 1.0_f32 + f32::EPSILON;
1829 /// let one_minus_eps = 1.0_f32 - f32::EPSILON;
1830 /// let minus_one = -1.0_f32;
1831 ///
1832 /// // The exact result (1 + eps) * (1 - eps) = 1 - eps * eps.
1833 /// assert_eq!(
1834 /// f32::math::mul_add(one_plus_eps, one_minus_eps, minus_one),
1835 /// -f32::EPSILON * f32::EPSILON
1836 /// );
1837 /// // Different rounding with the non-fused multiply and add.
1838 /// assert_eq!(one_plus_eps * one_minus_eps + minus_one, 0.0);
1839 /// # }
1840 /// ```
1841 ///
1842 /// _This standalone function is for testing only.
1843 /// It will be stabilized as an inherent method._
1844 ///
1845 /// [`f32::mul_add`]: ../../../std/primitive.f32.html#method.mul_add
1846 #[inline]
1847 #[doc(alias = "fmaf", alias = "fusedMultiplyAdd")]
1848 #[must_use = "method returns a new number and does not mutate the original value"]
1849 #[unstable(feature = "core_float_math", issue = "137578")]
1850 #[rustc_const_unstable(feature = "const_mul_add", issue = "146724")]
1851 pub const fn mul_add(x: f32, y: f32, z: f32) -> f32 {
1852 intrinsics::fmaf32(x, y, z)
1853 }
1854
1855 /// Experimental version of `div_euclid` in `core`. See [`f32::div_euclid`] for details.
1856 ///
1857 /// # Examples
1858 ///
1859 /// ```
1860 /// #![feature(core_float_math)]
1861 ///
1862 /// use core::f32;
1863 ///
1864 /// let a: f32 = 7.0;
1865 /// let b = 4.0;
1866 /// assert_eq!(f32::math::div_euclid(a, b), 1.0); // 7.0 > 4.0 * 1.0
1867 /// assert_eq!(f32::math::div_euclid(-a, b), -2.0); // -7.0 >= 4.0 * -2.0
1868 /// assert_eq!(f32::math::div_euclid(a, -b), -1.0); // 7.0 >= -4.0 * -1.0
1869 /// assert_eq!(f32::math::div_euclid(-a, -b), 2.0); // -7.0 >= -4.0 * 2.0
1870 /// ```
1871 ///
1872 /// _This standalone function is for testing only.
1873 /// It will be stabilized as an inherent method._
1874 ///
1875 /// [`f32::div_euclid`]: ../../../std/primitive.f32.html#method.div_euclid
1876 #[inline]
1877 #[unstable(feature = "core_float_math", issue = "137578")]
1878 #[must_use = "method returns a new number and does not mutate the original value"]
1879 pub fn div_euclid(x: f32, rhs: f32) -> f32 {
1880 let q = trunc(x / rhs);
1881 if x % rhs < 0.0 {
1882 return if rhs > 0.0 { q - 1.0 } else { q + 1.0 };
1883 }
1884 q
1885 }
1886
1887 /// Experimental version of `rem_euclid` in `core`. See [`f32::rem_euclid`] for details.
1888 ///
1889 /// # Examples
1890 ///
1891 /// ```
1892 /// #![feature(core_float_math)]
1893 ///
1894 /// use core::f32;
1895 ///
1896 /// let a: f32 = 7.0;
1897 /// let b = 4.0;
1898 /// assert_eq!(f32::math::rem_euclid(a, b), 3.0);
1899 /// assert_eq!(f32::math::rem_euclid(-a, b), 1.0);
1900 /// assert_eq!(f32::math::rem_euclid(a, -b), 3.0);
1901 /// assert_eq!(f32::math::rem_euclid(-a, -b), 1.0);
1902 /// // limitation due to round-off error
1903 /// assert!(f32::math::rem_euclid(-f32::EPSILON, 3.0) != 0.0);
1904 /// ```
1905 ///
1906 /// _This standalone function is for testing only.
1907 /// It will be stabilized as an inherent method._
1908 ///
1909 /// [`f32::rem_euclid`]: ../../../std/primitive.f32.html#method.rem_euclid
1910 #[inline]
1911 #[doc(alias = "modulo", alias = "mod")]
1912 #[unstable(feature = "core_float_math", issue = "137578")]
1913 #[must_use = "method returns a new number and does not mutate the original value"]
1914 pub fn rem_euclid(x: f32, rhs: f32) -> f32 {
1915 let r = x % rhs;
1916 if r < 0.0 { r + rhs.abs() } else { r }
1917 }
1918
1919 /// Experimental version of `powi` in `core`. See [`f32::powi`] for details.
1920 ///
1921 /// # Examples
1922 ///
1923 /// ```
1924 /// #![feature(core_float_math)]
1925 ///
1926 /// use core::f32;
1927 ///
1928 /// let x = 2.0_f32;
1929 /// let abs_difference = (f32::math::powi(x, 2) - (x * x)).abs();
1930 /// assert!(abs_difference <= 1e-5);
1931 ///
1932 /// assert_eq!(f32::math::powi(f32::NAN, 0), 1.0);
1933 /// ```
1934 ///
1935 /// _This standalone function is for testing only.
1936 /// It will be stabilized as an inherent method._
1937 ///
1938 /// [`f32::powi`]: ../../../std/primitive.f32.html#method.powi
1939 #[inline]
1940 #[must_use = "method returns a new number and does not mutate the original value"]
1941 #[unstable(feature = "core_float_math", issue = "137578")]
1942 pub fn powi(x: f32, n: i32) -> f32 {
1943 intrinsics::powif32(x, n)
1944 }
1945
1946 /// Experimental version of `sqrt` in `core`. See [`f32::sqrt`] for details.
1947 ///
1948 /// # Examples
1949 ///
1950 /// ```
1951 /// #![feature(core_float_math)]
1952 ///
1953 /// use core::f32;
1954 ///
1955 /// let positive = 4.0_f32;
1956 /// let negative = -4.0_f32;
1957 /// let negative_zero = -0.0_f32;
1958 ///
1959 /// assert_eq!(f32::math::sqrt(positive), 2.0);
1960 /// assert!(f32::math::sqrt(negative).is_nan());
1961 /// assert_eq!(f32::math::sqrt(negative_zero), negative_zero);
1962 /// ```
1963 ///
1964 /// _This standalone function is for testing only.
1965 /// It will be stabilized as an inherent method._
1966 ///
1967 /// [`f32::sqrt`]: ../../../std/primitive.f32.html#method.sqrt
1968 #[inline]
1969 #[doc(alias = "squareRoot")]
1970 #[unstable(feature = "core_float_math", issue = "137578")]
1971 #[must_use = "method returns a new number and does not mutate the original value"]
1972 pub fn sqrt(x: f32) -> f32 {
1973 intrinsics::sqrtf32(x)
1974 }
1975
1976 /// Experimental version of `abs_sub` in `core`. See [`f32::abs_sub`] for details.
1977 ///
1978 /// # Examples
1979 ///
1980 /// ```
1981 /// #![feature(core_float_math)]
1982 ///
1983 /// use core::f32;
1984 ///
1985 /// let x = 3.0f32;
1986 /// let y = -3.0f32;
1987 ///
1988 /// let abs_difference_x = (f32::math::abs_sub(x, 1.0) - 2.0).abs();
1989 /// let abs_difference_y = (f32::math::abs_sub(y, 1.0) - 0.0).abs();
1990 ///
1991 /// assert!(abs_difference_x <= 1e-6);
1992 /// assert!(abs_difference_y <= 1e-6);
1993 /// ```
1994 ///
1995 /// _This standalone function is for testing only.
1996 /// It will be stabilized as an inherent method._
1997 ///
1998 /// [`f32::abs_sub`]: ../../../std/primitive.f32.html#method.abs_sub
1999 #[inline]
2000 #[stable(feature = "rust1", since = "1.0.0")]
2001 #[deprecated(
2002 since = "1.10.0",
2003 note = "you probably meant `(self - other).abs()`: \
2004 this operation is `(self - other).max(0.0)` \
2005 except that `abs_sub` also propagates NaNs (also \
2006 known as `fdimf` in C). If you truly need the positive \
2007 difference, consider using that expression or the C function \
2008 `fdimf`, depending on how you wish to handle NaN (please consider \
2009 filing an issue describing your use-case too)."
2010 )]
2011 #[must_use = "method returns a new number and does not mutate the original value"]
2012 pub fn abs_sub(x: f32, other: f32) -> f32 {
2013 libm::fdimf(x, other)
2014 }
2015
2016 /// Experimental version of `cbrt` in `core`. See [`f32::cbrt`] for details.
2017 ///
2018 /// # Unspecified precision
2019 ///
2020 /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
2021 /// can even differ within the same execution from one invocation to the next.
2022 /// This function currently corresponds to the `cbrtf` from libc on Unix
2023 /// and Windows. Note that this might change in the future.
2024 ///
2025 /// # Examples
2026 ///
2027 /// ```
2028 /// #![feature(core_float_math)]
2029 ///
2030 /// use core::f32;
2031 ///
2032 /// let x = 8.0f32;
2033 ///
2034 /// // x^(1/3) - 2 == 0
2035 /// let abs_difference = (f32::math::cbrt(x) - 2.0).abs();
2036 ///
2037 /// assert!(abs_difference <= 1e-6);
2038 /// ```
2039 ///
2040 /// _This standalone function is for testing only.
2041 /// It will be stabilized as an inherent method._
2042 ///
2043 /// [`f32::cbrt`]: ../../../std/primitive.f32.html#method.cbrt
2044 #[inline]
2045 #[must_use = "method returns a new number and does not mutate the original value"]
2046 #[unstable(feature = "core_float_math", issue = "137578")]
2047 pub fn cbrt(x: f32) -> f32 {
2048 libm::cbrtf(x)
2049 }
2050}