Description Usage Arguments Details Value Note Author(s) References See Also
View source: R/MC.samplemean.R
Integrate a function from 0 to 1 using the Sample Mean Monte Carlo algorithm
1 2 3 4 5 6 7 | MC.samplemean(
FUN = function(x) x - x^2,
n = ani.options("nmax"),
col.rect = c("gray", "black"),
adj.x = TRUE,
...
)
|
FUN |
the function to be integrated |
n |
number of points to be sampled from the Uniform(0, 1) distribution |
col.rect |
colors of rectangles (for the past rectangles and the current one) |
adj.x |
should the locations of rectangles on the x-axis be adjusted?
If |
... |
other arguments passed to |
Sample Mean Monte Carlo integration can compute
I=\int_0^1 f(x) dx
by drawing random numbers x_i from Uniform(0, 1) distribution and average the values of f(x_i). As n goes to infinity, the sample mean will approach to the expectation of f(X) by Law of Large Numbers.
The height of the i-th rectangle in the animation is f(x_i) and the width is 1/n, so the total area of all the rectangles is ∑ f(x_i) 1/n, which is just the sample mean. We can compare the area of rectangles to the curve to see how close is the area to the real integral.
A list containing
x |
the Uniform random numbers |
y |
function values evaluated at |
n |
number of points drawn from the Uniform distribtion |
est |
the estimated value of the integral |
This function is for demonstration purpose only; the integral might be
very inaccurate when n
is small.
ani.options('nmax')
specifies the maximum number of trials.
Yihui Xie
Examples at https://yihui.org/animation/example/mc-samplemean/
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.