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
Created on 2019-11-13 by the reprex package (v0.3.0)