use super::super::wide_acc::WideAcc;
use crate::dtype::Element;
use num_traits::Float;
pub trait DistAcc<T: Element>: Float + 'static {
fn widen(v: T) -> Self;
fn narrow(self) -> T;
fn exponent(p: f64) -> Self;
fn count(n: usize) -> Self;
fn from_f64(v: f64) -> Self;
}
impl<T: Element> DistAcc<T> for f32 {
#[inline]
fn widen(v: T) -> Self {
<f32 as WideAcc>::from_elem(v)
}
#[inline]
fn narrow(self) -> T {
<f32 as WideAcc>::to_elem::<T>(self)
}
#[inline]
fn exponent(p: f64) -> Self {
p as f32
}
#[inline]
fn count(n: usize) -> Self {
n as f32
}
#[inline]
fn from_f64(v: f64) -> Self {
v as f32
}
}
impl<T: Element> DistAcc<T> for f64 {
#[inline]
fn widen(v: T) -> Self {
v.to_f64()
}
#[inline]
fn narrow(self) -> T {
T::from_f64(self)
}
#[inline]
fn exponent(p: f64) -> Self {
p
}
#[inline]
fn count(n: usize) -> Self {
n as f64
}
#[inline]
fn from_f64(v: f64) -> Self {
v
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "f16")]
#[test]
fn f32_accumulator_keeps_terms_an_f16_accumulator_drops() {
let big = half::f16::from_f32(1024.0);
let small = half::f16::from_f32(0.25);
let mut wide: f32 = <f32 as DistAcc<half::f16>>::widen(big);
let mut narrow = big;
for _ in 0..64 {
wide += <f32 as DistAcc<half::f16>>::widen(small);
narrow += small;
}
assert_eq!(wide, 1040.0);
assert_eq!(narrow.to_f32(), 1024.0);
assert_eq!(
<f32 as DistAcc<half::f16>>::narrow(wide).to_f32(),
1040.0,
"1040 is exactly representable in f16, so only the accumulator width shows here"
);
}
#[test]
fn f64_accumulator_is_exact_for_f64_elements() {
let v = 1.0e300f64;
assert_eq!(<f64 as DistAcc<f64>>::widen(v), v);
assert_eq!(<f64 as DistAcc<f64>>::narrow(v), v);
}
}