def triangle_distance ( ): #*****************************************************************************80 # ## triangle_distance() histograms distances between random triangle points. # # Licensing: # # This code is distributed under the MIT license. # # Modified: # # 30 January 2025 # # Author: # # John Burkardt # import matplotlib.pyplot as plt import numpy as np n = 10000 # # 345 right triangle. # t = np.array ( [ \ [ 0.00, 0.00 ], \ [ 3.00, 0.00 ], \ [ 0.00, 4.00 ] \ ] ) # # Randomly sample n pairs of points in the triangle. # p = triangle_sample ( t, n ) q = triangle_sample ( t, n ) # # Compute all the distances. # d = ( p - q ) ** 2 d = np.sum ( d, axis = 1 ) d = np.sqrt ( d ) d_max = np.max ( d ) # # Make a histogram. # plt.hist ( d, bins = 20, rwidth = 0.95, density = True ) plt.grid ( True ) plt.xlabel ( '<-- Distance -->' ) plt.ylabel ( '<-- Frequency -->' ) plt.title ( 'Distances between random points in a 3/4/5 triangle' ) filename = 'triangle_distance.png' plt.savefig ( filename ) print ( ' Graphics saved as "' + filename + '"' ) plt.show ( ) plt.close ( ) return def triangle_sample ( t, n ): #*****************************************************************************80 # ## triangle_sample() uniformly samples a triangle. # # Discussion: # # The triangle is defined by three vertices. This routine # uses Turk's rule #2. # # Licensing: # # This code is distributed under the MIT license. # # Modified: # # 30 January 2025 # # Author: # # John Burkardt # # Reference: # # Greg Turk, # Generating Random Points in a Triangle, # in Graphics Gems, # edited by Andrew Glassner, # AP Professional, 1990, pages 24-28. # # Input: # # real T(3,2), the X and Y coordinates of the vertices. # # integer N, the number of points desired. # # Output: # # real X(N,2), the points. # import numpy as np # # Choose N random pairs of values in [0,1]. # s = np.random.random ( [ n, 2 ] ) # # We want these pairs to be inside the unit triangle. # If 1 < s0 + s1, replace by 1-s0 and 1-s1. # i = 1.0 < s[:,0] + s[:,1] s[i,:] = 1.0 - s[i,:] # # Use S to compute barycentric coordinates R. # r = np.zeros ( [ n, 3 ] ) r[:,0] = s[:,0] r[:,1] = s[:,1] r[:,2] = 1.0 - r[:,0] - r[:,1] # # X[N,2] = R[N,3] * T[3,2] # x = np.matmul ( r, t ) return x if ( __name__ == "__main__" ): triangle_distance ( )