f32

Primitive Type f32 

1.0.0
Expand description

A 32-bit floating-point type (specifically, the “binary32” type defined in IEEE 754-2008).

This type can represent a wide range of decimal numbers, like 3.5, 27, -113.75, 0.0078125, 34359738368, 0, -1. So unlike integer types (such as i32), floating-point types can represent non-integer numbers, too.

However, being able to represent this wide range of numbers comes at the cost of precision: floats can only represent some of the real numbers and calculation with floats round to a nearby representable number. For example, 5.0 and 1.0 can be exactly represented as f32, but 1.0 / 5.0 results in 0.20000000298023223876953125 since 0.2 cannot be exactly represented as f32. Note, however, that printing floats with println and friends will often discard insignificant digits: println!("{}", 1.0f32 / 5.0f32) will print 0.2.

Additionally, f32 can represent some special values:

  • −0.0: IEEE 754 floating-point numbers have a bit that indicates their sign, so −0.0 is a possible value. For comparison −0.0 = +0.0, but floating-point operations can carry the sign bit through arithmetic operations. This means −0.0 × +0.0 produces −0.0 and a negative number rounded to a value smaller than a float can represent also produces −0.0.
  • and −∞: these result from calculations like 1.0 / 0.0.
  • NaN (not a number): this value results from calculations like (-1.0).sqrt(). NaN has some potentially unexpected behavior:
    • It is not equal to any float, including itself! This is the reason f32 doesn’t implement the Eq trait.
    • It is also neither smaller nor greater than any float, making it impossible to sort by the default comparison operation, which is the reason f32 doesn’t implement the Ord trait.
    • It is also considered infectious as almost all calculations where one of the operands is NaN will also result in NaN. The explanations on this page only explicitly document behavior on NaN operands if this default is deviated from.
    • Lastly, there are multiple bit patterns that are considered NaN. Rust does not currently guarantee that the bit patterns of NaN are preserved over arithmetic operations, and they are not guaranteed to be portable or even fully deterministic! This means that there may be some surprising results upon inspecting the bit patterns, as the same calculations might produce NaNs with different bit patterns. This also affects the sign of the NaN: checking is_sign_positive or is_sign_negative on a NaN is the most common way to run into these surprising results. (Checking x >= 0.0 or x <= 0.0 avoids those surprises, but also how negative/positive zero are treated.) See the section below for what exactly is guaranteed about the bit pattern of a NaN.

When a primitive operation (addition, subtraction, multiplication, or division) is performed on this type, the result is rounded according to the roundTiesToEven direction defined in IEEE 754-2008. That means:

  • The result is the representable value closest to the true value, if there is a unique closest representable value.
  • If the true value is exactly half-way between two representable values, the result is the one with an even least-significant binary digit.
  • If the true value’s magnitude is ≥ f32::MAX + 2(f32::MAX_EXPf32::MANTISSA_DIGITS − 1), the result is ∞ or −∞ (preserving the true value’s sign).
  • If the result of a sum exactly equals zero, the outcome is +0.0 unless both arguments were negative, then it is -0.0. Subtraction a - b is regarded as a sum a + (-b).

For more information on floating-point numbers, see Wikipedia.

See also the std::f32::consts module.

§NaN bit patterns

This section defines the possible NaN bit patterns returned by floating-point operations.

The bit pattern of a floating-point NaN value is defined by:

  • a sign bit.
  • a quiet/signaling bit. Rust assumes that the quiet/signaling bit being set to 1 indicates a quiet NaN (QNaN), and a value of 0 indicates a signaling NaN (SNaN). In the following we will hence just call it the “quiet bit”.
  • a payload, which makes up the rest of the significand (i.e., the mantissa) except for the quiet bit.

The rules for NaN values differ between arithmetic and non-arithmetic (or “bitwise”) operations. The non-arithmetic operations are unary -, abs, copysign, signum, {to,from}_bits, {to,from}_{be,le,ne}_bytes and is_sign_{positive,negative}. These operations are guaranteed to exactly preserve the bit pattern of their input except for possibly changing the sign bit.

The following rules apply when a NaN value is returned from an arithmetic operation:

  • The result has a non-deterministic sign.

  • The quiet bit and payload are non-deterministically chosen from the following set of options:

    • Preferred NaN: The quiet bit is set and the payload is all-zero.
    • Quieting NaN propagation: The quiet bit is set and the payload is copied from any input operand that is a NaN. If the inputs and outputs do not have the same payload size (i.e., for as casts), then
      • If the output is smaller than the input, low-order bits of the payload get dropped.
      • If the output is larger than the input, the payload gets filled up with 0s in the low-order bits.
    • Unchanged NaN propagation: The quiet bit and payload are copied from any input operand that is a NaN. If the inputs and outputs do not have the same size (i.e., for as casts), the same rules as for “quieting NaN propagation” apply, with one caveat: if the output is smaller than the input, dropping the low-order bits may result in a payload of 0; a payload of 0 is not possible with a signaling NaN (the all-0 significand encodes an infinity) so unchanged NaN propagation cannot occur with some inputs.
    • Target-specific NaN: The quiet bit is set and the payload is picked from a target-specific set of “extra” possible NaN payloads. The set can depend on the input operand values. See the table below for the concrete NaNs this set contains on various targets.

In particular, if all input NaNs are quiet (or if there are no input NaNs), then the output NaN is definitely quiet. Signaling NaN outputs can only occur if they are provided as an input value. Similarly, if all input NaNs are preferred (or if there are no input NaNs) and the target does not have any “extra” NaN payloads, then the output NaN is guaranteed to be preferred.

The non-deterministic choice happens when the operation is executed; i.e., the result of a NaN-producing floating-point operation is a stable bit pattern (looking at these bits multiple times will yield consistent results), but running the same operation twice with the same inputs can produce different results.

These guarantees are neither stronger nor weaker than those of IEEE 754: IEEE 754 guarantees that an operation never returns a signaling NaN, whereas it is possible for operations like SNAN * 1.0 to return a signaling NaN in Rust. Conversely, IEEE 754 makes no statement at all about which quiet NaN is returned, whereas Rust restricts the set of possible results to the ones listed above.

Unless noted otherwise, the same rules also apply to NaNs returned by other library functions (e.g. min, minimum, max, maximum); other aspects of their semantics and which IEEE 754 operation they correspond to are documented with the respective functions.

When an arithmetic floating-point operation is executed in const context, the same rules apply: no guarantee is made about which of the NaN bit patterns described above will be returned. The result does not have to match what happens when executing the same code at runtime, and the result can vary depending on factors such as compiler version and flags.

§Target-specific “extra” NaN values

target_archExtra payloads possible on this platform
aarch64, arm, arm64ec, loongarch64, powerpc (except when target_abi = "spe"), powerpc64, riscv32, riscv64, s390x, x86, x86_64None
nvptx64All payloads
sparc, sparc64The all-one payload
wasm32, wasm64If all input NaNs are quiet with all-zero payload: None.
Otherwise: all payloads.

For targets not in this table, all payloads are possible.

§Algebraic operators

Algebraic operators of the form a.algebraic_*(b) allow the compiler to optimize floating point operations using all the usual algebraic properties of real numbers – despite the fact that those properties do not hold on floating point numbers. This can give a great performance boost since it may unlock vectorization.

The exact set of optimizations is unspecified but typically allows combining operations, rearranging series of operations based on mathematical properties, converting between division and reciprocal multiplication, and disregarding the sign of zero. This means that the results of elementary operations may have undefined precision, and “non-mathematical” values such as NaN, +/-Inf, or -0.0 may behave in unexpected ways, but these operations will never cause undefined behavior.

Because of the unpredictable nature of compiler optimizations, the same inputs may produce different results even within a single program run. Unsafe code must not rely on any property of the return value for soundness. However, implementations will generally do their best to pick a reasonable tradeoff between performance and accuracy of the result.

For example:

x = a.algebraic_add(b).algebraic_add(c).algebraic_add(d);

May be rewritten as:

x = a + b + c + d; // As written
x = (a + c) + (b + d); // Reordered to shorten critical path and enable vectorization

Implementations§

Source§

impl f32

1.43.0 · Source

pub const RADIX: u32 = 2u32

The radix or base of the internal representation of f32.

1.43.0 · Source

pub const MANTISSA_DIGITS: u32 = 24u32

Number of significant digits in base 2.

Note that the size of the mantissa in the bitwise representation is one smaller than this since the leading 1 is not stored explicitly.

1.43.0 · Source

pub const DIGITS: u32 = 6u32

Approximate number of significant digits in base 10.

This is the maximum x such that any decimal number with x significant digits can be converted to f32 and back without loss.

Equal to floor(log10 2MANTISSA_DIGITS − 1).

1.43.0 · Source

pub const EPSILON: f32 = 1.1920929E-7f32

Machine epsilon value for f32.

This is the difference between 1.0 and the next larger representable number.

Equal to 21 − MANTISSA_DIGITS.

1.43.0 · Source

pub const MIN: f32 = -3.40282347E+38f32

Smallest finite f32 value.

Equal to −MAX.

1.43.0 · Source

pub const MIN_POSITIVE: f32 = 1.17549435E-38f32

Smallest positive normal f32 value.

Equal to 2MIN_EXP − 1.

1.43.0 · Source

pub const MAX: f32 = 3.40282347E+38f32

Largest finite f32 value.

Equal to (1 − 2MANTISSA_DIGITS) 2MAX_EXP.

1.43.0 · Source

pub const MIN_EXP: i32 = -125i32

One greater than the minimum possible normal power of 2 exponent for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).

This corresponds to the exact minimum possible normal power of 2 exponent for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition). In other words, all normal numbers representable by this type are greater than or equal to 0.5 × 2MIN_EXP.

1.43.0 · Source

pub const MAX_EXP: i32 = 128i32

One greater than the maximum possible power of 2 exponent for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).

This corresponds to the exact maximum possible power of 2 exponent for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition). In other words, all numbers representable by this type are strictly less than 2MAX_EXP.

1.43.0 · Source

pub const MIN_10_EXP: i32 = -37i32

Minimum x for which 10x is normal.

Equal to ceil(log10 MIN_POSITIVE).

1.43.0 · Source

pub const MAX_10_EXP: i32 = 38i32

Maximum x for which 10x is normal.

Equal to floor(log10 MAX).

1.43.0 · Source

pub const NAN: f32 = NaN_f32

Not a Number (NaN).

Note that IEEE 754 doesn’t define just a single NaN value; a plethora of bit patterns are considered to be NaN. Furthermore, the standard makes a difference between a “signaling” and a “quiet” NaN, and allows inspecting its “payload” (the unspecified bits in the bit pattern) and its sign. See the specification of NaN bit patterns for more info.

This constant is guaranteed to be a quiet NaN (on targets that follow the Rust assumptions that the quiet/signaling bit being set to 1 indicates a quiet NaN). Beyond that, nothing is guaranteed about the specific bit pattern chosen here: both payload and sign are arbitrary. The concrete bit pattern may change across Rust versions and target platforms.

1.43.0 · Source

pub const INFINITY: f32 = +Inf_f32

Infinity (∞).

1.43.0 · Source

pub const NEG_INFINITY: f32 = -Inf_f32

Negative infinity (−∞).

1.20.0 (const: 1.83.0) · Source

pub const fn to_bits(self) -> u32

Raw transmutation to u32.

This is currently identical to transmute::<f32, u32>(self) on all platforms.

See from_bits for some discussion of the portability of this operation (there are almost no issues).

Note that this function is distinct from as casting, which attempts to preserve the numeric value, and not the bitwise value.

§Examples
assert_ne!((1f32).to_bits(), 1f32 as u32); // to_bits() is not casting!
assert_eq!((12.5f32).to_bits(), 0x41480000);
1.20.0 (const: 1.83.0) · Source

pub const fn from_bits(v: u32) -> Self

Raw transmutation from u32.

This is currently identical to transmute::<u32, f32>(v) on all platforms. It turns out this is incredibly portable, for two reasons:

  • Floats and Ints have the same endianness on all supported platforms.
  • IEEE 754 very precisely specifies the bit layout of floats.

However there is one caveat: prior to the 2008 version of IEEE 754, how to interpret the NaN signaling bit wasn’t actually specified. Most platforms (notably x86 and ARM) picked the interpretation that was ultimately standardized in 2008, but some didn’t (notably MIPS). As a result, all signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.

Rather than trying to preserve signaling-ness cross-platform, this implementation favors preserving the exact bits. This means that any payloads encoded in NaNs will be preserved even if the result of this method is sent over the network from an x86 machine to a MIPS one.

If the results of this method are only manipulated by the same architecture that produced them, then there is no portability concern.

If the input isn’t NaN, then there is no portability concern.

If you don’t care about signalingness (very likely), then there is no portability concern.

Note that this function is distinct from as casting, which attempts to preserve the numeric value, and not the bitwise value.

§Examples
let v = f32::from_bits(0x41480000);
assert_eq!(v, 12.5);
1.40.0 (const: 1.83.0) · Source

pub const fn to_le_bytes(self) -> [u8; 4]

Returns the memory representation of this floating point number as a byte array in little-endian byte order.

See from_bits for some discussion of the portability of this operation (there are almost no issues).

§Examples
let bytes = 12.5f32.to_le_bytes();
assert_eq!(bytes, [0x00, 0x00, 0x48, 0x41]);
1.40.0 (const: 1.83.0) · Source

pub const fn from_le_bytes(bytes: [u8; 4]) -> Self

Creates a floating point value from its representation as a byte array in little endian.

See from_bits for some discussion of the portability of this operation (there are almost no issues).

§Examples
let value = f32::from_le_bytes([0x00, 0x00, 0x48, 0x41]);
assert_eq!(value, 12.5);

Trait Implementations§

1.0.0 (const: unstable) · Source§

impl Add<&f32> for &f32

Source§

type Output = <f32 as Add>::Output

The resulting type after applying the + operator.
Source§

fn add(self, other: &f32) -> <f32 as Add<f32>>::Output

Performs the + operation. Read more
1.0.0 (const: unstable) · Source§

impl Add<&f32> for f32

Source§

type Output = <f32 as Add>::Output

The resulting type after applying the + operator.
Source§

fn add(self, other: &f32) -> <f32 as Add<f32>>::Output

Performs the + operation. Read more
1.0.0 (const: unstable) · Source§

impl Add<f32> for &f32

Source§

type Output = <f32 as Add>::Output

The resulting type after applying the + operator.
Source§

fn add(self, other: f32) -> <f32 as Add<f32>>::Output

Performs the + operation. Read more
1.0.0 (const: unstable) · Source§

impl Add for f32

Source§

type Output = f32

The resulting type after applying the + operator.
Source§

fn add(self, other: f32) -> f32

Performs the + operation. Read more
1.22.0 (const: unstable) · Source§

impl AddAssign<&f32> for f32

Source§

fn add_assign(&mut self, other: &f32)

Performs the += operation. Read more
1.8.0 (const: unstable) · Source§

impl AddAssign for f32

Source§

fn add_assign(&mut self, other: f32)

Performs the += operation. Read more
1.0.0 (const: unstable) · Source§

impl Clone for f32

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)
where Self:,

Performs copy-assignment from source. Read more
1.0.0 (const: unstable) · Source§

impl Default for f32

Source§

fn default() -> f32

Returns the default value of 0.0

1.0.0 (const: unstable) · Source§

impl Div<&f32> for &f32

Source§

type Output = <f32 as Div>::Output

The resulting type after applying the / operator.
Source§

fn div(self, other: &f32) -> <f32 as Div<f32>>::Output

Performs the / operation. Read more
1.0.0 (const: unstable) · Source§

impl Div<&f32> for f32

Source§

type Output = <f32 as Div>::Output

The resulting type after applying the / operator.
Source§

fn div(self, other: &f32) -> <f32 as Div<f32>>::Output

Performs the / operation. Read more
1.0.0 (const: unstable) · Source§

impl Div<f32> for &f32

Source§

type Output = <f32 as Div>::Output

The resulting type after applying the / operator.
Source§

fn div(self, other: f32) -> <f32 as Div<f32>>::Output

Performs the / operation. Read more
1.0.0 (const: unstable) · Source§

impl Div for f32

Source§

type Output = f32

The resulting type after applying the / operator.
Source§

fn div(self, other: f32) -> f32

Performs the / operation. Read more
1.22.0 (const: unstable) · Source§

impl DivAssign<&f32> for f32

Source§

fn div_assign(&mut self, other: &f32)

Performs the /= operation. Read more
1.8.0 (const: unstable) · Source§

impl DivAssign for f32

Source§

fn div_assign(&mut self, other: f32)

Performs the /= operation. Read more
1.0.0 (const: unstable) · Source§

impl Mul<&f32> for &f32

Source§

type Output = <f32 as Mul>::Output

The resulting type after applying the * operator.
Source§

fn mul(self, other: &f32) -> <f32 as Mul<f32>>::Output

Performs the * operation. Read more
1.0.0 (const: unstable) · Source§

impl Mul<&f32> for f32

Source§

type Output = <f32 as Mul>::Output

The resulting type after applying the * operator.
Source§

fn mul(self, other: &f32) -> <f32 as Mul<f32>>::Output

Performs the * operation. Read more
1.0.0 (const: unstable) · Source§

impl Mul<f32> for &f32

Source§

type Output = <f32 as Mul>::Output

The resulting type after applying the * operator.
Source§

fn mul(self, other: f32) -> <f32 as Mul<f32>>::Output

Performs the * operation. Read more
1.0.0 (const: unstable) · Source§

impl Mul for f32

Source§

type Output = f32

The resulting type after applying the * operator.
Source§

fn mul(self, other: f32) -> f32

Performs the * operation. Read more
1.22.0 (const: unstable) · Source§

impl MulAssign<&f32> for f32

Source§

fn mul_assign(&mut self, other: &f32)

Performs the *= operation. Read more
1.8.0 (const: unstable) · Source§

impl MulAssign for f32

Source§

fn mul_assign(&mut self, other: f32)

Performs the *= operation. Read more
1.0.0 (const: unstable) · Source§

impl Neg for &f32

Source§

type Output = <f32 as Neg>::Output

The resulting type after applying the - operator.
Source§

fn neg(self) -> <f32 as Neg>::Output

Performs the unary - operation. Read more
1.0.0 (const: unstable) · Source§

impl Neg for f32

Source§

type Output = f32

The resulting type after applying the - operator.
Source§

fn neg(self) -> f32

Performs the unary - operation. Read more
1.0.0 (const: unstable) · Source§

impl PartialEq for f32

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
Source§

fn ne(&self, other: &Self) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
1.0.0 (const: unstable) · Source§

impl PartialOrd for f32

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
Source§

fn lt(&self, other: &Self) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
Source§

fn le(&self, other: &Self) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
Source§

fn gt(&self, other: &Self) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
Source§

fn ge(&self, other: &Self) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
1.0.0 (const: unstable) · Source§

impl Rem<&f32> for &f32

Source§

type Output = <f32 as Rem>::Output

The resulting type after applying the % operator.
Source§

fn rem(self, other: &f32) -> <f32 as Rem<f32>>::Output

Performs the % operation. Read more
1.0.0 (const: unstable) · Source§

impl Rem<&f32> for f32

Source§

type Output = <f32 as Rem>::Output

The resulting type after applying the % operator.
Source§

fn rem(self, other: &f32) -> <f32 as Rem<f32>>::Output

Performs the % operation. Read more
1.0.0 (const: unstable) · Source§

impl Rem<f32> for &f32

Source§

type Output = <f32 as Rem>::Output

The resulting type after applying the % operator.
Source§

fn rem(self, other: f32) -> <f32 as Rem<f32>>::Output

Performs the % operation. Read more
1.0.0 (const: unstable) · Source§

impl Rem for f32

The remainder from the division of two floats.

The remainder has the same sign as the dividend and is computed as: x - (x / y).trunc() * y.

§Examples

let x: f32 = 50.50;
let y: f32 = 8.125;
let remainder = x - (x / y).trunc() * y;

// The answer to both operations is 1.75
assert_eq!(x % y, remainder);
Source§

type Output = f32

The resulting type after applying the % operator.
Source§

fn rem(self, other: f32) -> f32

Performs the % operation. Read more
1.22.0 (const: unstable) · Source§

impl RemAssign<&f32> for f32

Source§

fn rem_assign(&mut self, other: &f32)

Performs the %= operation. Read more
1.8.0 (const: unstable) · Source§

impl RemAssign for f32

Source§

fn rem_assign(&mut self, other: f32)

Performs the %= operation. Read more
1.0.0 (const: unstable) · Source§

impl Sub<&f32> for &f32

Source§

type Output = <f32 as Sub>::Output

The resulting type after applying the - operator.
Source§

fn sub(self, other: &f32) -> <f32 as Sub<f32>>::Output

Performs the - operation. Read more
1.0.0 (const: unstable) · Source§

impl Sub<&f32> for f32

Source§

type Output = <f32 as Sub>::Output

The resulting type after applying the - operator.
Source§

fn sub(self, other: &f32) -> <f32 as Sub<f32>>::Output

Performs the - operation. Read more
1.0.0 (const: unstable) · Source§

impl Sub<f32> for &f32

Source§

type Output = <f32 as Sub>::Output

The resulting type after applying the - operator.
Source§

fn sub(self, other: f32) -> <f32 as Sub<f32>>::Output

Performs the - operation. Read more
1.0.0 (const: unstable) · Source§

impl Sub for f32

Source§

type Output = f32

The resulting type after applying the - operator.
Source§

fn sub(self, other: f32) -> f32

Performs the - operation. Read more
1.22.0 (const: unstable) · Source§

impl SubAssign<&f32> for f32

Source§

fn sub_assign(&mut self, other: &f32)

Performs the -= operation. Read more
1.8.0 (const: unstable) · Source§

impl SubAssign for f32

Source§

fn sub_assign(&mut self, other: f32)

Performs the -= operation. Read more
1.0.0 · Source§

impl Copy for f32

Auto Trait Implementations§

§

impl Freeze for f32

§

impl Send for f32

§

impl Sync for f32

§

impl Unpin for f32

Blanket Implementations§

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.