argmin/core/math/
scaledadd.rs

1// Copyright 2018-2020 argmin developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8use crate::core::math::{ArgminAdd, ArgminMul, ArgminScaledAdd};
9
10// This is a very generic implementation. Once the specialization feature is stable, impls for
11// types, which allow efficient execution of scaled adds can be made.
12impl<T, U, W> ArgminScaledAdd<T, U, W> for W
13where
14    U: ArgminMul<T, T>,
15    W: ArgminAdd<T, W>,
16{
17    #[inline]
18    fn scaled_add(&self, factor: &U, vec: &T) -> W {
19        self.add(&factor.mul(vec))
20    }
21}
22
23#[cfg(test)]
24mod tests {
25    use super::*;
26    use paste::item;
27
28    macro_rules! make_test {
29        ($t:ty) => {
30            item! {
31                #[test]
32                fn [<test_scaledadd_ $t>]() {
33                    let a = 2 as $t;
34                    let b = 4 as $t;
35                    let c = 10 as $t;
36                    let res = <$t as ArgminScaledAdd<$t, $t, $t>>::scaled_add(&a, &b, &c);
37                    assert!(((42 as $t - res) as f64).abs() < std::f64::EPSILON);
38                }
39            }
40        };
41    }
42
43    make_test!(isize);
44    make_test!(usize);
45    make_test!(i8);
46    make_test!(u8);
47    make_test!(i16);
48    make_test!(u16);
49    make_test!(i32);
50    make_test!(u32);
51    make_test!(i64);
52    make_test!(u64);
53    make_test!(f32);
54    make_test!(f64);
55}