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