gradient: Gradient by numerical approximation

Description Usage Arguments Value References Examples

View source: R/gradient.R

Description

gradient is a function based on the algorithm of numerical differentiation for estimating the gradient using finite difference approximations.

Usage

1
gradient(f, x, fx = NULL, dx = 1e-06, method = c("ffd", "cfd"))

Arguments

f

A function, representing the objective function.

x

A number or vector with length n, indicating the current point.

fx

A number, the objective value calculated at x.

dx

A number, the small perturbation in x.

method

character string, specifying the discretization method.
"ffd": Forward finite differences. Requires n+1 evaluations (or n if fx is provided)
"cfd": Central (or Symmetrical) finite differences. Requires 2n evaluations (fx is not used)

Value

df the numerical approximation of the gradient.

References

  1. Wikipedia, Numerical differentiation, https://en.wikipedia.org/wiki/Numerical_differentiation.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
## Not run: 
f <- function(x) {return ( sum(x^2) )}
df_analytical <- function (x) {return (2*x)}
x <- c(1,1) #current point
gradient(f, x) #uses ffd by default
gradient(f, x, method = "cfd")
df_analytical(x)

x <- seq(1,100)
dfx_analytical <- df_analytical(x)
dfx_ffd <- gradient(f, x, method = "ffd")
dfx_cfd <- gradient(f, x, method = "cfd")
norm(dfx_analytical - dfx_ffd, type = "2") #error in the FFD approximation
norm(dfx_analytical - dfx_cfd, type = "2") #error in the CFD approximation

## End(Not run)

brunasqz/NonlinearOpMethods documentation built on Oct. 27, 2019, 5:46 a.m.