half-rs icon indicating copy to clipboard operation
half-rs copied to clipboard

lossless `TryFrom<f{32,64}>` implementations for `f16` and `bf16`

Open Robbepop opened this issue 2 years ago • 1 comments

Would it be possible to introduce lossless TryFrom implementations for bf16 and f16 types from Rust primitive f32 and f64 types so that for example f16::try_from(value).map(f16::to_f32) is either Err or Ok(value2) with value == value2 for all possible values?

This means that if TryFrom is Ok the conversion was lossless and it is possible to fully recover the f32 or f64 value later on if no mutations happen in between. If TryFrom yields Err then it is not possible to losslessly convert the particular f32 or f64 value. No rounding shall take place.

I actually need this if this can be implemented efficiently. :)

Robbepop avatar May 30 '23 12:05 Robbepop

@Robbepop not sure if there's still interest but I implemented this and would gladly make a PR here. It's not too complicated or inefficient, but it does need special handling of denormals and overflow.

It will roundtrip for anything besides signaling NaNs, which will be returned as a NaN (either quiet or signaling depending on context), and it's not much less efficient or is as efficient compared to the software conversion functions.

Alexhuszagh avatar Dec 15 '24 18:12 Alexhuszagh