George
George

Reputation: 64

Minimum value of function

How can I find out the minimum value that can be returned by a function with infinite domain in R?

f <- function(x) { x^2-1 }
print(minVal(f))   # -1

f <- function(x) { x^2+1 }
print(minVal(f))   # 1

So far I've tried optimize, but it requires a finite interval:

minVal <- function(f) {
  optimize(f, c(-100, 100))
}

Upvotes: 0

Views: 250

Answers (2)

Ben Bolker
Ben Bolker

Reputation: 226192

As well as nlm, you could try

optim(fn=function(x) x^2 -1, par = 1, method="BFGS")

This happens to work with a starting value of 1 or 1000 (although numerical accuracy can almost never be guaranteed for general nonlinear minimization).

This will work even better if you specify the gradient explicitly:

optim(fn=function(x) x^2 -1, gr=function(x) 2*x, par = 1, method="BFGS")

Based on some quick experiment, this seems to give the correct answer for starting values between -10^7 and 10^7.

Upvotes: 2

LMc
LMc

Reputation: 18642

Have you tried the nlm function?

nlm(function(x) x^2 -1, p = 1E3)

$minimum
[1] -1

$estimate
[1] -2.499974e-10

$gradient
[1] 9.995338e-07

$code
[1] 1

$iterations
[1] 1

p is a starting value for minimization that is required.

Upvotes: 3

Related Questions