Learn R Programming

animation (version 2.0-5)

MC.hitormiss: Hit or Miss Monte Carlo integration

Description

Integrate a function using the Hit-or-Miss Monte Carlo algorithm

Usage

MC.hitormiss(FUN = function(x) x - x^2, n = ani.options("nmax"), 
    from = 0, to = 1, col.points = c("black", "red"), pch.points = c(20, 
        4), ...)

Arguments

FUN
the function to be integrated
n
number of points to be sampled from the Uniform(0, 1) distribution
from,to
the limits of integration
col.points,pch.points
colors and point characters for points which ``hit'' or ``miss'' the area under the curve
...
other arguments passed to points

Value

  • A list containing
  • x1the Uniform random numbers generated on x-axis
  • x2the Uniform random numbers generated on y-axis
  • yfunction values evaluated at x1
  • nnumber of points drawn from the Uniform distribtion
  • estthe estimated value of the integral

Details

We compute the proportion of points hitting the area under the curve, and the integral can be estimated by the proportion multiplied by the total area of the rectangle (from xmin to xmax, ymin to ymax).

References

http://animation.yihui.name/compstat:hit_or_miss_monte_carlo

See Also

integrate, MC.samplemean

Examples

Run this code
oopt = ani.options(interval = 0.2, nmax = ifelse(interactive(), 
    100, 2))

## should be close to 1/6
MC.hitormiss()$est

## should be close to 1/12
MC.hitormiss(from = 0.5, to = 1)$est

## HTML animation page
saveHTML({
    ani.options(interval = 0.5, nmax = ifelse(interactive(), 
        100, 2))
    MC.hitormiss()
}, img.name = "MC.hitormiss", htmlfile = "MC.hitormiss.html", 
    title = "Hit or Miss Monte Carlo Integration", description = c("", 
        "Generate Uniform random numbers", "and compute the proportion", 
        "of points under the curve."))

ani.options(oopt)

Run the code above in your browser using DataLab