Let's try to find the volume of a unit sphere in n dimensions (the n-ball) numerically...
The n-ball of radius $R$ in $n$ dimensions has volume $V_{n}(R)$ given by:
$$ V_{n}(R)={\frac {\pi ^{\frac {n}{2}}}{\Gamma \left({\frac {n}{2}}+1\right)}}R^{n} $$
so for $R=1$ we have the exact answer given by (let's call it $U(n)$):
$$ U(n)={\frac {\pi ^{\frac {n}{2}}}{\Gamma \left({\frac {n}{2}}+1\right)}} $$
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from scipy import special
def vol_sphere(n):
"Return the volume of the unit ball in n dimensions"
return np.pi**(n/2)/ special.gamma(n/2+1)
Let's try to find this as an integral, since a volume is always the integral of a region.
def vol_sphere_mc(n, reps=10_000):
points = np.random.uniform(-1, 1, size=(n, reps))
radius = (points**2).sum(axis=0)
return (2**n)*((radius<=1).sum()/reps)
reps = 10_000_000
for n in [2, 3, 4, 10, 20]:
ex = vol_sphere(n)
mc = vol_sphere_mc(n, reps)
print(n, 2**n, ex, mc, 100*abs(ex-mc)/ex )