# Exercise 6 : Rejection - A First Example

```{r}
f <- function(x) {
  2 / pi * sqrt(1 - x^2) * (x >= -1 & x <= 1)
}

n <- 10000

M <- 4 / pi
g <- function(x) {
  1 / 2 * (x >= -1 & x <= 1)
}

x <- numeric(0)
while (length(x) < n) {
  U <- runif(1)
  X <- runif(1, -1, 1)
  x <- append(x, X[U <= (f(X) / (M * g(X)))])
}

t <- seq(-1, 1, 0.01)
hist(x, freq = FALSE, breaks = 50)
lines(t, f(t), col = "red", lwd = 2)
```
