Last active
June 18, 2026 15:21
-
-
Save Enchufa2/030060c61f6f33935a399173ebaa628b to your computer and use it in GitHub Desktop.
Visualization of Bertrand paradox
This file contains hidden or 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) | |
| bertrand <- list( | |
| function(n) { | |
| theta1 <- runif(n, 0, 2*pi) | |
| theta2 <- runif(n, 0, 2*pi) | |
| data.frame(x1 = cos(theta1), x2 = cos(theta2), | |
| y1 = sin(theta1), y2 = sin(theta2)) | |
| }, | |
| function(n) { | |
| theta <- runif(n, 0, 2*pi) | |
| r <- runif(n, 0, 1) | |
| data.frame(x1 = cos(theta + acos(r)), x2 = cos(theta - acos(r)), | |
| y1 = sin(theta + acos(r)), y2 = sin(theta - acos(r))) | |
| }, | |
| function(n) { | |
| theta <- runif(n, 0, 2*pi) | |
| r <- sqrt(runif(n, 0, 1)) | |
| data.frame(x1 = cos(theta + acos(r)), x2 = cos(theta - acos(r)), | |
| y1 = sin(theta + acos(r)), y2 = sin(theta - acos(r))) | |
| } | |
| ) | |
| df <- lapply(bertrand, do.call, list(n=1e3)) |> | |
| dplyr::bind_rows(.id = "id") |> | |
| dplyr::mutate(length = sqrt((x1-x2)^2 + (y1-y2)^2), | |
| larger = length > 2*sin(pi/3)) | |
| df |> dplyr::summarise(mean(length), mean(larger), .by=id) | |
| p1 <- ggplot(df) + facet_grid(~id) + | |
| labs(title = "Distribution of chords") + | |
| aes(x = x1, xend = x2, y = y1, yend = y2, color = larger) + | |
| coord_fixed() + xlim(-1, 1) + ylim(-1, 1) + theme_void() + | |
| scale_color_manual(values = c("gray11", "red")) + | |
| geom_segment(size = 0.05, show.legend = FALSE) | |
| p2 <- ggplot(df) + facet_grid(~id) + | |
| labs(title = "Distribution of midpoints") + | |
| aes(x = (x1+x2)/2, y = (y1+y2)/2, color = larger) + | |
| coord_fixed() + xlim(-1, 1) + ylim(-1, 1) + theme_void() + | |
| scale_color_manual(values = c("gray11", "red")) + | |
| geom_point(size = 0.05, show.legend = FALSE) | |
| p3 <- ggplot(df) + facet_grid(~id) + | |
| labs(title = "Distribution of lengths") + | |
| aes(x = length, fill = larger) + | |
| theme_linedraw() + | |
| scale_fill_manual(values = c("gray11", "red")) + | |
| geom_histogram(show.legend = FALSE) | |
| patchwork::wrap_plots(p1, p2, p3, ncol=1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
