CC This work is licensed under the Creative Commons Attribution 4.0 International License. For questions please contact Michael Hahsler.

Minimization for convex data

fn <- function(x) -1 * dnorm(x, mean = 50, sd = 40)

x <- seq(1, 100, length.out = 1000)
plot(x, fn(x), type = "l")

Optimize (minimize)

o <- optim(fn = fn, par = 0, lower=0, upper = 100, method = "Brent")
plot(x, fn(x), type = "l")
points(o$par, o$value, col = "red")

Minimize a function with local

fn <- function(x) -1 * (dnorm(x, mean = 50, sd = 40) + .001 * sin(x))

x <- seq(1, 100, length.out = 1000)
plot(x, fn(x), type = "l")

Optimize (minimize)

o <- optim(fn = fn, par = 0, lower=0, upper = 100, method = "Brent")
o
## $par
## [1] 45.58048
## 
## $value
## [1] -0.01091249
## 
## $counts
## function gradient 
##       NA       NA 
## 
## $convergence
## [1] 0
## 
## $message
## NULL

Note: Be careful with local optima! Brent’s method uses golden selection search and thus still can find a good solution.

plot(x, fn(x), type = "l")
points(o$par, o$value, col = "red")