starkat99 / half-rs

Half-precision floating point types f16 and bf16 for Rust.
https://docs.rs/half/
Other
229 stars 51 forks source link

Adding `From<f32>`/`From<f64>` impls for `f16`/`bf16` #86

Closed coreylowman closed 1 year ago

coreylowman commented 1 year ago

This adds from/into in the other way than is currently present, making the following code possible:

use half::f16;

fn add_me(a: f16, b: impl Into<f16>) -> f16 {
    a + b.into()
}

fn main() {
    println!("{}", add_me(f16::ZERO, 2.0f32));
    println!("{}", add_me(f16::ZERO, 2.0f64));
    println!("{}", add_me(f16::ZERO, f16::from_f64(2.0f64)));
}
starkat99 commented 1 year ago

While certainly convenient, these weren't implemented for the same reasons From<f64> isn't implemented for f32: the loss of precision means making the conversion explicit is preferable, to avoid unexpected loss of precision. Instead, use num-traits conversion traits for generic methods like this for f16.