Learn R Programming

SpatioTemporal (version 0.9.2)

gen.gradient: Compute Finite Difference Gradient and Hessians.

Description

Computes finite difference gradient and/or hessian. gen.gradient function does forward, backward or central differences, the gen.hessian function uses only central differences.

Usage

gen.gradient(x, func, h = 0.001, diff.type = 0)

gen.hessian(x, func, h = 0.001)

Arguments

x
Point at which to compute the gradient or hessian.
func
A function that takes only x as an input argument. Use function(x){my.func(x,other.input)} to create a temporary function, see the example.
h
Step length for the finite difference.
diff.type
Type of finite difference, positive values gives forward differences, 0 gives central differences, and negative values gives backward differences.

Value

  • gen.gradient returns the gradient as a vector. gen.hessian returns the hessian matrix.

encoding

latin1

See Also

Used by loglike.grad, loglike.hessian, loglike.naive.grad, and loglike.naive.hessian.

Examples

Run this code
#create a two variable function
f.test <- function(x){sin(x[1])*cos(x[2])}

#compute the gradient using forward difference
gen.gradient(c(.5,.5), f.test, diff.type=1)
#and central difference
gen.gradient(c(.5,.5), f.test, diff.type=0)
#compared to the true value
c(cos(.5)*cos(.5),-sin(.5)*sin(.5))

#Compute the Hessian
gen.hessian(c(.5,.5), f.test, h=1e-4)
#and compare to the true value
matrix(c(-sin(.5)*cos(.5),-cos(.5)*sin(.5),
         -cos(.5)*sin(.5),-sin(.5)*cos(.5)),2,2)
if( max(abs(gen.gradient(c(.5,.5), f.test, h=1e-5, diff.type=0) -
            c(cos(.5)*cos(.5),-sin(.5)*sin(.5)))) > 1e-10 ){
  stop("gen.gradient, diff.type=0: Results not equal")
}
if( max(abs(gen.gradient(c(.5,.5), f.test, h=1e-5, diff.type=1) -
            c(cos(.5)*cos(.5),-sin(.5)*sin(.5)))) > 1e-5 ){
  stop("gen.gradient, diff.type=1: Results not equal")
}
if( max(abs(gen.gradient(c(.5,.5), f.test, h=1e-5, diff.type=-1) -
            c(cos(.5)*cos(.5),-sin(.5)*sin(.5)))) > 1e-5 ){
  stop("gen.gradient, diff.type=-1: Results not equal")
}
if( max(abs(gen.hessian(c(.5,.5), f.test, h=1e-4) -
        matrix(c(-sin(.5)*cos(.5),-cos(.5)*sin(.5),
               -cos(.5)*sin(.5),-sin(.5)*cos(.5)),2,2))) > 1e-5 ){
  stop("gen.hessian: Results not equal")
}

Run the code above in your browser using DataLab