4.2 #8

library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.2.1     ✔ readr     2.2.0
✔ forcats   1.0.1     ✔ stringr   1.6.0
✔ ggplot2   4.0.3     ✔ tibble    3.3.1
✔ lubridate 1.9.5     ✔ tidyr     1.3.2
✔ purrr     1.2.2     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
a <- 2
b <- 6

set.seed(370)
(sim_y <- data.frame(U = runif(10000, 0, 1))
  %>% mutate(Y = a + (b - a) * sin(pi * U / 2)^2)
  %>% mutate(Fhat_Y = cume_dist(Y),
             F_Y = (2 / pi) * asin(sqrt((Y - a) / (b - a))))
) %>% head
           U        Y Fhat_Y        F_Y
1 0.39037489 3.324741 0.3900 0.39037489
2 0.05187123 2.026497 0.0527 0.05187123
3 0.19400526 2.360115 0.1896 0.19400526
4 0.96089048 5.984923 0.9602 0.96089048
5 0.74730983 5.402211 0.7459 0.74730983
6 0.01052215 2.001093 0.0108 0.01052215
# a
(ggplot(data = sim_y)
  + geom_histogram(aes(x = Y, y = after_stat(density)),
                   fill = 'goldenrod',
                   binwidth = 0.1,
                   center = 2.05)
  + geom_function(fun = \(y) 1 / (pi * sqrt((y - a) * (b - y))),
                  col = 'cornflowerblue',
                  linewidth = 1,
                  n = 1000,
                  xlim = c(a + 0.001, b - 0.001))
  + coord_cartesian(ylim = c(0, 1))
  + theme_classic(base_size = 16)
)

# b
(ggplot(data = sim_y)
  + geom_step(aes(x = Y, y = Fhat_Y, color = 'Simulated CDF'))
  + geom_step(aes(x = Y, y = F_Y, color = 'Analytic CDF'))
  + scale_color_discrete(name = '')
  + theme_classic(base_size = 16)
)

# c
(ggplot(data = sim_y)
  + geom_point(aes(x = Fhat_Y, y = F_Y), size = .1)
  + geom_abline(aes(intercept = 0, slope = 1), color = 'red')
  + theme_classic(base_size = 16)
)