gradient_scalar: Gradient of a scalar field in R^n
Description
Computes a numerical approximation of the gradient of a scalar function
at a given point using central finite differences. The function f
is assumed to take a numeric vector as input and return a scalar.
Usage
gradient_scalar(f, x0, h = NULL, plot = FALSE)
Value
A numeric vector of the same length as x0 with the
components of the gradient.
Arguments
f
Function of a numeric vector f(x) returning a numeric scalar.
x0
Numeric vector giving the evaluation point.
h
Numeric step size for finite differences. Can be:
NULL (default): a step is chosen as 1e-4 * (1 + abs(x0)) for each component;
A scalar, used for all components;
A numeric vector of the same length as x0.
plot
Logical; if TRUE and length(x0) is 2 or 3,
draws the gradient vector with plotly.
Details
Optionally, if the input point has length 2 or 3 and plot = TRUE,
a simple visualization of the gradient vector is produced using
plotly.