[R] Numerical integration
David Winsemius
dwinsemius at comcast.net
Wed Nov 17 16:57:14 CET 2010
On Nov 17, 2010, at 6:44 AM, Eduardo de Oliveira Horta wrote:
> Hi!
>
> I was wondering if there are any other functions for numerical
> integration,
> besides 'integrate' from the stats package, but which wouldn't
> require the
> integrand to be vectorized. Oh, and must be capable of integrating
> over
> (-inf,+inf).
You could modify integrate to suit you specifications, Just substitute
this at the beginning of the integrate:
integrateV <- function (f, lower, upper, ..., subdivisions = 100,
rel.tol = .Machine$double.eps^0.25,
abs.tol = rel.tol, stop.on.error = TRUE, keep.xy = FALSE,
aux = NULL)
{
f <- match.fun(f)
### New material
options(show.error.messages = FALSE)
if( class(try(integrate(f, upper, lower))) == 'try-error') {f <-
Vectorize(f)}
options(show.error.messages = TRUE)
### End new material
ff <- function(x) f(x, ...)
.
.
.
Passes both your requirements:
> zz<- function(x) 2.0 # the function that fails in the integrate
help page
> try(integrateV(zz, 0, 1))
2 with absolute error < 2.2e-14
> zz<- function(x) dnorm(x) # test of infinite range capacity
> try(integrateV(zz, -Inf, Inf))
1 with absolute error < 9.4e-05
--
David Winsemius, MD
West Hartford, CT
More information about the R-help
mailing list