diff --git a/M1/Monte Carlo Methods/Exercise6.rmd b/M1/Monte Carlo Methods/Exercise6.rmd new file mode 100644 index 0000000..5e3990e --- /dev/null +++ b/M1/Monte Carlo Methods/Exercise6.rmd @@ -0,0 +1,29 @@ +# Exercise 6 : Rejection - A First Example + +```{r} +f <- function(x) { + return( + (2 / pi * sqrt(1 - x^2)) * (x >= -1 & x <= 1) + ) +} + +n <- 10000 + +M <- 4 / pi +g <- function(x) { + return( + 1 / 2 * (x >= -1 & x <= 1) + ) +} + +x <- NULL +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) +```