1 /*
2 * Copyright (c) 2007 - 2015 Joseph Gaeddert
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a copy
5 * of this software and associated documentation files (the "Software"), to deal
6 * in the Software without restriction, including without limitation the rights
7 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 * copies of the Software, and to permit persons to whom the Software is
9 * furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 * THE SOFTWARE.
21 */
22
23 //
24 // Generic vector norm computation
25 //
26
27 #include <stdlib.h>
28 #include <string.h>
29 #include <stdio.h>
30 #include <math.h>
31
32 // compute l2-norm on vector
33 // _x : input array [size: _n x 1]
34 // _n : array length
VECTOR(_norm)35 TP VECTOR(_norm)(T * _x,
36 unsigned int _n)
37 {
38 // t = 4*(floor(_n/4))
39 unsigned int t=(_n>>2)<<2;
40
41 // initialize accumulator
42 TP norm = 0;
43
44 // compute in groups of 4
45 // TODO: use generic 'real' and 'conj' functions
46 unsigned int i;
47 for (i=0; i<t; i+=4) {
48 norm += crealf( _x[i ]*conjf(_x[i ]) );
49 norm += crealf( _x[i+1]*conjf(_x[i+1]) );
50 norm += crealf( _x[i+2]*conjf(_x[i+2]) );
51 norm += crealf( _x[i+3]*conjf(_x[i+3]) );
52 }
53
54 // clean up remaining
55 // TODO: use generic 'real' and 'conj' functions
56 for ( ; i<_n; i++)
57 norm += crealf( _x[i]*conjf(_x[i]) );
58
59 // return square root of accumulation
60 // TODO: use generic 'sqrt' function
61 return sqrtf(norm);
62 }
63
64 // scale vector to its l2-norm
65 // _x : input array [size: _n x 1]
66 // _n : array length
67 // _y : output array [size: _n x 1]
VECTOR(_normalize)68 void VECTOR(_normalize)(T * _x,
69 unsigned int _n,
70 T * _y)
71 {
72 // compute l2-norm on vector
73 TP norm = VECTOR(_norm)(_x, _n);
74
75 // compute inverse
76 TP norm_inv = 1.0 / norm;
77
78 // t = 4*(floor(_n/4))
79 unsigned int t=(_n>>2)<<2;
80
81 // scale by inverse; compute in groups of 4
82 unsigned int i;
83 for (i=0; i<t; i+=4) {
84 _y[i ] = _x[i ] * norm_inv;
85 _y[i+1] = _x[i+1] * norm_inv;
86 _y[i+2] = _x[i+2] * norm_inv;
87 _y[i+3] = _x[i+3] * norm_inv;
88 }
89
90 // clean up remaining
91 for ( ; i<_n; i++)
92 _y[i] = _x[i] * norm_inv;
93 }
94
95