Skip to content

Instantly share code, notes, and snippets.

@dirkschumacher
Last active October 20, 2021 17:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dirkschumacher/fb7b20a133fbbd9e32271f20e0e6dc98 to your computer and use it in GitHub Desktop.
Save dirkschumacher/fb7b20a133fbbd9e32271f20e0e6dc98 to your computer and use it in GitHub Desktop.
# License GPL 2
library(armacmp)
# from the R docs of optim
fr <- function(x) { ## Rosenbrock Banana function
x1 <- x[1]
x2 <- x[2]
return(100 * (x2 - x1 * x1)^2 + (1 - x1)^2)
}
grr <- function(x = type_colvec()) { ## Gradient of 'fr'
x1 <- x[1L]
x2 <- x[2L]
x[1L] <- -400 * x1 * (x2 - x1 * x1) - 2 * (1 - x1)
x[2L] <- 200 * (x2 - x1 * x1)
return(x)
}
optim(matrix(c(-1.2, 1), ncol = 1), fr, grr, method = "L-BFGS-B")
#> $par
#> [,1]
#> [1,] 0.9999997
#> [2,] 0.9999995
#>
#> $value
#> [1] 2.267791e-13
#>
#> $counts
#> function gradient
#> 47 47
#>
#> $convergence
#> [1] 0
#>
#> $message
#> [1] "CONVERGENCE: REL_REDUCTION_OF_F <= FACTR*EPSMCH"
# using ensmallen, this call compiles everything to c++ and
# uses ensmallen's implementation of L-BFGS to minimize it
rosenbrock_solver <- compile_optimization_problem(
evaluate = fr,
gradient = grr,
optimizer = optimizer_L_BFGS()
)
rosenbrock_solver(matrix(c(-1.2, 1), ncol = 1))
#> [,1]
#> [1,] 1
#> [2,] 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment