Files
ArtStudies/M1/Monte Carlo Methods/Exercise2.rmd
2024-10-09 14:46:22 +02:00

47 lines
811 B
Plaintext

# 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}
n <- 10000
S <- numeric(n)
i <- 1
for (j in (1:n)) {
x <- -1 / 4 * log(1 - runif(1))
while (x <= 1) {
i <- i + 1
x <- x - 1 / 4 * log(1 - runif(1))
}
S[j] <- i
i <- 1
}
hist(S, freq = FALSE)
curve(dpois(S, lambda = 4), add = TRUE, col = "red")
```