10

I would like to find numerical derivatives of a bivariate function.

  • The function is defined by myself
  • I need first derivatives with respect to each argument and cross second derivative

Is there a package or built-in function to do this?

user67275
  • 1
  • 9
  • 38
  • 64

1 Answers1

17

Install and load the numDeriv package.

library(numDeriv)
f <- function(x) {
    a <- x[1]; b <- x[2]; c <- x[3]
    sin(a^2*(abs(cos(b))^c))
}
grad(f,x=1:3)
## [1]  0.14376097  0.47118519 -0.06301885
hessian(f,x=1:3)
##            [,1]       [,2]        [,3]
## [1,]  0.1422651  0.9374675 -0.12538196
## [2,]  0.9374675  1.8274058 -0.25388515
## [3,] -0.1253820 -0.2538852  0.05496226

(My example is trivariate rather than bivariate, but it will obviously work for a bivariate function as well.) See the help pages for more information on how the gradient and especially Hessian computations are done.

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453