I’m late for π day

March 15, 2011

(This article was first published on Back Side Smack » R Stuff, and kindly contributed to R-bloggers)

It is officially no longer pi day, but I didn’t see this Drew Conway post about estimating pi until just a few minutes ago. Because Google Reader doesn’t show github embeds, I also got to try it without seeing Drew’s solution. The estimation method relies on exploiting the area of a circle.
Area of a circle and an inscribed square
We can use R to generate random numbers for our x and y coordinates and count up the number of x,y pairs inside the circle (or quarter of a circle, in our case). Because frac {pi} {4} r^2 is the area of our quarter circle, the ratio of the 4 times the number of random coordinates within the quarter circle to the total number of random coordinates should converge on pi . This is a very simple Monte Carlo integration. So what do we get?

From pi day

Gets pretty close! The final error was 2.54641*10^{-6} , not too shabby! I’m computing the running sample average, so it isn’t a true Monte Carlo, but it converges well enough. Code is below:

To leave a comment for the author, please follow the link and comment on their blog: Back Side Smack » R Stuff.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: , , , , ,

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)