Using the hit-or-miss method to estimate the volume of a hypersphere centered at the origin in R

676 Views Asked by At

I just need some help on how to get started on this problem, cant use any libraries and relatively new to R. I understand it has to be a 2 for loops inside each other.

1

There are 1 best solutions below

0
On

I suppose this is the kind of implementation @AndreasBlass had in mind in his Comment. It is only for $d = 3$ and won't work well for large $d$ because then the hit rate will be way too low. I'm using the unit sphere.

Perhaps you can point out why this 'obvious' method doesn't match the level of your course. It certainly doesn't have (overt) nested for-loops.

x1 = runif(10^6, -1,1);  x2 = runif(10^6, -1,1);  x3 = runif(10^6, -1,1)
inside = (x1^2 + x2^2 + x3^2 < 1)
mean(inside)
## 0.523128    # hit rate
8*mean(inside)
## 4.185024    # aprx volume of sphere
4*pi/3
## 4.18879     # exact volume of sphere

The following works for the unit ball in $d$ dimensions ($d$ not too large), and the R code is a bit more elegant.

set.seed(2017)
m = 10^6;  d = 3;  x = runif(m*d, -1, 1)
MAT = matrix(x, nrow=m);  r = rowSums(MAT^2)
2^d*mean(r < 1)
## 4.190264        # Monte Carlo
pi^(d/2)/gamma(1 + d/2)
## 4.18879         # Exact