Guest User

Untitled

a guest
Dec 14th, 2018
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. '''
  2. Calculate the volume of the n-dimensional spehere a function of the dimension using a simple hit-or-miss Monte Carlo.
  3. '''
  4.  
  5. from __future__ import print_function, division
  6. import numpy as np
  7. import scipy.special
  8. import pylab as plt
  9. import time
  10.  
  11. Dmax = 30 # Largest dimension
  12. N = int(1e7) # Monte Carlo samples
  13.  
  14. data = []
  15.  
  16. for D in np.arange(2,Dmax+1): # Loop
  17. t0=time.time()
  18.  
  19. all = np.random.uniform(-1,1, D*N).reshape(N,D) # Generate points in cube
  20.  
  21. distance = np.sum(all**2,axis=1)**0.5 # Distance from cube center
  22.  
  23. Ninside = np.sum(distance<=1) # Number of points within sphere
  24. fractioninside = Ninside/N # Fraction of points within sphere
  25. cube = 2**D # Volume of the cube (from -1 to 1)
  26. sphere = fractioninside * cube # Volume of the sphere
  27.  
  28. solution = np.pi**(D/2) / scipy.special.gamma( D/2 + 1) # True value
  29. diff= np.abs(sphere-solution)/solution # Error
  30.  
  31. t=time.time()-t0
  32. print("D=%i\tN=%i\tN_in=%06d\tV=%.5f\t\tSol=%.5f\t\tdiff=%.5f\tt=%.2fs" %(D,N,Ninside,sphere,solution,diff,t))
  33.  
  34. data.append([D,sphere,solution,diff]) # Store data
  35.  
  36.  
  37. # Plots...
  38. dims, my,true,errors = np.array(data).T
  39. fig, axs= plt.subplots(2, 1,figsize=(5,10))
  40. axs[0].plot(dims,my,label='my',ls='-',marker='x')
  41. axs[0].plot(dims,true,label='true',ls='-')
  42. axs[1].plot(dims,errors,label='errors')
  43. [ax.legend() for ax in axs]
  44. plt.show()
Add Comment
Please, Sign In to add comment