rust_linear_algebra/vector/
norm.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
use super::Vector;
use std::ops::Mul;

impl<K> Vector<K>
where
    K: Mul<f32, Output = K> + Into<f32> + Copy + Default,
{
    pub fn norm_1(&self) -> f32 {
        self.iter().fold(0.0, |acc, &x| {
            let x_f32: f32 = x.into();
            if x_f32 < 0.0 {
                acc + (-x_f32)
            } else {
                acc + x_f32
            }
        })
    }
    pub fn norm(&self) -> f32 {
        let sum_of_squares: f32 = self.elements.iter().fold(0.0, |acc, &x| {
            let x_f32: f32 = x.into();
            acc + x_f32.powi(2)
        });
        sum_of_squares.sqrt()
    }
    pub fn norm_inf(&self) -> f32 {
        self.elements.iter().fold(0.0, |acc, &x| {
            let x_f32: f32 = x.into();
            acc.max(x_f32.abs())
        })
    }
}