mimium_lang/utils/
half_float.rs

1use half::f16;
2use std::fmt::Display;
3/// Half-Precision floating point type that can be converted from 64bit float with truncation checking.
4pub const ALLOWED_ERROR: f64 = 0.00001;
5
6#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
7pub struct HFloat(f16);
8
9impl Display for HFloat {
10    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11        self.0.fmt(f)
12    }
13}
14
15impl From<f16> for HFloat {
16    fn from(value: f16) -> Self {
17        Self(value)
18    }
19}
20impl From<HFloat> for f64 {
21    fn from(value: HFloat) -> Self {
22        value.0.to_f64()
23    }
24}
25
26impl TryFrom<f64> for HFloat {
27    type Error = ();
28
29    fn try_from(value: f64) -> Result<Self, Self::Error> {
30        let hv = f16::from_f64(value);
31        let error = (hv.to_f64() - value).abs();
32        if error < ALLOWED_ERROR {
33            Ok(Self(f16::from_f64(value)))
34        } else {
35            Err(())
36        }
37    }
38}
39
40#[cfg(test)]
41mod test {
42    use super::*;
43
44    #[test]
45    fn safecast() {
46        let f64v: f64 = 2.0;
47        let hv = HFloat::try_from(f64v);
48        assert!(hv.is_ok());
49        assert!((hv.unwrap().0.to_f64() - f64v).abs() < ALLOWED_ERROR)
50    }
51}