Skip to content

Instantly share code, notes, and snippets.

@bpbond
Last active November 6, 2019 00:55
Show Gist options
  • Save bpbond/2c0055859e686558ffce81c3d43a4f74 to your computer and use it in GitHub Desktop.
Save bpbond/2c0055859e686558ffce81c3d43a4f74 to your computer and use it in GitHub Desktop.
Approximate pi by throwing darts
library(tibble)
library(ggplot2)
# Imagine a circle inscribed in a unit square
# We can converge (slowly) on the value of pi by throwing random darts
# at this target; counting how many fall in versus out of the circle;
# and using the resulting approximate area ratio to calculate pi.
set.seed(12345)
n_darts <- 1000
darts <- tibble(dart = seq_len(n_darts),
x = runif(0, 1, n = n_darts), # each dart lands at x,y
y = runif(0, 1, n = n_darts),
# if a dart is within 0.5 units of the center, it's "in"
dist_from_center = sqrt((x - 0.5) ^ 2 + (y - 0.5) ^ 2),
in_circle = dist_from_center <= 0.5,
in_count = cumsum(in_circle),
# running approximation for pi, based on A = pi r^2
pi_est = in_count / dart / 0.25)
qplot(dart, pi_est, data = darts, geom = "line") + geom_hline(yintercept = pi, color = "blue")
# I actually did this one time with a class for real--dropped objects from
# a second floor balcony and counted how many landed in versus out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment