argmin_math/primitives/
scaledsub.rs

1// Copyright 2018-2024 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::{ArgminMul, ArgminScaledSub, ArgminSub};
9
10// This is a very generic implementation. Once the specialization feature is stable, impls for
11// types, which allow efficient execution of scaled subs can be made.
12impl<T, U, W> ArgminScaledSub<T, U, W> for W
13where
14    U: ArgminMul<T, T>,
15    W: ArgminSub<T, W>,
16{
17    #[inline]
18    fn scaled_sub(&self, factor: &U, vec: &T) -> W {
19        self.sub(&factor.mul(vec))
20    }
21}
22
23#[cfg(test)]
24mod tests {
25    use super::*;
26    use approx::assert_relative_eq;
27    use paste::item;
28
29    macro_rules! make_test {
30        ($t:ty) => {
31            item! {
32                #[test]
33                fn [<test_scaledsub_ $t>]() {
34                    let a = 100 as $t;
35                    let b = 2 as $t;
36                    let c = 29 as $t;
37                    let res = <$t as ArgminScaledSub<$t, $t, $t>>::scaled_sub(&a, &b, &c);
38                    assert_relative_eq!(42 as f64, res as f64, epsilon = f64::EPSILON);
39                }
40            }
41        };
42    }
43
44    make_test!(i8);
45    make_test!(u8);
46    make_test!(i16);
47    make_test!(u16);
48    make_test!(i32);
49    make_test!(u32);
50    make_test!(i64);
51    make_test!(u64);
52    make_test!(f32);
53    make_test!(f64);
54}