private static double euclideanNorm ( double vector [ ] ) { int n = vector . length ; if ( n < 1 ) { return 0 ; } if ( n == 1 ) { return Math . abs ( vector [ 0 ] ) ; } // this algorithm is (often) more accurate than just summing up the squares and taking the square-root afterwards double scale = 0 ; // scaling factor that is factored out double sum = 1 ; // basic sum of squares from which scale has been factored out for ( int i = 0 ; i < n ; i ++ ) { if ( vector [ i ] != 0 ) { double abs = Math . abs ( vector [ i ] ) ; // try to get the best scaling factor if ( scale < abs ) { double t = scale / abs ; sum = 1 + sum * ( t * t ) ; scale = abs ; } else { double t = abs / scale ; sum += t * t ; } } } return scale * Math . sqrt ( sum ) ; }
returns the euclidean norm of a vector