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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//! Functions to compute norms of vectors.
extern crate libc;

use ::blas::{cblas_dnrm2, cblas_snrm2};

pub trait Norm<T> {
    fn compute(a: &[T]) -> T;
}

pub struct L2Norm;

impl Norm<f64> for L2Norm {

    // TODO handling of NaN and stuff like this
    fn compute(a: &[f64]) -> f64 {
        unsafe {
            cblas_dnrm2(
                a.len()    as libc::c_int,
                a.as_ptr() as *const libc::c_double,
                1          as libc::c_int
            )
        }
    }
}

impl Norm<f32> for L2Norm {

    // TODO handling of NaN and stuff like this
    fn compute(a: &[f32]) -> f32 {
        unsafe {
            cblas_snrm2(
                a.len()    as libc::c_int,
                a.as_ptr() as *const libc::c_float,
                1          as libc::c_int
            )
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{Norm, L2Norm};

    #[test]
    fn test_l2nrom() {

        let a = &[1.0, 2.0, 3.0];
        assert!(L2Norm::compute(a) - 3.741657 <= 0.000001);
    }
}