I am trying to create a function where a user inputs any function, ie x^2, sin(x) ect, and my function needs to estimate the any under the graph using monte carlo methods. So far I have this (see below), but when i put in the console mcArea(f^2) it says object f not found. I know that later I need to implement integration to calculate the area but to start with I'm a bit stuck. I'm new to programming :))
any help would be fab !
mcArea <- function(f, n=100) {
a <- runif(n)
b <- runif(n)
I <- ifelse((f) < 1, TRUE, FALSE) * 1
}
Your mcArea function takes a function as its argument. You need to make sure x and y are big enough to capture the integral. You will probably need to tell mcArea what the x and y extents of the function are. For example you might want to integrate 2*sin(x) from x = 0 to pi and y = 0 to 2. If the function goes negative you will need to think about how to handle that too.
Here's a more general version.
``` r
set.seed(123)
# only handles positive functions
mcArea <- function(f, xmin = 0, xmax = 1, ymin = 0, ymax = 1, n = 1000) {
x <- runif(n, xmin, xmax)
y <- runif(n, ymin, ymax)
mean(y < f(x)) * (xmax - xmin) * (ymax - ymin)
}
f <- function(x){
x ^ 2
}
mcArea(f) # should be 0.333
#> [1] 0.327
mcArea(function(x){x ^ 2}) # this is called an anonymous function. should be 0.333
#> [1] 0.33
mcArea (sin, xmax = pi) # should be 2.000
#> [1] 2.05146
mcArea(function(x){2 * sin(x)}, xmax = pi, ymax = 2) # should be 4
#> [1] 4.153185