#! /usr/bin/env python3 # import matplotlib.pyplot as plt import numpy as np # print ( 'simulate_compare: compare simulation histogram to exact pdf' ) # # n = how many samples we want to create. # n = 10000 # # p1 and p2 record the random locations of the two flies. # We do this n times. # p1 = np.random.rand ( 2, n ) p2 = np.random.rand ( 2, n ) # # d records how far apart the flies are. # d = np.linalg.norm ( p1 - p2, axis = 0 ) # # Now we plot a histogram of the values of d. # plt.hist ( d, bins = 20, rwidth = 0.95, density = True ) # # Now we compute 101 values of the mathematical function (PDF) # that the histogram approximates. # n = 101 d = np.linspace ( 0.0, np.sqrt ( 2.0 ), n ) pdf = np.zeros ( n ) i1 = np.where ( d <= 1.0 ) pdf[i1] = 2 * d[i1] * ( d[i1]**2 - 4 * d[i1] + np.pi ) i2 = np.where ( 1.0 < d ) pdf[i2] = 2 * d[i2] * (4 * np.sqrt ( d[i2]**2 - 1 ) - ( d[i2]**2 + 2 - np.pi ) \ - 4.0 * np.arctan ( np.sqrt ( d[i2]**2 - 1 ) ) ) # # Plot the PDF. # plt.plot ( d, pdf, 'r-', linewidth = 3 ) plt.grid ( True ) plt.xlabel ( '<-- Distance -->' ) plt.ylabel ( '<-- Frequency -->' ) plt.title ( 'Compare exact and observed PDF' ) filename = 'simulate_compare.png' plt.savefig ( filename ) print ( ' Graphics saved as "%s"' % ( filename ) ) plt.show ( )