From 24d2254cb7e294a78ab37898e5fb040713701641 Mon Sep 17 00:00:00 2001 From: Arthur DANJOU Date: Wed, 25 Sep 2024 15:15:39 +0200 Subject: [PATCH] Add exo 7 --- M1/Monte Carlo Methods/Exercise7.rmd | 32 ++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 M1/Monte Carlo Methods/Exercise7.rmd diff --git a/M1/Monte Carlo Methods/Exercise7.rmd b/M1/Monte Carlo Methods/Exercise7.rmd new file mode 100644 index 0000000..360422e --- /dev/null +++ b/M1/Monte Carlo Methods/Exercise7.rmd @@ -0,0 +1,32 @@ +# Exercise 7 : Rejection + +```{r} +n <- 5000 + +f <- function(x, y) { + return( + 1 / pi * (x^2 + y^2 <= 1) + ) +} + +M <- 4 / pi +g <- function(x, y) { + return( + 1 / 4 * (x >= -1 & x <= 1 & y >= -1 & y <= 1) + ) +} + +x <- NULL +y <- NULL +while (length(x) < n) { + U <- runif(1) + X <- runif(1, -1, 1) + Y <- runif(1, -1, 1) + x <- append(x, X[U <= (f(X, Y) / (M * g(X, Y)))]) + y <- append(y, Y[U <= (f(X, Y) / (M * g(X, Y)))]) +} + +t <- seq(-1, 1, 0.01) +plot(x, y) +contour(t, t, outer(t, t, Vectorize(f)), add = TRUE, col = "red", lwd = 2) +```