1 //! Decodes a floating-point value into individual parts and error ranges.
3 use crate::num::dec2flt::float::RawFloat;
4 use crate::num::FpCategory;
6 /// Decoded unsigned finite value, such that:
8 /// - The original value equals to `mant * 2^exp`.
10 /// - Any number from `(mant - minus) * 2^exp` to `(mant + plus) * 2^exp` will
11 /// round to the original value. The range is inclusive only when
12 /// `inclusive` is `true`.
13 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
15 /// The scaled mantissa.
17 /// The lower error range.
19 /// The upper error range.
21 /// The shared exponent in base 2.
23 /// True when the error range is inclusive.
25 /// In IEEE 754, this is true when the original mantissa was even.
29 /// Decoded unsigned value.
30 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
31 pub enum FullDecoded {
34 /// Infinities, either positive or negative.
36 /// Zero, either positive or negative.
38 /// Finite numbers with further decoded fields.
42 /// A floating point type which can be `decode`d.
43 pub trait DecodableFloat: RawFloat + Copy {
44 /// The minimum positive normalized value.
45 fn min_pos_norm_value() -> Self;
48 impl DecodableFloat for f32 {
49 fn min_pos_norm_value() -> Self {
54 impl DecodableFloat for f64 {
55 fn min_pos_norm_value() -> Self {
60 /// Returns a sign (true when negative) and `FullDecoded` value
61 /// from given floating point number.
62 pub fn decode<T: DecodableFloat>(v: T) -> (/*negative?*/ bool, FullDecoded) {
63 let (mant, exp, sign) = v.integer_decode();
64 let even = (mant & 1) == 0;
65 let decoded = match v.classify() {
66 FpCategory::Nan => FullDecoded::Nan,
67 FpCategory::Infinite => FullDecoded::Infinite,
68 FpCategory::Zero => FullDecoded::Zero,
69 FpCategory::Subnormal => {
70 // neighbors: (mant - 2, exp) -- (mant, exp) -- (mant + 2, exp)
71 // Float::integer_decode always preserves the exponent,
72 // so the mantissa is scaled for subnormals.
73 FullDecoded::Finite(Decoded { mant, minus: 1, plus: 1, exp, inclusive: even })
75 FpCategory::Normal => {
76 let minnorm = <T as DecodableFloat>::min_pos_norm_value().integer_decode();
77 if mant == minnorm.0 {
78 // neighbors: (maxmant, exp - 1) -- (minnormmant, exp) -- (minnormmant + 1, exp)
79 // where maxmant = minnormmant * 2 - 1
80 FullDecoded::Finite(Decoded {
88 // neighbors: (mant - 1, exp) -- (mant, exp) -- (mant + 1, exp)
89 FullDecoded::Finite(Decoded {