Skip to content

Instantly share code, notes, and snippets.

@bpoweski
Created March 29, 2014 21:27
Show Gist options
  • Save bpoweski/9863335 to your computer and use it in GitHub Desktop.
Save bpoweski/9863335 to your computer and use it in GitHub Desktop.
Calculating Pi
attempts <- seq(1000, 1000000, by=10000)
estimated <- sapply(attempts, function(x) calc.pi(make.pi(x)))
ggplot(data.frame(estimated=estimated, n=attempts)) + geom_point(aes(x=n, y=estimated)) + geom_hline(yintercept=pi, color="green")
library("ggplot2")
set.seed(13)
make.pi <- function(n) {
darts <- data.frame(x=runif(n), y=runif(n))
darts$hit <- (darts$x^2 + darts$y^2) <= 1
darts
}
calc.pi <- function(df) {
4*sum(df$hit)/nrow(df)
}
sim <- make.pi(10000)
ggplot(sim, aes(x, y, color=hit)) + geom_point() + ggtitle(calc.pi(sim))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment