Created
August 17, 2021 01:26
-
-
Save maxdrohde/21d7b8a5978ba36661ef99b26698791c to your computer and use it in GitHub Desktop.
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(tidyverse) | |
library(gganimate) | |
set.seed(777) | |
points <- 2* 1e3 | |
x <- runif(points, min = -1, max=1) | |
y <- runif(points, min=-1, max=1) | |
inside <- x^2 + y^2 < 1 | |
df <- tibble(x, y, inside, frame=1:points) | |
ns <- map(1:points, ~(1:points)[1:.x]) | |
estimates <- | |
map_dbl(ns, ~df[.x,]$inside %>% mean %>% magrittr::multiply_by(4)) | |
df$estimate <- estimates | |
estimates <- sprintf("%.8f", estimates) | |
n <- 1:points | |
df$pi_estimate <- as_factor(glue::glue("Estimate with {n} points = {estimates}")) | |
anim <- | |
df %>% | |
ggplot() + | |
aes(x=x, y=y, color=inside) + | |
geom_point() + | |
coord_equal(xlim = c(-1,1), ylim=c(-1,1)) + | |
theme_minimal() + | |
theme(legend.position = "none") + | |
labs(title="{current_frame}") + | |
transition_manual(frame = pi_estimate, cumulative=TRUE) | |
anim2 <- | |
df %>% | |
ggplot() + | |
aes(x=frame, y=estimate) + | |
geom_point(size=0.2) + | |
geom_hline(mapping=aes(yintercept=pi), linetype=2) + | |
theme_minimal() + | |
coord_cartesian(ylim=c(2.5,4.25)) + | |
labs(x="Number of points", y="Estimated value") + | |
transition_manual(frame=frame, cumulative=TRUE) | |
gif <- animate(anim, | |
duration=10, | |
fps = 60, | |
height = 6, | |
width = 6, | |
units = "in", | |
res = 300, | |
renderer = ffmpeg_renderer()) | |
# Save to mp4 | |
anim_save(animation = gif, filename = "monte_carlo_circle.mp4") | |
gif <- animate(anim2, | |
duration=10, | |
fps = 60, | |
height = 6, | |
width = 6, | |
units = "in", | |
res = 300, | |
renderer = ffmpeg_renderer()) | |
# Save to mp4 | |
anim_save(animation = gif, filename = "monte_carlo_circle_lineplot.mp4") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment