# Exercise 2 : Exponential distribution and related distributions

### Question 1
```{r}
n <- 10000
u <- runif(n)
x <- -1/2 * log(1-u)
hist(x, breaks = 50, freq = FALSE)
curve(dexp(x, rate = 2), add = TRUE, col = "red")

qqplot(x, rexp(n, rate = 2))
```

### Question 2

```{r}
lambda <- 1.5
n <- 10000
d <- 10
S <- numeric(n)
for (i in 1:n) {
    u <- runif(d)
    x <- -1/lambda * log(1-u)
    S[i] <- sum(x)
}
hist(S, freq = FALSE, breaks = 50)
curve(dgamma(x, shape = d, rate = lambda), add = TRUE, col = "red")
```

### Question 3
```{r}
lambda <- 4
n <- 10000
X <- numeric(n)
p <- 1
for (i in 1:n) {
    S <- -1/lambda * log(1-runif(1))
    while (S <= 1) {
      S <- x - 1/lambda * log(1-runif(1))
      p <- p+1
    }
    X[i] <- p
    p <- 1
}
hist(X, freq = FALSE, breaks = 50)
curve(dpois(x, lambda), add = TRUE, col = "red")
```
