0

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!

user193369
  • 17
  • 4
  • A hypersphere is inscribed in a hypercube. The radius of the hypersphere is r. What is the side of the hypercube? What is the volume? Show them in your code. – n. m. could be an AI Nov 09 '16 at 15:06
  • Made the edit - also thanks so much because i realised i was taking the side length to be r when it should be 2r. Changed this and it now works perfectly! Thanks so much, knew it was something simple! – user193369 Nov 09 '16 at 15:14
  • Tangentially, in C we generally start counting at zero and end with a `<` check, i.e. `for (i=0; i – n. m. could be an AI Nov 09 '16 at 15:19
  • The first item `col[0]` seems never computed and also never added in the `sum`. Is it expected ? – J. Piquard Nov 09 '16 at 21:59
  • I have performed comparative tests between your source code (a compilable source based from your source code) and formula to compute [hyper-sphere volume](https://people.ok.ubc.ca/jbobowsk/Maple/Monte%20Carlo%20hypersphere.pdf) and for `pts = 1000000;`, I get a good correlation. Please provide a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – J. Piquard Nov 10 '16 at 11:25

0 Answers0