I'm trying to learn R. I'm trying to write a program which calculates (approximately) pi. Read About the method
My code is not working right now!
f <- 0
s <- 0
range <- 10000
for (i in (1:range)) {
v <- sample(1:range, 1)/range
n <- sample(1:range, 1)/range
if ( sqrt (v*v + n*n) <= 1) {
f <- f + 1
} else if ( v <=1 && n <= 1) {
s <- s+1
}
}
print ( f/s )
Here's an improved version of your code
range = 100000
v = runif(range)
n = runif(range)
f = sum(sqrt(v^2 + n^2) <= 1)
print(4 * f / range)
You should use runif
to get samples from a uniform instead of sample(...) / range
.
The s
is unnecessary since what you're doing is counting the number of times, f
, that your random point (v,n)
is within the circle in that quadrant, divided by the number of attempted draws, which would just be range
in your case.
You need to multiply by 4
since f / range
approximates the area of one-quarter of the unit circle.