#! /usr/bin/env python3 # def normalize ( n, x ): #****************************************************************************80 # # Purpose: # # NORMALIZE scales a vector X so its entries sum to 1. # # Modified: # # 19 February 2016 # # Author: # # Original C version by Warren Smith. # This Python version by John Burkardt. # # Parameters: # # Input, integer N, indicates the size of X. # # Input/output, double X[N+2], the vector to be normalized. # Entries X[1] through X[N] will sum to 1 on output. # # # Sum X. # sum = 0.0 for i in range ( 1, n + 1 ): sum = sum + abs ( x[i] ) # # Normalize so that the new sum of X will be 1. # for i in range ( 1, n + 1 ): x[i] = x[i] / sum return x def normalize_test ( ): #*****************************************************************************80 # ## NORMALIZE_TEST tests NORMALIZE. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 19 February 2016 # # Author: # # John Burkardt # import platform from r8vec_print import r8vec_print from r8vec_uniform_01 import r8vec_uniform_01 print ( '' ) print ( 'NORMALIZE_TEST' ) print ( ' Python version: %s' % ( platform.python_version ( ) ) ) print ( ' NORMALIZE normalizes entries 1 through N of a vector' ) print ( ' of length N+2.' ) n = 5 seed = 123456789 x, seed = r8vec_uniform_01 ( n + 2, seed ) r8vec_print ( n + 2, x, ' Initial X:' ) x_norm = 0.0 for i in range ( 1, n + 1 ): x_norm = x_norm + abs ( x[i] ) print ( '' ) print ( ' Initial L1 norm of X(1:%d) = %10.6g' % ( n, x_norm ) ) x = normalize ( n, x ) r8vec_print ( n + 2, x, ' Normalized X:' ) x_norm = 0.0 for i in range ( 1, n + 1 ): x_norm = x_norm + abs ( x[i] ) print ( '' ) print ( ' Final L1 norm of X(1:%d) = %10.6g' % ( n, x_norm ) ) # # Terminate. # print ( '' ) print ( 'NORMALIZE_TEST' ) print ( ' Normal end of execution.' ) return if ( __name__ == '__main__' ): from timestamp import timestamp timestamp ( ) normalize_test ( ) timestamp ( )