Calculating area under any graph

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
}

So far this will only work for functions where x and y are both in (0,1).

set.seed(123)

mcArea <- function(f, n=100) {
  x <- runif(n)
  y <- runif(n)
  mean(y < f(x))
}

f <- function(x){
  x^2
}

mcArea(f)
#> [1] 0.33

Created on 2019-11-13 by the reprex package (v0.3.0)

1 Like

How would i get it where the user could input any function they wanted?
Thanks

They just change f. f is a function of x. Or use a built-in function like this

mcArea(sin)

ahh okays thanks for the help

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)

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.