Día π
El 14 de marzo se celebra el día de
Una manera de aproximar su valor es mediante puntos ubicados aleatoriamente sobre un cuadrado, que posee un círculo inscrito, como se muestra a continuación:
La proporción de puntos dentro del círculo respecto del total se acerca a la cuarta parte de
Siendo
El script muestra como un aumento progresivo de
Paquetes
Ocultar código
library(glue)
library(showtext)
library(ggtext)
library(tidyverse)
Función
Genera un tibble
a partir de la cantidad de puntos dada (
Ocultar código
<- function(z) {
f_pi
set.seed(2025)
<- tibble(
d x = runif(n = z, min = -1, max = 1),
y = runif(n = z, min = -1, max = 1),
r = sqrt(x^2 + y^2),
estado = if_else(r <= 1, "in", "out"),
grupo = paste0("p", format(z, scientific = FALSE))
)
return(d)
}
Colores y fuentes
Ocultar código
<- "#E88934"
c1 <- "#1E466E"
c2 <- "grey60"
c3 <- "black"
c4 <- "#637B31"
c5 <- "#208CC0"
c6 <- "#7528AF"
c7 <- "grey90" c8
Fuentes: Ubuntu y JetBrains Mono.
Ocultar código
font_add(
family = "ubuntu",
regular = "./fuente/Ubuntu-Regular.ttf",
bold = "./fuente/Ubuntu-Bold.ttf",
italic = "./fuente/Ubuntu-Italic.ttf"
)
# monoespacio & íconos
font_add(
family = "jet",
regular = "./fuente/JetBrainsMonoNLNerdFontMono-Regular.ttf"
)
showtext_auto()
showtext_opts(dpi = 300)
Epígrafe
Ocultar código
<- glue("<span style='color:{c2};'>**Víctor Gauto**</span>")
autor <- glue("<span style='font-family:jet;'></span>")
icon_twitter <- glue("<span style='font-family:jet;'></span>")
icon_instagram <- glue("<span style='font-family:jet;'></span>")
icon_github <- glue("<span style='font-family:jet;'>󰫑</span>")
icon_mastodon <- glue("<span style='font-family:jet;'></span>")
icon_bsky <- glue("<span style='color:{c2};'>**vhgauto**</span>")
usuario <- glue("**|**")
sep
<- glue(
mi_caption "{autor} {sep} {icon_github} {icon_twitter} {icon_instagram} ",
"{icon_mastodon} {icon_bsky} {usuario}"
)
Datos
Símbolos útiles
Ocultar código
<- ""
pi_etq <- ""
punto_etq <- glue(" <b style='color: {c3}'>|</b> ") sep_etq
Genero una única base de datos, agrupados por la cantidad de puntos (
Ocultar código
<- map(c(1e3, 1e4, 1e5, 1e6), f_pi) |>
d list_rbind() |>
mutate(
grupo = fct_inorder(grupo)
)
<- d |>
titulo_tbl reframe(
pi_aprox = sum(estado == "in")/n()*4,
.by = grupo
|>
) mutate(
prob = round(abs((pi_aprox - pi)/pi*100), 3),
.by = grupo
|>
) mutate(
p = as.numeric(sub("p", "", grupo))
|>
) mutate(
etq1 = paste0(
format(
big.mark = ".", decimal.mark = ",", scientific = FALSE, trim = TRUE
p,
),
punto_etq),etq2 = paste0(
" ≈ ",
pi_etq, format(
round(pi_aprox, 5),
nsmall = 5, big.mark = ".", decimal.mark = ",", trim = TRUE
)
),etq3 = paste0(
format(
round(prob, 3),
nsmall = 3, big.mark = "", decimal.mark = ",", trim = TRUE
),"%"
)|>
) mutate(
etq1 = glue("<span style='color: {c5}'>{etq1}</span>"),
etq2 = glue("<span style='color: {c6}'>{etq2}</span>"),
etq3 = glue("<span style='color: {c7}'>{etq3}</span>")
|>
) mutate(
etq = glue("{etq1}{sep_etq}{etq2}{sep_etq}{etq3}")
)
<- set_names(
strip_titulo x = titulo_tbl$etq,
nm = titulo_tbl$grupo
)
Figura
El título es una expresión en LaTeX
.
Ocultar código
<- latex2exp::TeX(r"($\lim_{n\to\infty} \frac{t}{n} = \frac{\pi}{4} $)") eq
Subtítulo y figura.
Ocultar código
<- glue(
mi_subtitulo "*t* es el número de <b style='color: {c1}'>puntos dentro del círculo</b> y
<span style='color: {c5}'>*n* es el total</span>,
aleatoriamente ubicados.<br>
Para cada panel se indican <b style='color: {c5}'>n</b>, el
<b style='color: {c6}'>valor aproximado de
<span style='font-family: jet'>{pi_etq}</span></b>
y el <b style='color: {c7}'>error porcentual</b>."
)
<- ggplot(d, aes(x, y, color = estado)) +
g geom_point(
size = .1, alpha = .5, show.legend = FALSE
+
) facet_wrap(vars(grupo), ncol = 2,
labeller = as_labeller(strip_titulo)
+
) scale_color_manual(
breaks = c("in", "out"),
values = c(c1, c2)
+
) coord_equal(clip = "off", expand = FALSE) +
labs(
title = eq, subtitle = mi_subtitulo, caption = mi_caption
+
) theme_void() +
theme(
plot.background = element_rect(fill = c8, color = NA),
plot.margin = margin(r = 15, l = 15),
plot.title = element_text(
family = "sans serif", size = 40, hjust = .5, margin = margin(t = 20),
color = c2
),plot.subtitle = element_markdown(
size = 22, hjust = .5, margin = margin(t = 15, b = 25), lineheight = 1.4
),plot.caption = element_markdown(
family = "ubuntu", color = c1, size = 15, margin = margin(t = 20, b = 15)
),panel.spacing.x = unit(1, "cm"),
strip.text = element_markdown(
family = "jet", size = 15, margin = margin(t = 10, b = 5), color = c4
) )
Guardo la figura creada.
Ocultar código
ggsave(
plot = g,
filename = paste0(getwd(), "/viz/pi.png"),
width = 30,
height = 37,
units = "cm"
)