Use splitfngr with nlminb
nlminb_share.RdUse nlminb function but pass in a single function that returns both the function and gradient together in a list. Useful when the function and gradient are expensive to calculate and can be calculated faster together than separate.
Examples
quad_share <- function(x){list(sum(x^4), 4*x^3)}
nlminb_share(start=c(3, -5), fngr=quad_share)
#> $par
#> [1] 1.083723e-12 -1.083081e-12
#>
#> $objective
#> [1] 2.755427e-48
#>
#> $convergence
#> [1] 0
#>
#> $iterations
#> [1] 124
#>
#> $evaluations
#> function gradient
#> 132 125
#>
#> $message
#> [1] "relative convergence (4)"
#>
if (FALSE) { # \dontrun{
# Add a sleep amount to show when it can be faster
# Using share
quad_fngr <- function(x){Sys.sleep(.01); list(sum(x^4), 4*x^3)}
system.time(nlminb_share(start=c(3, -5), fngr=quad_fngr))
# Without share
quad_fn <- function(x) {Sys.sleep(.01); sum(x^4)}
quad_gr <- function(x) {Sys.sleep(.01); 4*x^3}
system.time(nlminb(c(3,-5), quad_fn, quad_gr))
} # }