grad.func: Returns the gradient of a function at a specific point in its...

View source: R/grad.func.R

grad.funcR Documentation

Returns the gradient of a function at a specific point in its domain.

Description

Returns the vector gradient, \nabla f, of a function, f(\vec{r}), at aspecific point, \vec{r} = \vec{r}_o, in its domain, once the tolerance, \epsilon, for the calculation of the gradient has been provided.
Mathematically speaking, the function returns the expression shown below.

\nabla f(\vec{r})\bigg|_{\vec{r} = \vec{r}_o}

Usage

grad.func(f, pt, epsilon)

Arguments

f

The function, f(\vec{r}) = f(x_1, x_2, \dots , x_n), for which you need to calculate the gradient.
The function f has to return a numeric scalar.
The function should only have a single argument, which is the vector of the independent variables of the function. i.e. please use f(\vec{r}) and not f(x_1, x_2, \dots , x_n) for your function definition.
Please see Examples.

pt

The point, \vec{r}_o, in the domain of the function where the gradient needs to be calculated.
This has to be a numeric vector whose length is equal to the vector which is the argument of the function. i.e. the size of the vectors \vec{r} and \vec{r}_o should match.

epsilon

This epsilon or \epsilon is the perturbation which will be used to numerically estimate the gradient.
The derivative is calculated using partials for example as shown below.

\partial f/\partial x_1 = \left\{\,\, f(x_1 + \epsilon, x_2, \dots) - f(x_1 - \epsilon, x_2, \dots)\,\,\right\}/2\epsilon


The value of \epsilon should be chosen wisely. Please see Details.

Details

The value of epsilon, \epsilon, should be chosen wisely, depending on context.
The rate of rise or fall of the function between f(x_1 + \epsilon, \dots) and f(x_1 - \epsilon, \dots) should be considered.
See example below.

#build the function
expfun <- function(X){
  return(2*X^12)
}

#call grad.func
grad.func(f = expfun, pt = 2*10^-9, epsilon = 10^-6)
grad.func(f = expfun, pt = 2*10^-9, epsilon = 10^-15)

#output
> grad.func(f = expfun, pt = 2*10^-9, epsilon = 10^-6)
[1] 4.800352e-68
> grad.func(f = expfun, pt = 2*10^-9, epsilon = 10^-15)
[1] 4.9152e-95

The exact answer is 4.9152 \times 10^{-95}, but \epsilon = 10^{-6} is too large for a highly increasing function like f(x) = 2x^{12}.

Value

The returned value, \nabla f, is always a vector whose length is equal to the length of the argument pt or \vec{r}_o

Author(s)

Chitran Ghosal

References

https://en.wikipedia.org/wiki/Gradient
https://math.stackexchange.com/questions/2744497/what-does-gradient-actually-mean

Examples

##define the paraboloid function centered at (3,5)
para <- function(p){
  return( (p[1] - 3)^2 + (p[2] - 5)^2)
}

#call the grad.func functions
grad.func(f=para, pt = c(3,5), epsilon = 10^-1)
grad.func(f=para, pt = c(0,0), epsilon = 10^-1)

Chitran1987/StatsChitran documentation built on Feb. 23, 2025, 8:30 p.m.