grback.Rdgrback computes the backward difference approximation to the gradient of
user function userfn.
grback(par, userfn, fbase=NULL, env=optsp, ...)parameters to the user objective function userfn
User-supplied objective function
The value of the function at the parameters, else NULL. This is to save recomputing the function at this point.
Environment for scratchpad items (like deps for approximation
control in this routine). Default optsp.
optional arguments passed to the objective function.
| Package: | grback |
| Depends: | R (>= 2.6.1) |
| License: | GPL Version 2. |
grback returns a single vector object df which approximates the
gradient of userfn at the parameters par. The approximation is controlled by a
global value optderiveps that is set when the package is attached.
cat("Example of use of grback\n")
#> Example of use of grback
myfn<-function(xx, shift=100){
ii<-1:length(xx)
result<-shift+sum(xx^ii)
}
xx<-c(1,2,3,4)
ii<-1:length(xx)
print(xx)
#> [1] 1 2 3 4
gn<-grback(xx,myfn, shift=0)
print(gn)
#> [1] 1.000000 3.999998 26.999973 255.999616
ga<-ii*xx^(ii-1)
cat("compare to analytic gradient:\n")
#> compare to analytic gradient:
print(ga)
#> [1] 1 4 27 256
cat("change the step parameter to 1e-4\n")
#> change the step parameter to 1e-4
optsp$deps <- 1e-4
gn2<-grback(xx,myfn, shift=0)
print(gn2)
#> [1] 1.0000 3.9998 26.9973 255.9616