I want to calculate area under the curve using monte carlo simulation of function
. I want to calculate it on interval [-2, 2]
My work so far
# Define function f
f <- function(x) x^2 + 1
# I want to close my function in rectangle (-2, 2) - x axis and (1, 5) y -axis
n <- 10^6
# Randomize from x axis of rectangle
x_n <- runif(n, min = -2, max = 2)
# Randomize from y axis of rectangle
y_n <- runif(n, min = 1, max = 5)
# Calculate function values of randomized points
values <- f(x_n)
# Formula for are under the curve for monte carlo simulation is
# Area of rectangle * (Points below curve) / (Total number of points)
So my result is:
> sum(y_n < values) / n * (4 * 4)
[1] 5.329888
which is bad result (correct result is 9.33333). What I'm doing wrong? For sure algorithm should have been much closer to 9.3333 after milion sampling