How can I minimize this function in R?

267 views Asked by At

I'm attempting to write a formula that will determine a value of a that minimizes the function output myfun (i.e. a-fptotal). MWE:

c <- as.matrix(c(.25,.5,.25))
d <- as.matrix(c(10000,12500,15000))
e <- 700
f <- 1.1
tr <- .30

myfun <- function(a) {
   b <- max(a-e,0)
   df <- data.frame(u1=c(c*b*.40),u2=c(c*b*.60))
   df$year <- 1:nrow(df)
   df$factor <- 1/(f)^df$year
   df$d <- d
   df$t <- (df$d-df$u1-df$u2)*tr
   df$f <- df$d-df$t
   df$fp <- df$f*df$factor
   fptotal <- sum(df$fp)
   return(a-fptotal) # what is a good approach to minimize this?
}

I've tried things like this without any success:

o2 <- optimize(myfun, lower = 0, upper = 30000)

The correct answer should be around 28355:

myfun(28355)  
## [1] -1.04151

Any thoughts are appreciated. Thank you!

1

There are 1 answers

1
Ben Bolker On BEST ANSWER

I think you want to minimize the square of a-fptotal ...

ff <- function(x) myfun(x)^2
> optimize(ff,lower=0,upper=30000)
$minimum
[1] 28356.39

$objective
[1] 1.323489e-23

Or find the root (i.e. where myfun(x)==0):

uniroot(myfun,interval=c(0,30000))
$root
[1] 28356.39

$f.root
[1] 1.482476e-08

$iter
[1] 4

$init.it
[1] NA

$estim.prec
[1] 6.103517e-05