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