Computes the numerical gradient of functions or the symbolic gradient of characters in arbitrary orthogonal coordinate systems.

gradient(
  f,
  var,
  params = list(),
  coordinates = "cartesian",
  accuracy = 4,
  stepsize = NULL,
  drop = TRUE
)

f %gradient% var

Arguments

f

array of characters or a function returning a numeric array.

var

vector giving the variable names with respect to which the derivatives are to be computed and/or the point where the derivatives are to be evaluated. See derivative.

params

list of additional parameters passed to f.

coordinates

coordinate system to use. One of: cartesian, polar, spherical, cylindrical, parabolic, parabolic-cylindrical or a vector of scale factors for each varibale.

accuracy

degree of accuracy for numerical derivatives.

stepsize

finite differences stepsize for numerical derivatives. It is based on the precision of the machine by default.

drop

if TRUE, return the gradient as a vector and not as an array for scalar-valued functions.

Value

Gradient vector for scalar-valued functions when drop=TRUE, array otherwise.

Details

The gradient of a scalar-valued function \(F\) is the vector \((\nabla F)_i\) whose components are the partial derivatives of \(F\) with respect to each variable \(i\). The gradient is computed in arbitrary orthogonal coordinate systems using the scale factors \(h_i\):

$$(\nabla F)_i = \frac{1}{h_i}\partial_iF$$

When the function \(F\) is a tensor-valued function \(F_{d_1,\dots,d_n}\), the gradient is computed for each scalar component. In particular, it becomes the Jacobian matrix for vector-valued function.

$$(\nabla F_{d_1,\dots,d_n})_i = \frac{1}{h_i}\partial_iF_{d_1,\dots,d_n}$$

Functions

  • f %gradient% var: binary operator with default parameters.

References

Guidotti E (2022). "calculus: High-Dimensional Numerical and Symbolic Calculus in R." Journal of Statistical Software, 104(5), 1-37. doi:10.18637/jss.v104.i05

See also

Other differential operators: curl(), derivative(), divergence(), hessian(), jacobian(), laplacian()

Examples

### symbolic gradient 
gradient("x*y*z", var = c("x", "y", "z"))
#> [1] "y * z" "x * z" "x * y"

### numerical gradient in (x=1, y=2, z=3)
f <- function(x, y, z) x*y*z
gradient(f = f, var = c(x=1, y=2, z=3))
#> [1] 6 3 2

### vectorized interface
f <- function(x) x[1]*x[2]*x[3]
gradient(f = f, var = c(1, 2, 3))
#> [1] 6 3 2

### symbolic vector-valued functions
f <- c("y*sin(x)", "x*cos(y)")
gradient(f = f, var = c("x","y"))
#>      [,1]         [,2]           
#> [1,] "y * cos(x)" "sin(x)"       
#> [2,] "cos(y)"     "-(x * sin(y))"

### numerical vector-valued functions
f <- function(x) c(sum(x), prod(x))
gradient(f = f, var = c(0,0,0))
#>      [,1] [,2] [,3]
#> [1,]    1    1    1
#> [2,]    0    0    0

### binary operator
"x*y^2" %gradient% c(x=1, y=3)
#> [1] 9 6