Quantcast
Channel: r software hub
Viewing all articles
Browse latest Browse all 1015

Happy PI day

$
0
0

By Wingfeet

I have never done a post for PI day. This year I want to do so.

So, we all know the simple estimation of PI based on random numbers. The code used here is chosen for speed in R.

pi2d

4*sum(rowSums(matrix(runif(N*2)^2,ncol=2))

}

What irritates me, is the low efficiency of this estimate. What do you get for 10 000 simulations? Probably, but not even certain, the first two digits.

summary(sapply(1:1000,function(x) pi2d(10000)))

Min. 1st Qu. Median Mean 3rd Qu. Max.

3.080 3.130 3.141 3.141 3.153 3.189

In the past years I have been thinking how to get that more efficient, but that is not obvious. For instance, it is possible to use the three dimensional equivalent, a ball:

pi3d

6*sum(rowSums(matrix(runif(N*3)^2,ncol=3))
}

summary(sapply(1:1000,function(x) pi3d(10000)))
Min. 1st Qu. Median Mean 3rd Qu. Max.

3.052 3.121 3.140 3.142 3.161 3.243

This is even worse, the variation is higher.

At some point I thought this is due to the limited information in such a calculation, it is binomial and one simulation gives one bit of information. And it could be more simple. If the first random number is known, say y, then all second random numbers over sqrt(1-y2) give distance larger than 1, while the remainder gives distance less than 1. Thus should pi be equal to the mean of random numbers transformed like sqrt(1-y2)?
pin
4*sum(sqrt(1-runif(N)^2))/N
}
summary(sapply(1:1000,function(x) pin(10000)))
Min. 1st Qu. Median Mean 3rd Qu. Max.
3.113 3.135 3.142 3.141 3.147 …read more

Source:: r-bloggers.com


Viewing all articles
Browse latest Browse all 1015