PS 7.3

4. Let Y_1,…,Y_n represent an i.i.d. sample from an EXP(λ) population. Verify that 〖T=Y〗((i) )-Y((i-1) )∼EXP(λ(n-i+1)) by simulating 10,000 realizations of T for each combination of i∈{3,5,9};n∈{10,15,20}; and λ∈{0.05,0.1}. Plot the simulated densities of T superimposed with the analytic densities.

library(purrrfect)
library(tidyverse)


T_sim <- parameters(~n, ~lambda, ~idx,
                    c(10, 15, 20), c(0.05, 0.1), c(3, 5, 9)) %>%
  add_trials(10000) %>%
  mutate(
    y_sample = pmap(list(n, lambda), \(n, l) rexp(n, rate = l)),
    y_sorted = map(y_sample, sort),
    Y_i = pmap_dbl(list(idx, y_sorted), \(i, y) pluck(y, i)),
    Y_im1 = pmap_dbl(list(idx, y_sorted), \(i, y) pluck(y, i - 1)),
    T = Y_i - Y_im1,
    f_T = (n - idx + 1) * lambda * exp(-(n - idx + 1) * lambda * T)
  )
ggplot(T_sim, aes(x = T)) +
  geom_histogram(aes(y = after_stat(density)), 
                 fill = 'goldenrod', center = 0.1, binwidth = 0.5) +
  geom_line(aes(y = f_T), color = 'cornflowerblue', size = 1) +
  facet_grid(n ~ lambda + idx, labeller = label_both, scales = 'free_x') +
  xlim(0, 7) +
  theme_classic(base_size = 16) +
  labs(title = 'Simulated and Analytic Densities for T = Y_(i) - Y_(i-1)')