Advertisement
Guest User

Untitled

a guest
Jan 26th, 2020
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. import random
  2. import numpy as np
  3.  
  4.  
  5. def testHistFn2D():
  6. numSample = 10000
  7. xs = np.array( [random.random() for i in range(numSample)] )
  8. ys = np.array( [random.random() for i in range(numSample)] )
  9. numbins = 10
  10. test_fn_1 = xs + ys
  11.  
  12. # MC, the histogram becomes a pdf by weighting the points by 1/numSample * (1/size of a bin)
  13. h0,b0 = np.histogram(test_fn_1, numbins, weights=numbins/(2.*numSample)*np.ones(len(xs)))
  14. plt.errorbar(x=(b0[:-1]+b0[1:])/2., y=h0, xerr=(b0[:-1]-b0[1:])/2.);
  15.  
  16. # Actual pdf for x + y
  17. pdf = lambda xi: (xi<1)*xi + (xi>1)*(2.-xi)
  18. plt.plot(np.linspace(0.,2.,40), pdf(np.linspace(0.,2.,40)))
  19.  
  20. # Summing MC histogram, i.e. sum_bins pdf(bin)*(size of bin), should return one
  21. print( np.sum( h0 )*2./numbins )
  22.  
  23. #compare the two
  24. plt.show()
  25.  
  26. def testHistFn3D():
  27. numSample = 10000
  28. xs = np.array( [random.random() for i in range(numSample)] )
  29. ys = np.array( [random.random() for i in range(numSample)] )
  30. zs = np.array( [random.random() for i in range(numSample)] )
  31. numbins = 10
  32. test_fn_1 = xs + ys + zs
  33.  
  34. # MC
  35. h0,b0 = np.histogram(test_fn_1, numbins, weights=numbins/(3.*numSample)*np.ones(len(xs)))
  36. plt.errorbar(x=(b0[:-1]+b0[1:])/2., y=h0, xerr=(b0[:-1]-b0[1:])/2.);
  37.  
  38. # Analytic
  39. pdf = lambda xi: (4./9.)*( (xi<3./2.)*xi + (xi>3./2.)*(3.-xi))
  40. plt.plot(np.linspace(0.,3.,40), pdf(np.linspace(0.,3.,40)))
  41.  
  42. # Should return 1
  43. print( np.sum( h0 )*3./numbins )
  44.  
  45. # Compare
  46. plt.show()
  47.  
  48.  
  49. if __name__ == "__main__":
  50. testHistFn2D()
  51. testHistFn3D()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement