#! /usr/bin/env python3 # def circle_sample_test ( ): #*****************************************************************************80 # ## circle_sample_test() compares 3 ways to sample the unit circle. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 09 January 2022 # # Author: # # John Burkardt # import matplotlib.pyplot as plt import numpy as np print ( "circle_sample_test:" ) print ( " Compare methods of randomly sampling the unit circle" ) print ( " with points x = r cos(t), y = r sin(t)" ) print ( "" ) print ( " method 1: r = random, t = 2 pi * random" ) print ( " method 2: r = sqrt(random), t = 2 pi * random" ) print ( " method 3: x = random, y = random, reject if 1 < x^2+y^2" ) # # Get points on the circumference. # nc = 100 theta = np.linspace ( 0, 2.0 * np.pi, nc ) xc = np.cos ( theta ) yc = np.sin ( theta ) ns = 1000 for sample_function, sample_name in [ [ circle_sample1, 'circle_sample1' ], [ circle_sample2, 'circle_sample2' ], [ circle_sample3, 'circle_sample3' ] ]: xs, ys = sample_function ( ns ) plt.clf ( ) plt.plot ( xc, yc, 'b-', linewidth = 2 ) plt.plot ( xs, ys, 'g.', markersize = 5 ) plt.title ( sample_name ) plt.axis ( 'equal' ) plt.grid ( True ) filename = sample_name + '.jpg' plt.savefig ( filename ) print ( " Graphics saved as '" + filename + "'" ) plt.show ( ) plt.close ( ) print ( "" ) print ( "circle_sample:" ) print ( " Normal end of execution." ) return def circle_sample1 ( n ): #*****************************************************************************80 # ## circle_sample1 uses sampling method 1. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 09 January 2022 # # Author: # # John Burkardt # import numpy as np r = np.random.rand ( n ) theta = 2.0 * np.pi * np.random.rand ( n ) x = r * np.cos ( theta ) y = r * np.sin ( theta ) return x, y def circle_sample2 ( n ): #*****************************************************************************80 # ## circle_sample2 uses sampling method 2. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 09 January 2022 # # Author: # # John Burkardt # import numpy as np r = np.sqrt ( np.random.rand ( n ) ) theta = 2.0 * np.pi * np.random.rand ( n ) x = r * np.cos ( theta ) y = r * np.sin ( theta ) return x, y def circle_sample3 ( n ): #*****************************************************************************80 # ## circle_sample3 uses sampling method 3. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 09 January 2022 # # Author: # # John Burkardt # import numpy as np x = 2.0 * np.random.rand ( n ) - 1.0 y = 2.0 * np.random.rand ( n ) - 1.0 for i in range ( 0, n ): while ( 1.0 < x[i]**2 + y[i]**2 ): x[i] = 2.0 * np.random.rand ( 1 ) - 1.0 y[i] = 2.0 * np.random.rand ( 1 ) - 1.0 return x, y if ( __name__ == '__main__' ): circle_sample_test ( )