Created
March 29, 2014 21:27
-
-
Save bpoweski/9863335 to your computer and use it in GitHub Desktop.
Calculating Pi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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