From ad0707972b9ea2e3180ab7cfceb18aff193bf1c0 Mon Sep 17 00:00:00 2001 From: Rob Hyndman Date: Wed, 20 Mar 2024 11:21:51 +1100 Subject: [PATCH] Updated code from week 4 workshop --- week4/workshop_code.R | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/week4/workshop_code.R b/week4/workshop_code.R index adca208..0cd63cb 100644 --- a/week4/workshop_code.R +++ b/week4/workshop_code.R @@ -134,3 +134,29 @@ sq <- function(x) { memo_sq <- memoise(sq) memo_sq(2) memo_sq(2) + +## Vectorisation + +calc_area <- function(N = 1e4) { + hits <- 0 + N <- 1e3 + for(i in seq(N)) { + u1 <- runif(1, 0,1) + u2 <- runif(1, 0,1) + if(u2 < u1^2) + hits <- hits + 1 + } + hits/N +} + +calc_area2 <- function(N = 1e4) { + u1 <- runif(N, 0, 1) + u2 <- runif(N, 0, 1) + mean(u2 < u1^2) +} + +bench::mark( + calc_area(), + calc_area2(), + check = FALSE +)