pub trait FloatEncoding {
type Mantissa;
type Exponent;
// Required methods
fn decode(self) -> Result<(Self::Mantissa, Self::Exponent), FpCategory>;
fn encode(
mantissa: Self::Mantissa,
exponent: Self::Exponent,
) -> Approximation<Self, Sign>
where Self: Sized;
}
Expand description
Support encoding and decoding of floats into (mantissa, exponent) parts.
See the docs of each method for the details
§Examples
use core::num::FpCategory;
assert_eq!(0f64.decode(), Ok((0, -1074))); // exponent will not be reduced
assert_eq!(1f32.decode(), Ok((1 << 23, -23)));
assert_eq!(f32::INFINITY.decode(), Err(FpCategory::Infinite));
assert_eq!(f64::encode(0, 1), Exact(0f64));
assert_eq!(f32::encode(1, 0), Exact(1f32));
assert_eq!(f32::encode(i32::MAX, 100), Inexact(f32::INFINITY, Positive));
Required Associated Types§
Required Methods§
Sourcefn decode(self) -> Result<(Self::Mantissa, Self::Exponent), FpCategory>
fn decode(self) -> Result<(Self::Mantissa, Self::Exponent), FpCategory>
Convert a float number mantissa * 2^exponent
into (mantissa, exponent)
parts faithfully.
This method will not reduce the result (e.g. turn 2 * 2^-1
into 1 * 2^0
), and it
will return Err when the float number is nan or infinite.
Sourcefn encode(
mantissa: Self::Mantissa,
exponent: Self::Exponent,
) -> Approximation<Self, Sign>where
Self: Sized,
fn encode(
mantissa: Self::Mantissa,
exponent: Self::Exponent,
) -> Approximation<Self, Sign>where
Self: Sized,
Convert (mantissa, exponent)
to mantissa * 2^exponent
faithfully.
It won’t generate NaN
values. However if the actual value is out of the
representation range, it might return an infinity or subnormal number.
If any rounding happened during the conversion, it should follow the default behavior defined by IEEE 754 (round to nearest, ties to even)
The returned approximation is exact if the input can be exactly representable by f32,
otherwise the error field of the approximation contains the sign of result - mantissa * 2^exp
.