numericDeriv {stats}R Documentation

Evaluate Derivatives Numerically

Description

numericDeriv numerically evaluates the gradient of an expression.

Usage

numericDeriv(expr, theta, rho = parent.frame(), dir = 1,
             eps = .Machine$double.eps ^ (1/if(central) 3 else 2), central = FALSE)

Arguments

expr

expression or call to be differentiated. Should evaluate to a numeric vector.

theta

character vector of names of numeric variables used in expr.

rho

environment containing all the variables needed to evaluate expr.

dir

numeric vector of directions, typically with values in -1, 1 to use for the finite differences; will be recycled to the length of theta.

eps

a positive number, to be used as unit step size h for the approximate numerical derivative (f(x+h)-f(x))/h or the central version, see central.

central

logical indicating if central divided differences should be computed, i.e., (f(x+h) - f(x-h)) / 2h . These are typically more accurate but need more evaluations of f().

Details

This is a front end to the C function numeric_deriv, which is described in Writing R Extensions.

The numeric variables must be of type double and not integer.

Value

The value of eval(expr, envir = rho) plus a matrix attribute "gradient". The columns of this matrix are the derivatives of the value with respect to the variables listed in theta.

Author(s)

Saikat DebRoy saikat@stat.wisc.edu; tweaks and eps, central options by R Core Team.

Examples

myenv <- new.env()
myenv$mean <- 0.
myenv$sd   <- 1.
myenv$x    <- seq(-3., 3., length.out = 31)
nD <- numericDeriv(quote(pnorm(x, mean, sd)), c("mean", "sd"), myenv)
str(nD)

## Visualize :
require(graphics)
matplot(myenv$x, cbind(c(nD), attr(nD, "gradient")), type="l")
abline(h=0, lty=3)
## "gradient" is close to the true derivatives, you don't see any diff.:
curve( - dnorm(x), col=2, lty=3, lwd=2, add=TRUE)
curve(-x*dnorm(x), col=3, lty=3, lwd=2, add=TRUE)
##
# shows 1.609e-8 on most platforms
all.equal(attr(nD,"gradient"),
          with(myenv, cbind(-dnorm(x), -x*dnorm(x))))


[Package stats version 4.4.0 Index]