Playing With R

I played around a bit with R (wikipedia link). It’s nice. R is a language often used in statistics, data analysis and stuff like that.

The following code estimates pi using the ratio between the area of the square enclosed by the circle (which is Pi). This is part of an assignment a friend of mine has to do for his statistics class in a masters:

est.pi <- function(n=2000) {

x <- runif(n)
y <- runif(n)

aux <- (x[]^2) + (y[]^2)

aux2 <- c()

for (i in 1:length(aux)) {
if (aux[i] < 1)
aux2[i] <- TRUE
else
aux2[i] <- FALSE
}

result <- (sum(aux2) / n) * 4
print(result)
}

This one calculates pi the calculus way (sum of the areas of the rectangles) instead of statistics. I did this just because I couldn’t figure out how to do it using statistics (until I was told the method that is):

calc.pi <- function(n=50000) {
count <- 1
total <- 0
x<-seq(0,1,length=n)

while(count < n) {
lenx <- x[count+1] - x[count]
leny <- sqrt(1 - x[count]^2)
total <- total + lenx*leny
count <- count + 1
}
print(total*4)
}


Leave a Comment