Skip to contents

derivative() takes the first derivative of a single-variable function by central difference; gradient() and hessian() take the gradient and the Hessian matrix of a function of a parameter vector. All three are the ported Numerics NumericalDerivative routines.

Usage

derivative(f, x, step_size = NULL)

gradient(f, x)

hessian(f, x)

Arguments

f

for derivative(), a function taking one number and returning one number; for gradient() and hessian(), a function taking a numeric vector and returning one number.

x

the point to differentiate at: one number for derivative(), a numeric vector for gradient() and hessian().

step_size

the finite-difference step for derivative(). NULL, the default, leaves the ported routine's own step selection in force, as does any value at or below zero: the adaptive step eps^(1/2) * (1 + |x|).

Value

derivative() returns a single number, gradient() a numeric vector the length of x, and hessian() a square symmetric matrix.

Note

gradient() and hessian() share their names with functions in numDeriv and pracma, so whichever of those packages is attached last masks this one (and its arguments differ). The examples below qualify every call with corehydror:: so it is unambiguous which function is being called.

Examples

corehydror::derivative(function(x) x^3, 2)
#> [1] 12
rosenbrock <- function(p) (1 - p[1])^2 + 100 * (p[2] - p[1]^2)^2
corehydror::gradient(rosenbrock, c(1, 1))
#> [1]  1.600000e-07 -1.110225e-14
corehydror::hessian(rosenbrock, c(1, 1))
#>      [,1] [,2]
#> [1,]  802 -400
#> [2,] -400  200