# -*- coding: utf-8 -*- """ volume of an n-sphere, relative to an n-cube @author: neil 2022 """ import numpy as np print('numerical integration to achieve 2 figure accuracy for an 8-sphere requires >> 10^17 calculations') # Analytic soln print('Analytic solution of volume on an 8 dimensional sphere: {:.5f}'.format( 4.057*(.5)**8 )) # Our approach to MC integration is to throw darts (random guesses) # at an n-sphere inscribed in a n-cube and calculate the number of hits vs the total throws, # which will approx the ratio of the volumes. # For this we use a radius of 0.5, that way we know easily the volume of the n-cube (=1!) # Define number of samples N = 100000 d = 8 # define number of dimensions x = np.random.rand(N,d)-.5 # a 'pythonic' method to make an N by d array of uniform random numbers between -.5 and +.5 hits=0 for j in np.arange(N): norm=0 for s in range(d): norm+= x[j,s]**2 # calc the square of the pythagorean distance from the origin in n-dimensions # np.linalg.norm(x,axis=1) replaces much of the above loop, returns the sum of the squares of a row of the x=array if np.sqrt(norm) <= .5: # if the distance is less than the radius, we have a HIT! hits += 1 # after the above we have the sum of chosen points in n-space that were inside the n-sphere # Calculate integral by taking the ratio of points in and out to the area of the unit square unit_vol = 1**d # volume of unit cube in all dimensions is 1! integral = (hits / N) print("Monte Carlo Integral estimate of 8-sphere volume: {:.5f}".format(integral/unit_vol))