Evaluates the gradient of f at x using forward-mode AD. Equivalent to D(f, x) for scalar-valued f.

gradient(f, x)

Arguments

f

A function taking a parameter vector (numeric or dual) and returning a scalar. Parameters are accessed via x[i].

x

A numeric vector of parameter values.

Value

A numeric vector of length p containing the gradient.

Details

The function should use x[1], x[2], etc. to access parameters. This is compatible with the standard R convention used by optim.

Examples

f <- function(x) -(x[1] - 3)^2 - (x[2] - 5)^2
gradient(f, c(1, 2))  # c(4, 6)
#> [1] 4 6