I'm trying to calculate the volume of a hypersphere in n dimensions with radius r. I'm using a Monte-Carlo method of generating points in a hypercube and then taking the ratio of points within a sphere embedded inside it (using the idea that a sphere in 2D is x^2 + y^2 = r^2, in 3D is x^2 + y^2 + z^2 = r^2 etc.) and multiplying it by the volume of the surrounding cube to find the volume of the sphere.
//array to store n co-ordinates for pts points
double co[n+1];
srand(time(NULL));
//iterates over pts points, randomly generating co-ordinates in each dimension and squaring them
for (i = 1; i <= pts; i++)
{
sum = 0;
for (j = 1; j <= n; j++)
{
co[j] = (-r) + 2*r*((double)rand() / (double)RAND_MAX);
sum += pow(co[j],2);
}
//checks if point lies inside the hypersphere
if (sum <= pow(r,2))
{
count++;
}
}
//takes the ratio of points inside the hypersphere and multiplies by the volume of the hypercube (has side length 2r, so volume is (2r)^n) it is inside
v = (count/pts)*pow(2*r,n);
For some reason, the produced volumes are consistently 2^n smaller than they should be (tested using r = 1 in 3D to give 4/3*pi, but actually gives 1/8 of this). I might have fundamentally misunderstood how the method is supposed to work, or else there might be a stupid mistake somewhere. Any help is much appreciated!