public static double [ ] normalizeL2 ( double [ ] vector ) { // compute vector 2-norm double norm2 = 0 ; for ( int i = 0 ; i < vector . length ; i ++ ) { norm2 += vector [ i ] * vector [ i ] ; } norm2 = ( double ) Math . sqrt ( norm2 ) ; if ( norm2 == 0 ) { Arrays . fill ( vector , 1 ) ; } else { for ( int i = 0 ; i < vector . length ; i ++ ) { vector [ i ] = vector [ i ] / norm2 ; } } return vector ; }
This method applies L2 normalization on a given array of doubles . The passed vector is modified by the method .