6.2 question 6

library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ readr     2.1.5
✔ forcats   1.0.0     ✔ stringr   1.5.1
✔ ggplot2   3.5.2     ✔ tibble    3.3.0
✔ lubridate 1.9.4     ✔ tidyr     1.3.1
✔ purrr     1.1.0     
── 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
library(purrrfect)

Attaching package: 'purrrfect'

The following objects are masked from 'package:base':

    replicate, tabulate
N <- 10000  

dY <- function(y) {
  ifelse(y > 0 & y < 1, 2*(1-y), 0)
}

dU <- function(u) {
  inside <- u > -1 & u < 1
  y <- (1-u)/2
  out <- dY(y) * 0.5
  ifelse(inside, out, 0)
}

dV <- function(v) {
  y <- 1 / v
  ifelse(v > 1, dY(y) * (1 / v^2), 0)
}

dW <- function(w) {
  inside <- w > 0 & w < 1
  y <- w^2
  out <- dY(y) * (2*w)
  ifelse(inside, out, 0)
}

(sim_grid <- parameters(
  ~dummy, 1
) %>% add_trials(10000))
# A tibble: 10,000 × 2
   dummy .trial
   <dbl>  <dbl>
 1     1      1
 2     1      2
 3     1      3
 4     1      4
 5     1      5
 6     1      6
 7     1      7
 8     1      8
 9     1      9
10     1     10
# ℹ 9,990 more rows
sim_res <-
  sim_grid %>%
  mutate(
    Y = rbeta(10000, shape1 = 1, shape2 = 2)
  ) %>%
  mutate(
    U = 1 - 2 * Y,
    V = 1 / Y,
    W = sqrt(Y)
  ) %>%
  mutate(
    fY = dY(Y),
    fU = dU(U),
    fV = dV(V),
    fW = dW(W)
  )

plot for u

ggplot(sim_res, aes(x = U)) +
  geom_histogram(aes(y = after_stat(density)),
                 bins = 40,
                 fill = "gray80", color = "black") +
  geom_line(aes(y = fU),
            linewidth = 1, color = "black") +
  labs(title = "U = 1 - 2Y",
       x = "u", y = "density") +
  theme_classic()

plot for v

ggplot(sim_res, aes(x = V)) +
  geom_histogram(aes(y = after_stat(density)),
                 bins = 40,
                 fill = "gray80", color = "black") +
  geom_line(aes(y = fV),
            linewidth = 1, color = "black") +
  labs(title = "V = 1 / Y",
       x = "v", y = "density") +
  coord_cartesian(xlim = c(1, 10)) +
  theme_classic()

ggplot(sim_res, aes(x = W)) +
  geom_histogram(aes(y = after_stat(density)),
                 bins = 40,
                 fill = "gray80", color = "black") +
  geom_line(aes(y = fW),
            linewidth = 1, color = "black") +
  labs(title = "W = sqrt(Y)",
       x = "w", y = "density") +
  theme_classic()