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