gradient: Compute the gradient of a scalar-valued function

View source: R/derivatives.R

gradientR Documentation

Compute the gradient of a scalar-valued function

Description

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

Usage

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.

Details

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

Value

A numeric vector of length p containing the gradient.

Examples

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

nabla documentation built on Feb. 11, 2026, 1:06 a.m.